diff --git a/README.md b/README.md index 1c01e59a..cbfb551c 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,20 @@ # ezyfox-server EzyFox Server -#Synopsis +# Synopsis -#Code Example +# Code Example -#Motivation +# Motivation -#API Reference +# API Reference -#Tests +# Tests mvn test -#Contributors +# Contributors -#License +# License - Apache License, Version 2.0 diff --git a/build.sh b/build.sh new file mode 100755 index 00000000..bfe70853 --- /dev/null +++ b/build.sh @@ -0,0 +1,33 @@ +mvn clean install +mvn clean install -f ezyfox-server-util +mvn clean install -f ezyfox-server-io +mvn clean install -f ezyfox-server-concurrent +mvn clean install -f ezyfox-server-security +mvn clean install -f ezyfox-server-common +mvn clean install -f ezyfox-server-binding +mvn clean install -f ezyfox-server-bean +mvn clean install -f ezyfox-server-mapping +mvn clean install -f ezyfox-server-codec +mvn clean install -f ezyfox-server-core +mvn clean install -f ezyfox-server-databridge +mvn clean install -f ezyfox-server-webapi +mvn clean install -f ezyfox-server-httpserver +mvn clean install -f ezyfox-server-boot +mvn clean install -f ezyfox-server-netty +mvn clean install -f ezyfox-server-nio +mvn clean install -f ezyfox-server-jackson +mvn clean install -f ezyfox-server-msgpack +mvn clean install -f ezyfox-server-sfs2x +mvn clean install -f ezyfox-server-nettycodec +mvn clean install -f ezyfox-server-niocodec +mvn clean install -f ezyfox-server-database +mvn clean install -f ezyfox-server-mongodb +mvn clean install -f ezyfox-server-morphia +mvn clean install -f ezyfox-server-hazelcast +mvn clean install -f ezyfox-server-hazelcast-mongodb +mvn clean install -f ezyfox-server-hazelcast-morphia +mvn clean install -f ezyfox-server-hazelcast-bean +mvn clean install -f ezyfox-server-monitor +mvn clean install -f ezyfox-server-admintools +mvn clean install -f ezyfox-server-nettyrunner +mvn clean install -f ezyfox-server-niorunner \ No newline at end of file diff --git a/ezyfox-server-admintools/.tern-project b/ezyfox-server-admintools/.tern-project new file mode 100644 index 00000000..f030bd16 --- /dev/null +++ b/ezyfox-server-admintools/.tern-project @@ -0,0 +1,17 @@ +{ + "plugins": { + "guess-types": { + + }, + "outline": { + + }, + "angular": { + + } + }, + "libs": [ + "ecma5", + "browser" + ] +} \ No newline at end of file diff --git a/ezyfox-server-admintools/pom.xml b/ezyfox-server-admintools/pom.xml new file mode 100644 index 00000000..26a1a16b --- /dev/null +++ b/ezyfox-server-admintools/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-admintools + 1.0.0 + war + + ezyfox-server-admintools + http://maven.apache.org + + + 1.0.0 + 1.0.0 + 4.3.8.RELEASE + 2.5.10.1 + 5.2.10.Final + 2.1.1 + 6.0.6 + + + + + com.tvd12 + ezyfox-server-mongodb + ${ezy.mongodb.version} + + + com.tvd12 + ezyfox-server-hazelcast + ${ezy.hazelcast.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-context-support + ${spring.version} + + + org.springframework + spring-orm + ${spring.version} + jar + compile + + + + org.apache.struts + struts2-core + ${struts.version} + + + org.apache.struts + struts2-spring-plugin + ${struts.version} + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + + org.apache.commons + commons-dbcp2 + ${commons.dbcp2.version} + + + + mysql + mysql-connector-java + ${mysqlconnector.version} + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + javax.servlet.jsp.jstl + jstl-api + 1.2 + provided + + + + + src/main/java + + + maven-war-plugin + 2.4 + + src/main/webapp + false + + + + + + diff --git a/ezyfox-server-admintools/sql/create_product_table.sql b/ezyfox-server-admintools/sql/create_product_table.sql new file mode 100644 index 00000000..72048fc0 --- /dev/null +++ b/ezyfox-server-admintools/sql/create_product_table.sql @@ -0,0 +1,9 @@ +USE `test`; + +CREATE TABLE `product` ( + `product_id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(128) NOT NULL, + `description` varchar(512) NOT NULL, + `price` float NOT NULL, + PRIMARY KEY (`product_id`) +) \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/HomeAction.java b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/HomeAction.java new file mode 100644 index 00000000..cef74543 --- /dev/null +++ b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/HomeAction.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.adt.action; + +import com.opensymphony.xwork2.ActionSupport; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyMaxIdService; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class HomeAction extends ActionSupport { + private static final long serialVersionUID = -5885995144592628588L; + + private String random = "random"; + + @Getter(AccessLevel.NONE) + private transient EzyMaxIdService maxIdService; + + @Override + public String execute() throws Exception { + setRandom(String.valueOf(maxIdService.incrementAndGet("count"))); + return SUCCESS; + } + +} diff --git a/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/ListProductAction.java b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/ListProductAction.java new file mode 100644 index 00000000..68c2052a --- /dev/null +++ b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/action/ListProductAction.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.adt.action; + +import java.util.List; + +import com.opensymphony.xwork2.ActionSupport; +import com.tvd12.ezyfoxserver.adt.dao.ProductDAO; +import com.tvd12.ezyfoxserver.adt.model.Product; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class ListProductAction extends ActionSupport { + private static final long serialVersionUID = 8858337894805627088L; + + private ProductDAO productDAO; + private List products; + + public String execute() { + products = productDAO.list(); + return SUCCESS; + } +} diff --git a/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/ProductDAO.java b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/ProductDAO.java new file mode 100644 index 00000000..30af0a31 --- /dev/null +++ b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/ProductDAO.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.adt.dao; + +/** + * Copyright CodeJava.net To Present + * All rights reserved. + */ +import java.util.List; + +import com.tvd12.ezyfoxserver.adt.model.Product; + +public interface ProductDAO { + + List list(); + +} diff --git a/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/impl/ProductDAOImpl.java b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/impl/ProductDAOImpl.java new file mode 100644 index 00000000..64162d62 --- /dev/null +++ b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/dao/impl/ProductDAOImpl.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.adt.dao.impl; + +/** + * Copyright CodeJava.net To Present + * All rights reserved. + */ +import java.util.List; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.transaction.Transactional; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; + +import com.tvd12.ezyfoxserver.adt.dao.ProductDAO; +import com.tvd12.ezyfoxserver.adt.model.Product; + +public class ProductDAOImpl implements ProductDAO { + + private SessionFactory sessionFactory; + + public ProductDAOImpl(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + @Transactional + @Override + public List list() { + CriteriaQuery query = + createQuery().distinct(true); + query.from(Product.class); + return getCurrentSession().createQuery(query).list(); + } + + private Session getCurrentSession() { + return sessionFactory.getCurrentSession(); + } + + private CriteriaBuilder getCriteriaBuilder() { + return getCurrentSession().getCriteriaBuilder(); + } + + private CriteriaQuery createQuery() { + return getCriteriaBuilder().createQuery(Product.class); + } +} diff --git a/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/model/Product.java b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/model/Product.java new file mode 100644 index 00000000..2a089344 --- /dev/null +++ b/ezyfox-server-admintools/src/main/java/com/tvd12/ezyfoxserver/adt/model/Product.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.adt.model; + +import lombok.Getter; +import lombok.Setter; + +/** + * Copyright CodeJava.net To Present + * All rights reserved. + */ +@Getter +@Setter +public class Product { + private long id; + private String name; + private String description; + private float price; +} diff --git a/ezyfox-server-admintools/src/main/resources/hibernate.cfg.xml b/ezyfox-server-admintools/src/main/resources/hibernate.cfg.xml new file mode 100644 index 00000000..9fd8cbc0 --- /dev/null +++ b/ezyfox-server-admintools/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,12 @@ + + + + + + org.hibernate.dialect.MySQLDialect + true + + + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/resources/hibernate/mapping/product.hbm.xml b/ezyfox-server-admintools/src/main/resources/hibernate/mapping/product.hbm.xml new file mode 100644 index 00000000..247cbd5c --- /dev/null +++ b/ezyfox-server-admintools/src/main/resources/hibernate/mapping/product.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + diff --git a/ezyfox-server-admintools/src/main/resources/struts.xml b/ezyfox-server-admintools/src/main/resources/struts.xml new file mode 100644 index 00000000..37eb0333 --- /dev/null +++ b/ezyfox-server-admintools/src/main/resources/struts.xml @@ -0,0 +1,25 @@ + + + + + + + + /WEB-INF/views/jsp/home.jsp + + + + /WEB-INF/views/ftl/home.ftl + + + + /WEB-INF/views/vm/home.vm + + + + /WEB-INF/views/jsp/list_product.jsp + + + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/webapp/META-INF/MANIFEST.MF b/ezyfox-server-admintools/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 00000000..5e949512 --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/ezyfox-server-admintools/src/main/webapp/WEB-INF/spring/app-context.xml b/ezyfox-server-admintools/src/main/webapp/WEB-INF/spring/app-context.xml new file mode 100644 index 00000000..0f7a55c2 --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/WEB-INF/spring/app-context.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + localhost + 27017 + root + 123456 + test + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/ftl/home.ftl b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/ftl/home.ftl new file mode 100644 index 00000000..dc8908f2 --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/ftl/home.ftl @@ -0,0 +1,14 @@ + + + + + Home + + + +
+

${random}

+
+ + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/home.jsp b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/home.jsp new file mode 100644 index 00000000..5a6f396f --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/home.jsp @@ -0,0 +1,16 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="s" uri="/struts-tags" %> + + + + +Home + + +
+ +
+ + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/list_product.jsp b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/list_product.jsp new file mode 100644 index 00000000..a7c284d5 --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/jsp/list_product.jsp @@ -0,0 +1,31 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<%@ taglib prefix="s" uri="/struts-tags" %> + + + + +Product List + + +
+ + + + + + + + + + + + + + + +
NoProduct NameDescriptionPrice
+
+ + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/vm/home.vm b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/vm/home.vm new file mode 100644 index 00000000..99d40d75 --- /dev/null +++ b/ezyfox-server-admintools/src/main/webapp/WEB-INF/views/vm/home.vm @@ -0,0 +1,6 @@ + +Home + +

${random}

+ + + + + ezyfox server admintools + + + contextConfigLocation + /WEB-INF/spring/app-context.xml + + + + org.springframework.web.context.ContextLoaderListener + + + + DispatcherFilter + org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter + + + + DispatcherFilter + /* + + \ No newline at end of file diff --git a/ezyfox-server-admintools/src/test/resources/AllTests.tng.xml b/ezyfox-server-admintools/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-admintools/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-bean/assembly.xml b/ezyfox-server-bean/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-bean/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-bean/pom.xml b/ezyfox-server-bean/pom.xml new file mode 100644 index 00000000..34107c42 --- /dev/null +++ b/ezyfox-server-bean/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-bean + 1.0.0 + ezyfox-server-bean + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + \ No newline at end of file diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanConfig.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanConfig.java new file mode 100644 index 00000000..6c6ba45e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanConfig.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyBeanConfig { + + void config(); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContext.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContext.java new file mode 100644 index 00000000..cea2480e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContext.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.Properties; + +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; + +public interface EzyBeanContext extends + EzyBeanFetcher, + EzySingletonFetcher, + EzyPrototypeFetcher, + EzyPropertyFetcher { + + Properties getProperties(); + EzySingletonFactory getSingletonFactory(); + EzyPrototypeFactory getPrototypeFactory(); + EzyBeanNameTranslator getBeanNameTranslator(); + + static EzyBeanContextBuilder builder() { + return EzySimpleBeanContext.builder(); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextAware.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextAware.java new file mode 100644 index 00000000..45d967cb --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyBeanContextAware { + + void setContext(EzyBeanContext context); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextBuilder.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextBuilder.java new file mode 100644 index 00000000..0c4e8ae7 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanContextBuilder.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.properties.EzyPropertiesReader; + +@SuppressWarnings("rawtypes") +public interface EzyBeanContextBuilder extends EzyBuilder { + + EzyBeanContextBuilder scan(String packageName); + + EzyBeanContextBuilder scan(String... packageNames); + + EzyBeanContextBuilder scan(Iterable packageNames); + + EzyBeanContextBuilder addSingleton(String name, Object singleton); + + EzyBeanContextBuilder addSingletonClass(Class clazz); + + EzyBeanContextBuilder addSingletonClasses(Class... classes); + + EzyBeanContextBuilder addSingletonClasses(Iterable classes); + + EzyBeanContextBuilder addPrototypeClass(Class clazz); + + EzyBeanContextBuilder addPrototypeClasses(Class... classes); + + EzyBeanContextBuilder addPrototypeClasses(Iterable classes); + + EzyBeanContextBuilder addPrototypeSupplier(String objectName, EzyPrototypeSupplier supplier); + + EzyBeanContextBuilder errorHandler(EzyErrorHandler handler); + + EzyBeanContextBuilder addProperties(Map properties); + + EzyBeanContextBuilder addProperty(String key, Object value); + + EzyBeanContextBuilder propertiesReader(EzyPropertiesReader propertiesReader); + +} \ No newline at end of file diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanFetcher.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanFetcher.java new file mode 100644 index 00000000..b12cdfda --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyBeanFetcher { + + Object getBean(Class type); + + Object getBean(String name, Class type); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslator.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslator.java new file mode 100644 index 00000000..fb707f8e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslator.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyBeanNameTranslator { + + String translate(String name, Class type); + + void map(String freename, Class type, String realname); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslatorAware.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslatorAware.java new file mode 100644 index 00000000..d0a9926e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyBeanNameTranslatorAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyBeanNameTranslatorAware { + + void setBeanNameTranslator(EzyBeanNameTranslator translator); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyErrorHandler.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyErrorHandler.java new file mode 100644 index 00000000..eecf4037 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyErrorHandler.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyErrorHandler { + + void handle(Throwable error); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPropertyFetcher.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPropertyFetcher.java new file mode 100644 index 00000000..e2120ee3 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPropertyFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyPropertyFetcher { + + boolean containsProperty(Object key); + + T getProperty(Object key, Class outType); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactory.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactory.java new file mode 100644 index 00000000..2fbaa48f --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactory.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.List; +import java.util.Map; + +@SuppressWarnings("rawtypes") +public interface EzyPrototypeFactory { + + EzyPrototypeSupplier getSupplier(String objectName, Class objectType); + + EzyPrototypeSupplier getSupplier(Map properties); + + List getSuppliers(Map properties); + + List getSuppliers(Class annoClass); + + Map getProperties(EzyPrototypeSupplier supplier); + + void addSupplier(EzyPrototypeSupplier supplier); + + void addSupplier(String objectName, EzyPrototypeSupplier supplier); + + void addSupplier(String objectName, EzyPrototypeSupplier supplier, Map properties); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactoryAware.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactoryAware.java new file mode 100644 index 00000000..51125e8f --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFactoryAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyPrototypeFactoryAware { + + void setPrototypeFactory(EzyPrototypeFactory factory); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFetcher.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFetcher.java new file mode 100644 index 00000000..fffe00f2 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeFetcher.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.List; +import java.util.Map; + +@SuppressWarnings("rawtypes") +public interface EzyPrototypeFetcher { + + T getPrototype(String name, Class type); + + T getPrototype(Map properties); + + List getPrototypes(Map properties); + + EzyPrototypeSupplier getPrototypeSupplier(Map properties); + + List getPrototypeSuppliers(Map properties); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeSupplier.java new file mode 100644 index 00000000..bf5156c7 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzyPrototypeSupplier.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzyPrototypeSupplier { + + Class getObjectType(); + + Object supply(EzyBeanContext context); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactory.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactory.java new file mode 100644 index 00000000..7e1a3963 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactory.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.List; +import java.util.Map; + +@SuppressWarnings("rawtypes") +public interface EzySingletonFactory { + + Object getSingleton(String name, Class type); + + Object getSingleton(Map properties); + + List getSingletons(Map properties); + + List getSingletons(Class annoClass); + + Map getProperties(Object singleton); + + Object addSingleton(Object singleton); + + Object addSingleton(String name, Object singleton); + + Object addSingleton(String name, Object singleton, Map properties); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactoryAware.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactoryAware.java new file mode 100644 index 00000000..3dee927f --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFactoryAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.bean; + +public interface EzySingletonFactoryAware { + + void setSingletonFactory(EzySingletonFactory factory); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFetcher.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFetcher.java new file mode 100644 index 00000000..f5211ba9 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/EzySingletonFetcher.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.bean; + +import java.util.List; +import java.util.Map; + +@SuppressWarnings("rawtypes") +public interface EzySingletonFetcher { + + T getSingleton(String name, Class type); + + T getSingleton(Map properties); + + List getSingletons(Map properties); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyAutoBind.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyAutoBind.java new file mode 100644 index 00000000..1fdb561c --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyAutoBind.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ + ElementType.FIELD, + ElementType.METHOD, + ElementType.CONSTRUCTOR +}) +public @interface EzyAutoBind { + + String[] value() default {}; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfiguration.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfiguration.java new file mode 100644 index 00000000..96d80384 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfiguration.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyConfiguration { + + int priority() default 0; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfigurationBefore.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfigurationBefore.java new file mode 100644 index 00000000..16e1daf5 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyConfigurationBefore.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyConfigurationBefore { + + int priority() default 0; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPackagesScan.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPackagesScan.java new file mode 100644 index 00000000..a21381cc --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPackagesScan.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates that a class configure which packages bean context need to load + * + * @author tavandung12 + * + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyPackagesScan { + + /** + * packages to load + * + * @return array of package names + */ + public String[] value(); +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPostInit.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPostInit.java new file mode 100644 index 00000000..99e6b087 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPostInit.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +@Target({ + ElementType.METHOD +}) +public @interface EzyPostInit { + + String[] value() default ""; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPrototype.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPrototype.java new file mode 100644 index 00000000..8ac9954a --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzyPrototype.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) +public @interface EzyPrototype { + + String value() default ""; + + EzyKeyValue[] properties() default {}; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzySingleton.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzySingleton.java new file mode 100644 index 00000000..addda015 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/annotation/EzySingleton.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) +public @interface EzySingleton { + + String value() default ""; + + EzyKeyValue[] properties() default {}; + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzyNewSingletonException.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzyNewSingletonException.java new file mode 100644 index 00000000..30dceebd --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzyNewSingletonException.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.bean.exception; + +import com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey; + +import lombok.Getter; + +@Getter +public class EzyNewSingletonException extends IllegalStateException { + private static final long serialVersionUID = -1494071992523176740L; + + private final String errorBeanName; + private final Class errorClass; + private final Class singletonClass; + + public EzyNewSingletonException( + Class singletonClass, Class errorClass, String errorBeanName) { + super( + "can't load singleton of class " + + singletonClass.getSimpleName() + + ", can't set (" + errorBeanName + ", " + errorClass.getSimpleName() + ")" + ); + this.errorClass = errorClass; + this.singletonClass = singletonClass; + this.errorBeanName = errorBeanName; + } + + public final EzyBeanKey getErrorKey() { + return EzyBeanKey.of(getErrorBeanName(), getErrorClass()); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzySingletonException.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzySingletonException.java new file mode 100644 index 00000000..2ad7c2f7 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/exception/EzySingletonException.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.exception; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey; + +public class EzySingletonException extends IllegalStateException { + private static final long serialVersionUID = 814337130118800149L; + + public EzySingletonException(String msg) { + super(msg); + } + + public static EzySingletonException + implementationNotFound(EzyBeanKey key, Set> uncompleted) { + StringBuilder message = new StringBuilder("bean ") + .append(key) + .append(" implementation not found, uncompleted classes: ") + .append(uncompleted); + return new EzySingletonException(message.toString()); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanKey.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanKey.java new file mode 100644 index 00000000..e7ce9dc6 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanKey.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.io.Serializable; + +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; + +import lombok.Getter; + +@Getter +public class EzyBeanKey implements Serializable { + private static final long serialVersionUID = -2376464316946102262L; + + protected String name; + protected Class type; + + public EzyBeanKey(String name, Class type) { + this.name = name; + this.type = type; + } + + public static EzyBeanKey of(String name, Class type) { + return new EzyBeanKey(name, type); + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(o -> o.name) + .function(o -> o.type) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .append(name, type) + .toHashCode(); + } + + @Override + public String toString() { + return "(" + name + "," + type.getSimpleName() + ")"; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanNameParser.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanNameParser.java new file mode 100644 index 00000000..a8abcd81 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyBeanNameParser.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +public final class EzyBeanNameParser { + + private EzyBeanNameParser() { + } + + public static String getBeanName(Class clazz) { + if(clazz.isAnnotationPresent(EzySingleton.class)) + return getSingletonName(clazz); + if(clazz.isAnnotationPresent(EzyPrototype.class)) + return getPrototypeName(clazz); + return EzyClasses.getVariableName(clazz); + } + + // ============== parse singleton ================== + public static String getSingletonName(EzyField field) { + return getSingletonName(field.getAnnotation(EzySingleton.class), field.getName()); + } + + public static String getSingletonName(EzyMethod method) { + return getSingletonName(method.getAnnotation(EzySingleton.class), method.getFieldName()); + } + + public static String getSingletonName(Class clazz) { + return getSingletonName(clazz, clazz.getAnnotation(EzySingleton.class)); + } + + public static String getSingletonName(Class clazz, EzySingleton annotation) { + return getSingletonName(annotation, EzyClasses.getVariableName(clazz, "Impl")); + } + + public static String getSingletonName(EzySingleton annotation, String defaultName) { + if(annotation == null) + return defaultName; + if(StringUtils.isEmpty(annotation.value())) + return defaultName; + return annotation.value(); + } + + // ============ parse prototype ========== + public static String getPrototypeName(EzyField field) { + return getPrototypeName(field.getAnnotation(EzyPrototype.class), field.getName()); + } + + public static String getPrototypeName(EzyMethod method) { + return getPrototypeName(method.getAnnotation(EzyPrototype.class), method.getFieldName()); + } + + public static String getPrototypeName(Class clazz) { + return getPrototypeName(clazz, clazz.getAnnotation(EzyPrototype.class)); + } + + public static String getPrototypeName(Class clazz, EzyPrototype annotation) { + return getPrototypeName(annotation, EzyClasses.getVariableName(clazz, "Impl")); + } + + public static String getPrototypeName(EzyPrototype annotation, String defaultName) { + if(annotation == null) + return defaultName; + if(StringUtils.isEmpty(annotation.value())) + return defaultName; + return annotation.value(); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorPrototypeSupplierLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorPrototypeSupplierLoader.java new file mode 100644 index 00000000..10c7d2a7 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorPrototypeSupplierLoader.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.lang.reflect.Constructor; + +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyByConstructorPrototypeSupplierLoader + extends EzySimplePrototypeSupplierLoader + implements EzyPrototypeSupplierLoader { + + protected final Constructor constructor; + + public EzyByConstructorPrototypeSupplierLoader(EzyClass clazz) { + super(clazz); + this.constructor = getConstructor(clazz); + } + + @Override + protected String[] getConstructorArgumentNames() { + return getConstructorArgumentNames(constructor); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return constructor.getParameterTypes(); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorSingletonLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorSingletonLoader.java new file mode 100644 index 00000000..c5890537 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByConstructorSingletonLoader.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.lang.reflect.Constructor; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +@SuppressWarnings("rawtypes") +public class EzyByConstructorSingletonLoader + extends EzySimpleSingletonLoader + implements EzySingletonLoader { + + protected final Constructor constructor; + + protected EzyByConstructorSingletonLoader(EzyClass clazz) { + super(clazz); + this.constructor = getConstructor(clazz); + } + + @Override + protected String[] getConstructorArgumentNames() { + return getConstructorArgumentNames(constructor); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return constructor.getParameterTypes(); + } + + @Override + protected Object newSingletonByConstructor( + EzyBeanContext context, Class[] parameterTypes) throws Exception { + if(parameterTypes.length == 0) + return clazz.newInstance(); + return constructor.newInstance(getArguments(parameterTypes, context)); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldPrototypeSupplierLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldPrototypeSupplierLoader.java new file mode 100644 index 00000000..fd36e785 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldPrototypeSupplierLoader.java @@ -0,0 +1,63 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.List; +import java.util.Map; + +import com.tvd12.ezyfoxserver.asm.EzyFunction.EzyBody; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyField; + +public class EzyByFieldPrototypeSupplierLoader + extends EzySimplePrototypeSupplierLoader + implements EzyPrototypeSupplierLoader { + + protected final EzyField field; + protected final Object configurator; + + public EzyByFieldPrototypeSupplierLoader(EzyField field, Object configurator) { + super(new EzyClass(field.getType())); + this.field = field; + this.configurator = configurator; + } + + @Override + protected String getPrototypeName() { + return EzyBeanNameParser.getPrototypeName( + field.getAnnotation(EzyPrototype.class), field.getName()); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return new Class[0]; + } + + @Override + protected String[] getConstructorArgumentNames() { + return new String[0]; + } + + @SuppressWarnings("rawtypes") + @Override + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getPrototypeProperties( + field.getAnnotation(EzyPrototype.class)); + } + + @Override + protected EzyInstruction newConstructInstruction(EzyBody body, List cparams) { + Class configClass = configurator.getClass(); + EzyInstruction prepare = newVariableInstruction( + configClass, "configurator", EzyClasses.getVariableName(configClass)); + body.append(prepare); + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .append("configurator.") + .append(field.getName()); + return instruction; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldSingletonLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldSingletonLoader.java new file mode 100644 index 00000000..6526a0e1 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByFieldSingletonLoader.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +@SuppressWarnings("rawtypes") +public class EzyByFieldSingletonLoader + extends EzySimpleSingletonLoader + implements EzySingletonLoader { + + protected final EzyField field; + + public EzyByFieldSingletonLoader( + EzyField field, Object configurator, Map, EzyMethod> methodsByType) { + super(new EzyClass(field.getType()), configurator, methodsByType); + this.field = field; + } + + @Override + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getSingletonProperties( + field.getAnnotation(EzySingleton.class)); + } + + @Override + protected String getSingletonName() { + return EzyBeanNameParser.getSingletonName( + field.getAnnotation(EzySingleton.class), field.getName()); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return new Class[0]; + } + + @Override + protected Object newSingletonByConstructor( + EzyBeanContext context, Class[] parameterTypes) throws Exception { + return field.get(configurator); + } + + @Override + protected String[] getConstructorArgumentNames() { + return new String[0]; + } + + @Override + protected Class[] getConstructorParameterTypes(Class clazz) { + return new Class[0]; + } + + @Override + protected void detectCircularDependency(Class[] parameterTypes, StringBuilder log) { + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodPrototypeSupplierLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodPrototypeSupplierLoader.java new file mode 100644 index 00000000..00bb3e4e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodPrototypeSupplierLoader.java @@ -0,0 +1,63 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.asm.EzyFunction.EzyBody; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +public class EzyByMethodPrototypeSupplierLoader + extends EzySimplePrototypeSupplierLoader + implements EzyPrototypeSupplierLoader { + + protected final EzyMethod method; + protected final Object configurator; + + public EzyByMethodPrototypeSupplierLoader(EzyMethod method, Object configurator) { + super(new EzyClass(method.getReturnType())); + this.method = method; + this.configurator = configurator; + } + + @Override + protected String getPrototypeName() { + return EzyBeanNameParser.getPrototypeName( + method.getAnnotation(EzyPrototype.class), method.getFieldName()); + } + + @SuppressWarnings("rawtypes") + @Override + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getPrototypeProperties( + method.getAnnotation(EzyPrototype.class)); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return method.getParameterTypes(); + } + + @Override + protected EzyInstruction newConstructInstruction(EzyBody body, List cparams) { + Class configClass = configurator.getClass(); + EzyInstruction prepare = newVariableInstruction( + configClass, "configurator", EzyClasses.getVariableName(configClass)); + body.append(prepare); + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .append("configurator.") + .append(method.getName()) + .bracketopen() + .append(StringUtils.join(cparams, ", ")) + .bracketclose(); + return instruction; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodSingletonLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodSingletonLoader.java new file mode 100644 index 00000000..345de22b --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyByMethodSingletonLoader.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +@SuppressWarnings("rawtypes") +public class EzyByMethodSingletonLoader + extends EzySimpleSingletonLoader + implements EzySingletonLoader { + + protected final EzyMethod method; + + public EzyByMethodSingletonLoader( + EzyMethod method, + Object configurator, + Map, EzyMethod> methodsByType) { + super(new EzyClass(method.getReturnType()), configurator, methodsByType); + this.method = method; + } + + @Override + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getSingletonProperties( + method.getAnnotation(EzySingleton.class)); + } + + @Override + protected String getSingletonName() { + return EzyBeanNameParser.getSingletonName( + method.getAnnotation(EzySingleton.class), method.getFieldName()); + } + + @Override + protected Class[] getConstructorParameterTypes() { + return method.getParameterTypes(); + } + + @Override + protected Object newSingletonByConstructor( + EzyBeanContext context, Class[] parameterTypes) throws Exception { + if(parameterTypes.length == 0) + return method.invoke(configurator); + return method.invoke(configurator, getArguments(parameterTypes, context)); + } + + @Override + protected Class[] getConstructorParameterTypes(Class clazz) { + EzyMethod method = methodsByType.get(clazz); + return method != null ? method.getParameterTypes() : new Class[0]; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationBeforeClassSorter.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationBeforeClassSorter.java new file mode 100644 index 00000000..fc33aa7d --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationBeforeClassSorter.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfigurationBefore; + +@SuppressWarnings("rawtypes") +public class EzyConfigurationBeforeClassSorter { + + private EzyConfigurationBeforeClassSorter() { + } + + public static List sort(Collection classes) { + List list = new ArrayList<>(classes); + list.sort(newComparator()); + return list; + } + + private static Comparator newComparator() { + return (c1, c2) -> getPriority(c1) - getPriority(c2); + } + + private static int getPriority(Class clazz) { + return getPriority(clazz.getAnnotation(EzyConfigurationBefore.class)); + } + + private static int getPriority(EzyConfigurationBefore annotation) { + return annotation.priority(); + } +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationClassSorter.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationClassSorter.java new file mode 100644 index 00000000..b1e1ffdb --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationClassSorter.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; + +@SuppressWarnings("rawtypes") +public class EzyConfigurationClassSorter { + + private EzyConfigurationClassSorter() { + } + + public static List sort(Collection classes) { + List list = new ArrayList<>(classes); + list.sort(newComparator()); + return list; + } + + private static Comparator newComparator() { + return (c1, c2) -> getPriority(c1) - getPriority(c2); + } + + private static int getPriority(Class clazz) { + return getPriority(clazz.getAnnotation(EzyConfiguration.class)); + } + + private static int getPriority(EzyConfiguration annotation) { + return annotation.priority(); + } +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationLoader.java new file mode 100644 index 00000000..fb2ad807 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyConfigurationLoader.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; + +public interface EzyConfigurationLoader { + + EzyConfigurationLoader clazz(Class clazz); + + EzyConfigurationLoader context(EzyBeanContext context); + + void load(); +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyKeyValueParser.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyKeyValueParser.java new file mode 100644 index 00000000..db0c48ca --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyKeyValueParser.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.util.EzyKeyValueAnnotations; + +@SuppressWarnings({ "rawtypes" }) +public final class EzyKeyValueParser { + + private EzyKeyValueParser() { + } + + public static Map getSingletonProperties(Class clazz) { + return getSingletonProperties(clazz.getAnnotation(EzySingleton.class)); + } + + public static Map getSingletonProperties(EzySingleton annotation) { + EzyKeyValue[] keyValues = annotation != null ? annotation.properties() : new EzyKeyValue[0]; + return EzyKeyValueAnnotations.getProperties(keyValues); + } + + public static Map getPrototypeProperties(Class clazz) { + return getPrototypeProperties(clazz.getAnnotation(EzyPrototype.class)); + } + + public static Map getPrototypeProperties(EzyPrototype annotation) { + EzyKeyValue[] keyValues = annotation != null ? annotation.properties() : new EzyKeyValue[0]; + return EzyKeyValueAnnotations.getProperties(keyValues); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyPrototypeSupplierLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyPrototypeSupplierLoader.java new file mode 100644 index 00000000..26783e97 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzyPrototypeSupplierLoader.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public interface EzyPrototypeSupplierLoader { + + EzyPrototypeSupplier load(EzyPrototypeFactory factory); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanContext.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanContext.java new file mode 100644 index 00000000..8af776b1 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanContext.java @@ -0,0 +1,484 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanNameParser.getPrototypeName; +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanNameParser.getSingletonName; + +import java.lang.annotation.Annotation; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.bean.EzyErrorHandler; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfigurationBefore; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPackagesScan; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.bean.exception.EzyNewSingletonException; +import com.tvd12.ezyfoxserver.bean.exception.EzySingletonException; +import com.tvd12.ezyfoxserver.bean.supplier.EzyArrayListSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyCollectionSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyConcurrentHashMapSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyCopyOnWriteArrayListSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyCopyOnWriteArraySetSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyHashMapSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyHashSetSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyLinkedListSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyListSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyMapSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyQueueSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzySetSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyStackSupplier; +import com.tvd12.ezyfoxserver.bean.supplier.EzyTreeMapSupplier; +import com.tvd12.ezyfoxserver.properties.EzyPropertiesReader; +import com.tvd12.ezyfoxserver.properties.EzySimplePropertiesReader; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyHashMapSet; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyMapSet; + +import lombok.Getter; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class EzySimpleBeanContext + extends EzyLoggable + implements EzyBeanContext { + + @Getter + protected Properties properties; + @Getter + protected EzySingletonFactory singletonFactory; + @Getter + protected EzyPrototypeFactory prototypeFactory; + @Getter + protected EzyBeanNameTranslator beanNameTranslator; + + protected EzyPropertiesReader propertiesReader; + + @Override + public Object getBean(String name, Class type) { + Object object = getSingleton(name, type); + if(object != null) + return object; + return getPrototype(name, type); + } + + @Override + public Object getBean(Class type) { + return getBean(EzyBeanNameParser.getBeanName(type), type); + } + + @Override + public T getSingleton(String name, Class type) { + return (T) singletonFactory.getSingleton(name, type); + } + + @Override + public T getSingleton(Map properties) { + return (T) singletonFactory.getSingleton(properties); + } + + @Override + public List getSingletons(Map properties) { + return singletonFactory.getSingletons(properties); + } + + @Override + public T getPrototype(String name, Class type) { + EzyPrototypeSupplier supplier = prototypeFactory.getSupplier(name, type); + if(supplier == null) + throw new IllegalArgumentException("has no bean with name = " + name + ", and type " + type); + return (T) supplier.supply(this); + } + + @Override + public T getPrototype(Map properties) { + EzyPrototypeSupplier supplier = getPrototypeSupplier(properties); + return supplier != null ? (T)supplier.supply(this) : null; + } + + @Override + public List getPrototypes(Map properties) { + List list = new ArrayList<>(); + List suppliers = getPrototypeSuppliers(properties); + for(EzyPrototypeSupplier supplier : suppliers) + list.add(supplier.supply(this)); + return list; + } + + @Override + public EzyPrototypeSupplier getPrototypeSupplier(Map properties) { + return prototypeFactory.getSupplier(properties); + } + + @Override + public List getPrototypeSuppliers(Map properties) { + return prototypeFactory.getSuppliers(properties); + } + + @Override + public boolean containsProperty(Object key) { + return properties.containsKey(key); + } + + @Override + public T getProperty(Object key, Class outType) { + return propertiesReader.get(properties, key, outType); + } + + public static EzyBeanContextBuilder builder() { + return new Builder(); + } + + public static class Builder extends EzyLoggable implements EzyBeanContextBuilder { + protected Properties properties; + protected Set singletonClasses; + protected Set prototypeClasses; + protected Set packagesScanClasses; + protected Set configurationClasses; + protected Set configurationBeforeClasses; + protected EzyPropertiesReader propertiesReader; + protected EzySingletonFactory singletonFactory; + protected EzyPrototypeFactory prototypeFactory; + protected EzyBeanNameTranslator beanNameTranslator; + + protected EzyErrorHandler errorHandler; + protected EzyMapSet> unloadedSingletons; + + public Builder() { + this.properties = new Properties(); + this.singletonClasses = new HashSet<>(); + this.prototypeClasses = new HashSet<>(); + this.packagesScanClasses = new HashSet<>(); + this.configurationClasses = new HashSet<>(); + this.configurationBeforeClasses = new HashSet<>(); + this.errorHandler = new EzySimpleErrorHandler(); + this.unloadedSingletons = new EzyHashMapSet<>(); + this.beanNameTranslator = new EzySimpleBeanNameTranslator(); + this.singletonFactory = newBeanFactory(new EzySimpleSingletonFactory()); + this.prototypeFactory = newBeanFactory(new EzySimplePrototypeFactory()); + } + + protected T newBeanFactory(T factory) { + factory.setBeanNameTranslator(beanNameTranslator); + return factory; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#scan(java.lang.String) + */ + @Override + public EzyBeanContextBuilder scan(String packageName) { + singletonClasses.addAll(getAnnotatedClasses(packageName, EzySingleton.class)); + prototypeClasses.addAll(getAnnotatedClasses(packageName, EzyPrototype.class)); + packagesScanClasses.addAll(getAnnotatedClasses(packageName, EzyPackagesScan.class)); + configurationClasses.addAll(getAnnotatedClasses(packageName, EzyConfiguration.class)); + configurationBeforeClasses.addAll(getAnnotatedClasses(packageName, EzyConfigurationBefore.class)); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#scan(java.lang.String) + */ + @Override + public EzyBeanContextBuilder scan(String... packageNames) { + return scan(Sets.newHashSet(packageNames)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#scan(java.lang.Iterable) + */ + @Override + public EzyBeanContextBuilder scan(Iterable packageNames) { + packageNames.forEach(this::scan); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addSingleton(java.lang.String, java.lang.Object) + */ + @Override + public EzyBeanContextBuilder addSingleton(String name, Object singleton) { + singletonFactory.addSingleton(name, singleton); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addPrototypeSupplier(java.lang.String, com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier) + */ + @Override + public EzyBeanContextBuilder addPrototypeSupplier(String objectName, EzyPrototypeSupplier supplier) { + prototypeFactory.addSupplier(objectName, supplier); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addSingletonClass(java.lang.Class) + */ + @Override + public EzyBeanContextBuilder addSingletonClass(Class clazz) { + this.singletonClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addSingletonClasses(java.lang.Class) + */ + @Override + public EzyBeanContextBuilder addSingletonClasses(Class... classes) { + return addSingletonClasses(Sets.newHashSet(classes)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addSingletonClasses(java.lang.Iterable) + */ + @Override + public EzyBeanContextBuilder addSingletonClasses(Iterable classes) { + classes.forEach(this::addSingletonClass); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addPrototypeClass(java.lang.Class) + */ + @Override + public EzyBeanContextBuilder addPrototypeClass(Class clazz) { + this.prototypeClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addPrototypeClasses(java.lang.Class) + */ + @Override + public EzyBeanContextBuilder addPrototypeClasses(Class... classes) { + return addPrototypeClasses(Sets.newHashSet(classes)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#addPrototypeClasses(java.lang.Iterable) + */ + @Override + public EzyBeanContextBuilder addPrototypeClasses(Iterable classes) { + classes.forEach(this::addPrototypeClass); + return this; + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder#errorHandler(com.tvd12.ezyfoxserver.bean.EzyErrorHandler) + */ + @Override + public EzyBeanContextBuilder errorHandler(EzyErrorHandler handler) { + this.errorHandler = handler; + return this; + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder#addProperties(java.util.Map) + */ + @Override + public EzyBeanContextBuilder addProperties(Map properties) { + this.properties.putAll(properties); + return this; + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder#addProperty(java.lang.String, java.lang.Object) + */ + public EzyBeanContextBuilder addProperty(String key, Object value) { + this.properties.put(key, value); + return this; + } + + @Override + public EzyBeanContextBuilder propertiesReader(EzyPropertiesReader propertiesReader) { + this.propertiesReader = propertiesReader; + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.bean.impl.EzyBeanContextBuilder#build() + */ + @Override + public EzySimpleBeanContext build() { + EzySimpleBeanContext context = new EzySimpleBeanContext(); + context.properties = properties; + context.prototypeFactory = prototypeFactory; + context.singletonFactory = singletonFactory; + context.beanNameTranslator = beanNameTranslator; + context.propertiesReader = getPropertiesReader(); + addSingleton("beanContext", context); + addSingleton("singletonFactory", singletonFactory); + addSingleton("prototypeFactory", prototypeFactory); + addSingleton("beanNameTranslator", beanNameTranslator); + scanPackagesScanClasses(); + prototypeClasses.removeAll(singletonClasses); + loadConfigurationBeforeClasses(context); + addScannedSingletonsToFactory(context); + addDefaultPrototypeSuppliers(); + addScannedPrototypeSuppliersToFactory(); + tryLoadUncompletedSingletonsAgain(context, false); + loadConfigurationClasses(context); + tryLoadUncompletedSingletonsAgain(context, true); + return context; + } + + private Set> getAnnotatedClasses(String packageName, Class annClass) { + return EzyPackages.getAnnotatedClasses(packageName, annClass); + } + + private void addScannedSingletonsToFactory(EzyBeanContext context) { + for(Class type : singletonClasses) + createAndLoadSingleton(context, type); + } + + private void addScannedPrototypeSuppliersToFactory() { + for(Class type : prototypeClasses) + createAndLoadPrototypeSupplier(type); + } + + private Object createAndLoadSingleton(EzyBeanContext context, Class type) { + return createAndLoadSingleton(context, type, false); + } + + private Object createAndLoadSingleton(EzyBeanContext context, Class type, boolean reload) { + String beanName = getSingletonName(type); + Object current = singletonFactory.getSingleton(beanName, type); + if(current != null && !reload) return current; + try { + return new EzyByConstructorSingletonLoader(new EzyClass(type)).load(context); + } + catch(EzyNewSingletonException e) { + unloadedSingletons.addItems(e.getErrorKey(), e.getSingletonClass()); + return null; + } + } + + private void createAndLoadPrototypeSupplier(Class type) { + String beanName = getPrototypeName(type); + Object current = prototypeFactory.getSupplier(beanName, type); + if(current == null) + new EzyByConstructorPrototypeSupplierLoader(new EzyClass(type)).load(prototypeFactory); + } + + private void scanPackagesScanClasses() { + packagesScanClasses.forEach(this::scanPackagesScanClass); + } + + private void scanPackagesScanClass(Class clazz) { + scan(clazz.getAnnotation(EzyPackagesScan.class).value()); + } + + private void loadConfigurationBeforeClasses(EzyBeanContext context) { + List classes = EzyConfigurationBeforeClassSorter.sort(configurationBeforeClasses); + for(Class clazz : classes) + loadConfigurationClass(clazz, context); + } + + private void loadConfigurationClasses(EzyBeanContext context) { + List classes = EzyConfigurationClassSorter.sort(configurationClasses); + for(Class clazz : classes) + loadConfigurationClass(clazz, context); + } + + private void loadConfigurationClass(Class clazz, EzyBeanContext context) { + new EzySimpleConfigurationLoader().context(context).clazz(clazz).load(); + } + + private void tryLoadUncompletedSingletonsAgain(EzyBeanContext context, boolean finish) { + Set keySet = new HashSet<>(unloadedSingletons.keySet()); + for(EzyBeanKey key : keySet) { + Set> uncompleted = unloadedSingletons.get(key); + getLogger().debug("unload bean: {}, uncompleted: {}", key, uncompleted); + getLogger().debug("try load bean {} again", key); + loadUncompletedSingletons(context, key, uncompleted, finish); + } + if(finish) { + while(!unloadedSingletons.isEmpty()) + tryLoadUncompletedSingletonsAgain(context, finish); + } + } + + private void loadUncompletedSingletons( + EzyBeanContext context, EzyBeanKey key, Set> uncompleted, boolean finish) { + Object singleton = getSingletonOfErrorBeanKey0(context, key, finish); + if(singleton == null) return; + getLogger().debug("found singleton {} with key {}", singleton, key); + for(Class clazz : uncompleted) { + createAndLoadSingleton(context, clazz, true); + } + } + + private Object getSingletonOfErrorBeanKey0(EzyBeanContext context, EzyBeanKey key, boolean finish) { + Object singleton = null; + try { + singleton = getSingletonOfErrorBeanKey(context, key); + } + catch(EzySingletonException e) { + if(finish) { + errorHandler.handle(e); + unloadedSingletons.remove(key); + } + } + if(finish && singleton != null) { + unloadedSingletons.remove(key); + } + return singleton; + } + + private Object getSingletonOfErrorBeanKey(EzyBeanContext context, EzyBeanKey key) { + Object singleton = singletonFactory.getSingleton(key.getName(), key.getType()); + if(singleton != null) return singleton; + return loadSingletonOfBeanKey(context, key); + } + + private Object loadSingletonOfBeanKey(EzyBeanContext context, EzyBeanKey key) { + for(EzyBeanKey i : unloadedSingletons.keySet()) { + Set> classes = unloadedSingletons.get(i); + for(Class implClass : classes) { + if(key.getType().isAssignableFrom(implClass)) { + return createAndLoadSingleton(context, implClass, true); + } + } + } + throw EzySingletonException.implementationNotFound(key, unloadedSingletons.get(key)); + } + + private EzyPropertiesReader getPropertiesReader() { + return propertiesReader != null ? propertiesReader : new EzySimplePropertiesReader(); + } + + private void addDefaultPrototypeSuppliers() { + prototypeFactory.addSupplier(new EzyArrayListSupplier()); + prototypeFactory.addSupplier(new EzyCollectionSupplier()); + prototypeFactory.addSupplier(new EzyConcurrentHashMapSupplier()); + prototypeFactory.addSupplier(new EzyCopyOnWriteArrayListSupplier()); + prototypeFactory.addSupplier(new EzyCopyOnWriteArraySetSupplier()); + prototypeFactory.addSupplier(new EzyHashMapSupplier()); + prototypeFactory.addSupplier(new EzyHashSetSupplier()); + prototypeFactory.addSupplier(new EzyLinkedListSupplier()); + prototypeFactory.addSupplier(new EzyListSupplier()); + prototypeFactory.addSupplier(new EzyMapSupplier()); + prototypeFactory.addSupplier(new EzyQueueSupplier()); + prototypeFactory.addSupplier(new EzySetSupplier()); + prototypeFactory.addSupplier(new EzyStackSupplier()); + prototypeFactory.addSupplier(new EzyTreeMapSupplier()); + } + + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanFactory.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanFactory.java new file mode 100644 index 00000000..e327dea4 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanFactory.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +public class EzySimpleBeanFactory extends EzyLoggable { + + @Setter + protected EzyBeanNameTranslator beanNameTranslator; + + protected final String translateBeanName(String name, Class type) { + if(beanNameTranslator == null) + return name; + return beanNameTranslator.translate(name, type); + } + + protected final void mapBeanName(String freename, Class type, String realname) { + if(beanNameTranslator != null) + beanNameTranslator.map(freename, type, realname); + } + + protected final String getDefaultBeanName(Class type) { + return EzyClasses.getVariableName(type); + } +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanNameTranslator.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanNameTranslator.java new file mode 100644 index 00000000..a130f748 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleBeanNameTranslator.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey.*; + +public class EzySimpleBeanNameTranslator implements EzyBeanNameTranslator { + + protected final Map map = new ConcurrentHashMap<>(); + + @Override + public String translate(String name, Class type) { + EzyBeanKey key = of(name, type); + return map.containsKey(key) ? map.get(key) : name; + } + + @Override + public void map(String freename, Class type, String realname) { + map.put(of(freename, type), realname); + } +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleConfigurationLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleConfigurationLoader.java new file mode 100644 index 00000000..88d34668 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleConfigurationLoader.java @@ -0,0 +1,175 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import com.tvd12.ezyfoxserver.bean.EzyBeanConfig; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslatorAware; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextAware; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactoryAware; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactoryAware; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyPropertiesAware; + +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanNameParser.*; + +public class EzySimpleConfigurationLoader + extends EzyLoggable + implements EzyConfigurationLoader { + + protected EzyClass clazz; + protected Properties properties; + protected EzyBeanContext context; + protected EzyPrototypeFactory prototypeFactory; + protected EzySingletonFactory singletonFactory; + protected EzyBeanNameTranslator beanNameTranslator; + protected Map, EzyMethod> singletonMethods; + + @Override + public EzyConfigurationLoader clazz(Class configClass) { + this.clazz = new EzyClass(configClass); + this.singletonMethods = mapSingletonTypeMethods(); + return this; + } + + @Override + public EzyConfigurationLoader context(EzyBeanContext context) { + this.context = context; + this.properties = context.getProperties(); + this.singletonFactory = context.getSingletonFactory(); + this.prototypeFactory = context.getPrototypeFactory(); + this.beanNameTranslator = context.getBeanNameTranslator(); + return this; + } + + @Override + public void load() { + Object configurator = newConfigurator(); + addSingletonByFields(configurator); + addSingletonByMethods(configurator); + addPrototypeByFields(configurator); + addPrototypeByMethods(configurator); + } + + private Object newConfigurator() { + Object object = new EzyByConstructorSingletonLoader(clazz) + .load(context); + if(object instanceof EzyBeanContextAware) + ((EzyBeanContextAware)object).setContext(context); + if(object instanceof EzyPropertiesAware) + ((EzyPropertiesAware)object).setProperties(properties); + if(object instanceof EzySingletonFactoryAware) + ((EzySingletonFactoryAware)object).setSingletonFactory(singletonFactory); + if(object instanceof EzyPrototypeFactoryAware) + ((EzyPrototypeFactoryAware)object).setPrototypeFactory(prototypeFactory); + if(object instanceof EzyBeanNameTranslatorAware) + ((EzyBeanNameTranslatorAware)object).setBeanNameTranslator(beanNameTranslator); + if(object instanceof EzyBeanConfig) + ((EzyBeanConfig)object).config(); + return object; + } + + private void addSingletonByFields(Object configurator) { + getSingletonFields().forEach(f -> addSingletonByField(f, configurator)); + } + + private void addSingletonByField(EzyField field, Object configurator) { + String beanName = getSingletonName(field); + Object current = singletonFactory.getSingleton(beanName, field.getType()); + if(current == null) + new EzyByFieldSingletonLoader( + field, configurator, singletonMethods).load(context); + } + + private void addSingletonByMethods(Object configurator) { + Set> types = new HashSet<>(singletonMethods.keySet()); + for(Class type : types) { + EzyMethod method = singletonMethods.remove(type); + if(method != null) { + getLogger().debug("add singleton of {} with method {}", type, method); + addSingletonByMethod(method, configurator); + } + } + } + + private void addSingletonByMethod(EzyMethod method, Object configurator) { + String beanName = getSingletonName(method); + Object current = singletonFactory.getSingleton(beanName, method.getReturnType()); + if(current == null) { + new EzyByMethodSingletonLoader( + method, configurator, singletonMethods).load(context); + } + } + + //============ prototype ================= + private void addPrototypeByFields(Object configurator) { + getPrototypeFields().forEach(f -> addPrototypeByField(f, configurator)); + } + + private void addPrototypeByField(EzyField field, Object configurator) { + String beanName = getPrototypeName(field); + Object current = prototypeFactory.getSupplier(beanName, field.getType()); + if(current == null) + new EzyByFieldPrototypeSupplierLoader(field, configurator).load(prototypeFactory); + } + + private void addPrototypeByMethods(Object configurator) { + Map, EzyMethod> methods = mapPrototypeTypeMethods(); + Set> types = new HashSet<>(methods.keySet()); + for(Class type : types) + addPrototypeByMethod(methods.remove(type), configurator, methods); + } + + private void addPrototypeByMethod(EzyMethod method, + Object configurator, Map, EzyMethod> methods) { + String beanName = getPrototypeName(method); + Object current = prototypeFactory.getSupplier(beanName, method.getReturnType()); + if(current == null) { + new EzyByMethodPrototypeSupplierLoader(method, configurator).load(prototypeFactory); + } + } + + //============ get components ========== + + private List getSingletonFields() { + return getBeanFields(EzySingleton.class); + } + + private Map, EzyMethod> mapSingletonTypeMethods() { + return mapBeanTypeMethods(EzySingleton.class); + } + + private List getPrototypeFields() { + return getBeanFields(EzyPrototype.class); + } + + private Map, EzyMethod> mapPrototypeTypeMethods() { + return mapBeanTypeMethods(EzyPrototype.class); + } + + private List getBeanFields(Class annClass) { + return clazz.getPublicFields(f -> f.isAnnotated(annClass)); + } + + private Map, EzyMethod> mapBeanTypeMethods(Class annClass) { + List methods = clazz.getPublicMethods(m -> + m.isAnnotated(annClass) && + m.getReturnType() != void.class + ); + return EzyMaps.newHashMap(methods, m -> m.getReturnType()); + } +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleErrorHandler.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleErrorHandler.java new file mode 100644 index 00000000..3b7668c6 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleErrorHandler.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import com.tvd12.ezyfoxserver.bean.EzyErrorHandler; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleErrorHandler + extends EzyLoggable + implements EzyErrorHandler { + + @Override + public void handle(Throwable error) { + getLogger().warn("error", error); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleObjectBuilder.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleObjectBuilder.java new file mode 100644 index 00000000..22e54adc --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleObjectBuilder.java @@ -0,0 +1,166 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; + +import com.tvd12.ezyfoxserver.annotation.EzyProperty; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyPropertyAnnotations; + +@SuppressWarnings("rawtypes") +public abstract class EzySimpleObjectBuilder extends EzyLoggable { + + protected final EzyClass clazz; + protected final AtomicInteger variableCount; + protected final List bindingFields; + protected final List bindingMethods; + protected final List propertyFields; + protected final List propertyMethods; + + public EzySimpleObjectBuilder(EzyClass clazz) { + this.clazz = clazz; + this.variableCount = new AtomicInteger(0); + this.bindingFields = getBindingFields(clazz); + this.bindingMethods = getBindingMethods(clazz); + this.propertyFields = getPropertyFields(clazz); + this.propertyMethods = getPropertyMethods(clazz); + } + + protected Constructor getConstructor(EzyClass clazz) { + List constructors = clazz.getDeclaredConstructors(); + for(Constructor con : constructors) + if(con.isAnnotationPresent(EzyAutoBind.class)) + return con; + return clazz.getDeclaredConstructor(); + } + + protected abstract Class[] getConstructorParameterTypes(); + + protected String[] getConstructorArgumentNames() { + return getArgumentNames(getConstructorParameterTypes()); + } + + protected final String[] getArgumentNames(Class[] parameterTypes) { + String[] names = new String[parameterTypes.length]; + for(int i = 0 ; i < parameterTypes.length ; i++) + names[i] = EzyClasses.getVariableName(parameterTypes[i]); + return names; + } + + protected final String[] getConstructorArgumentNames(EzyAutoBind annotation) { + Class[] parameterTypes = getConstructorParameterTypes(); + String[] names = getArgumentNames(parameterTypes); + if(annotation == null) return names; + String[] fixNames = annotation.value(); + for(int i = 0 ; i < fixNames.length ; i++) + if(i < names.length) names[i] = fixNames[i]; + return names; + } + + protected final String[] getConstructorArgumentNames(Constructor constructor) { + return getConstructorArgumentNames( + constructor.getAnnotation(EzyAutoBind.class)); + } + + protected final List getBindingFields(EzyClass clazz) { + return getValidFields(clazz, EzyAutoBind.class); + } + + protected final List getBindingMethods(EzyClass clazz) { + return getValidMethods(clazz, this::isBindingMethod); + } + + protected final List getPropertyFields(EzyClass clazz) { + return getValidFields(clazz, EzyProperty.class); + } + + protected final List getPropertyMethods(EzyClass clazz) { + return getValidMethods(clazz, this::isPropertyMethod); + } + + protected final List getPostInitMethods() { + return clazz.getPublicMethods(m -> + m.isAnnotated(EzyPostInit.class) && + m.getParameterCount() == 0 + ); + } + + private boolean isBindingMethod(EzyMethod method) { + return isValidMethod(method, EzyAutoBind.class); + } + + private boolean isPropertyMethod(EzyMethod method) { + return isValidMethod(method, EzyProperty.class); + } + + private List getValidFields( + EzyClass clazz, Class ann) { + return clazz.getFields(f -> f.isPublic() && f.isAnnotated(ann)); + } + + private List + getValidMethods(EzyClass clazz, Predicate predicate) { + List methods = clazz.getMethods(); + List valid = EzyLists.filter(methods, predicate); + return EzyLists.newArrayList(valid, EzySetterMethod::new); + } + + private boolean isValidMethod(EzyMethod method, Class ann) { + if(!method.isPublic()) + return false; + if(method.getParameterCount() != 1) + return false; + EzyField field = clazz.getField(method.getFieldName()); + boolean answer = + field != null && + !field.isPublic() && + field.isAnnotated(ann); + return answer ? answer : method.isAnnotated(ann); + } + + protected final boolean isAbstractClass(Class clazz) { + return Modifier.isAbstract(clazz.getModifiers()); + } + + protected final String getBeanName(EzyReflectElement element) { + if(element instanceof EzyField) + return getBeanName((EzyField)element); + return getBeanName((EzyMethod)element); + } + + private String getBeanName(EzyField field) { + EzyAutoBind annotation = field.getAnnotation(EzyAutoBind.class); + if(annotation == null) + return field.getName(); + if(annotation.value().length > 0 && annotation.value()[0].length() > 0) + return annotation.value()[0]; + return field.getName(); + } + + private final String getBeanName(EzyMethod method) { + EzyAutoBind annotation = method.getAnnotation(EzyAutoBind.class); + if(annotation != null && annotation.value().length > 0) + return annotation.value()[0]; + String fieldName = method.getFieldName(); + EzyField field = clazz.getField(fieldName); + return field != null ? getBeanName(field) : fieldName; + } + + protected final String getPropertyName(EzyReflectElement element) { + return EzyPropertyAnnotations.getPropertyName(clazz, element); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeFactory.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeFactory.java new file mode 100644 index 00000000..bd85022b --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeFactory.java @@ -0,0 +1,121 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import static com.tvd12.ezyfoxserver.reflect.EzyClasses.*; +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey.*; + +@SuppressWarnings({ "unchecked", "rawtypes" }) +public class EzySimplePrototypeFactory + extends EzySimpleBeanFactory + implements EzyPrototypeFactory { + + protected final Map supplierByKey + = new ConcurrentHashMap<>(); + protected final Map suppliersByProperties + = new ConcurrentHashMap<>(); + + @Override + public EzyPrototypeSupplier getSupplier(String objectName, Class objectType) { + String realname = translateBeanName(objectName, objectType); + return supplierByKey.get(of(realname, objectType)); + } + + @Override + public EzyPrototypeSupplier getSupplier(Map properties) { + for(Entry entry : suppliersByProperties.entrySet()) + if(EzyMaps.containsAll(entry.getValue(), properties)) + return entry.getKey(); + return null; + } + + @Override + public List getSuppliers(Map properties) { + List list = new ArrayList<>(); + for(Entry entry : suppliersByProperties.entrySet()) + if(EzyMaps.containsAll(entry.getValue(), properties)) + list.add(entry.getKey()); + return list; + } + + @Override + public List getSuppliers(Class annoClass) { + List list = new ArrayList<>(); + for(EzyBeanKey key : supplierByKey.keySet()) { + Class type = key.getType(); + if(type.isAnnotationPresent(annoClass)) + list.add(supplierByKey.get(type)); + } + return list; + } + + @Override + public Map getProperties(EzyPrototypeSupplier supplier) { + return suppliersByProperties.get(supplier); + } + + @Override + public void addSupplier(EzyPrototypeSupplier supplier) { + Class type = supplier.getObjectType(); + addSupplier(getBeanName(type), supplier); + } + + @Override + public void addSupplier(String objectName, EzyPrototypeSupplier supplier) { + Class type = supplier.getObjectType(); + addSupplier(objectName, supplier, getProperties(type)); + } + + @Override + public void addSupplier( + String objectName, EzyPrototypeSupplier supplier, Map properties) { + Class type = supplier.getObjectType(); + EzyBeanKey key = of(objectName, type); + + if(supplierByKey.containsKey(key)) + return; + + supplierByKey.put(key, supplier); + suppliersByProperties.put(supplier, properties); + + String defname = getDefaultBeanName(type); + mapBeanName(defname, type, objectName); + + Set subTypes = flatSuperAndInterfaceClasses(type, true); + for(Class subType : subTypes) + checkAndAddSupplier(objectName, subType, supplier); + } + + private void checkAndAddSupplier( + String objectName, Class type, EzyPrototypeSupplier supplier) { + EzyBeanKey key = of(objectName, type); + if(supplierByKey.containsKey(key)) + return; + supplierByKey.put(key, supplier); + } + + private String getBeanName(Class type) { + return EzyBeanNameParser.getPrototypeName(type); + } + + private Map getProperties(Class type) { + EzyPrototype ann = type.getAnnotation(EzyPrototype.class); + Map properties = new HashMap<>(); + EzyKeyValue[] keyValues = ann != null ? ann.properties() : new EzyKeyValue[0]; + Arrays.stream(keyValues).forEach(kv -> properties.put(kv.key(), kv.value())); + return properties; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeSupplierLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeSupplierLoader.java new file mode 100644 index 00000000..62ae194f --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimplePrototypeSupplierLoader.java @@ -0,0 +1,301 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtNewMethod; +import lombok.Setter; + +@SuppressWarnings("rawtypes") +public abstract class EzySimplePrototypeSupplierLoader + extends EzySimpleObjectBuilder + implements EzyPrototypeSupplierLoader { + + @Setter + private static boolean debug; + private static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzySimplePrototypeSupplierLoader(EzyClass clazz) { + super(clazz); + } + + @Override + public final EzyPrototypeSupplier load(EzyPrototypeFactory factory) { + try { + return process(factory); + } + catch(Exception e) { + throw new IllegalStateException("can not create prototype supplier of class " + clazz, e); + } + } + + private Class getPrototypeClass() { + return clazz.getClazz(); + } + + protected String getPrototypeName() { + return EzyBeanNameParser.getPrototypeName(getPrototypeClass()); + } + + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getPrototypeProperties(getPrototypeClass()); + } + + private EzyPrototypeSupplier process(EzyPrototypeFactory factory) throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + + EzyMethod supplyMethod = getSupplyMethod(); + supplyMethod.setDisplayName("supply$impl"); + String supplyImplMethodContent = makeSupplyImplMethodContent(supplyMethod); + supplyMethod.setDisplayName("supply"); + String supplyMethodContent = makeSupplyMethodContent(supplyMethod); + + EzyMethod getObjectTypeMethod = getGetObjectTypeMethod(); + String getObjectTypeMethodContent = makeGetObjectTypeMethodContent(getObjectTypeMethod); + + printMethodContent(supplyMethodContent); + printMethodContent(supplyImplMethodContent); + printMethodContent(getObjectTypeMethodContent); + + implClass.setInterfaces(new CtClass[] { pool.makeClass(EzyPrototypeSupplier.class.getName()) }); + implClass.addMethod(CtNewMethod.make(supplyImplMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(supplyMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(getObjectTypeMethodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + EzyPrototypeSupplier supplier = (EzyPrototypeSupplier)answerClass.newInstance(); + factory.addSupplier(getPrototypeName(), supplier, getAnnotationProperties()); + getLogger().debug("add prototype supplier of " + implClassName); + return supplier; + } + + private String makeGetObjectTypeMethodContent(EzyMethod method) { + return new EzyFunction(method) + .body() + .append(new EzyInstruction("\t", "\n") + .answer() + .clazz(clazz.getClazz(), true)) + .function() + .toString(); + } + + private String makeSupplyMethodContent(EzyMethod method) { + return new EzyFunction(method) + .body() + .append(new EzyInstruction("\t", "\n", false) + .append("try {")) + .append(new EzyInstruction("\t\t", "\n") + .append("return this.supply$impl(arg0)")) + .append(new EzyInstruction("\t", "\n", false) + .append("} catch(") + .clazz(Exception.class) + .append(" e) {")) + .append(new EzyInstruction("\t\t", "\n\t}\n") + .append("throw new ") + .clazz(IllegalStateException.class) + .bracketopen() + .string("can't create bean of " + clazz.getClazz().getTypeName()) + .append(", e") + .bracketclose()) + .function() + .toString(); + } + + private String makeSupplyImplMethodContent(EzyMethod method) { + EzyFunction.EzyBody methodBody = new EzyFunction(method) + .modifier("protected") + .body(); + addConstructInstruction(methodBody); + addSetPropertiesInstructions(methodBody); + addBindingValueInstructions(methodBody); + addCallPostInitInstructions(methodBody); + addReturnInstruction(methodBody); + EzyFunction function = methodBody.function(); + return function.toString(); + } + + private void addConstructInstruction(EzyFunction.EzyBody body) { + List cparams = addAndGetConstructorParamNames(body); + EzyInstruction instruction = newConstructInstruction(body, cparams); + body.append(instruction); + } + + private List addAndGetConstructorParamNames(EzyFunction.EzyBody body) { + int index = 0; + List cparams = new ArrayList<>(); + String[] argumentNames = getConstructorArgumentNames(); + for(Class type : getConstructorParameterTypes()) { + String variableName = "cparam" + index; + String beanName = EzyStrings.getString(argumentNames, index ++, variableName); + cparams.add(variableName); + body.append(newVariableInstruction(type, variableName, beanName)); + } + return cparams; + } + + protected EzyInstruction newConstructInstruction(EzyFunction.EzyBody body, List cparams) { + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .append("new ") + .clazz(clazz.getClazz()) + .bracketopen() + .append(StringUtils.join(cparams, ", ")) + .bracketclose(); + return instruction; + } + + protected final EzyInstruction newVariableInstruction(Class varType, String varName, String beanName) { + return new EzyInstruction("\t", "\n") + .variable(varType, varName) + .equal() + .bracketopen() + .clazz(varType) + .bracketclose() + .append("arg0.getBean") + .bracketopen() + .string(beanName) + .comma() + .clazz(varType, true) + .bracketclose(); + } + + private void addReturnInstruction(EzyFunction.EzyBody body) { + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .answer() + .append("object"); + body.append(instruction); + } + + private void addSetPropertiesInstructions(EzyFunction.EzyBody body) { + for(EzyField field : propertyFields) + addSetPropertyInstruction(body, field); + for(EzySetterMethod method : propertyMethods) + addSetPropertyInstruction(body, method); + } + + private void addSetPropertyInstruction(EzyFunction.EzyBody body, EzyField field) { + Class propertyType = field.getType(); + String propertyName = getPropertyName(field); + body.append(new EzyInstruction("\t", "\n", false) + .append("if(arg0.containsProperty(\"" + propertyName + "\"))")); + body.append(new EzyInstruction("\t\t", "\n") + .append("object.") + .append(field.getName()) + .equal() + .brackets(propertyType) + .append("arg0.getProperty") + .bracketopen() + .string(propertyName) + .comma() + .clazz(propertyType, true) + .bracketclose()); + } + + private void addSetPropertyInstruction(EzyFunction.EzyBody body, EzySetterMethod method) { + Class propertyType = method.getType(); + String propertyName = getPropertyName(method); + body.append(new EzyInstruction("\t", "\n", false) + .append("if(arg0.containsProperty(\"" + propertyName + "\"))")); + body.append(new EzyInstruction("\t\t", "\n") + .append("object.") + .append(method.getName()) + .bracketopen() + .brackets(propertyType) + .append("arg0.getProperty") + .bracketopen() + .string(propertyName) + .comma() + .clazz(propertyType, true) + .bracketclose() + .bracketclose()); + } + + private void addBindingValueInstructions(EzyFunction.EzyBody body) { + for(EzyField field : bindingFields) + addBindingValueInstruction(body, field); + for(EzySetterMethod method : bindingMethods) + addBindingValueInstruction(body, method); + } + + private void addBindingValueInstruction( + EzyFunction.EzyBody body, EzyField field) { + String variableName = field.getName() + variableCount.incrementAndGet(); + Class propertyType = field.getType(); + body.append(newVariableInstruction(propertyType, variableName, getBeanName(field))); + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .append("object.") + .append(field.getName()) + .equal() + .append(variableName); + body.append(instruction); + } + + private void addBindingValueInstruction( + EzyFunction.EzyBody body, EzySetterMethod method) { + String variableName = method.getFieldName() + variableCount.incrementAndGet(); + Class propertyType = method.getType(); + body.append(newVariableInstruction(propertyType, variableName, getBeanName(method))); + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .append("object.") + .append(method.getName()) + .brackets(variableName); + body.append(instruction); + } + + private void addCallPostInitInstructions(EzyFunction.EzyBody body) { + List methods = getPostInitMethods(); + methods.forEach(m -> addCallPostInitInstruction(body, m)); + } + + private void addCallPostInitInstruction(EzyFunction.EzyBody body, EzyMethod method) { + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .append("object.") + .append(method.getName()) + .brackets(""); + body.append(instruction); + } + + private String getImplClassName() { + return clazz.getName() + "$EzyPrototypeSupplier$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + private EzyMethod getSupplyMethod() { + return EzyMethod.builder() + .clazz(EzyPrototypeSupplier.class) + .methodName("supply") + .parameterTypes(EzyBeanContext.class) + .build(); + } + + private EzyMethod getGetObjectTypeMethod() { + return EzyMethod.builder() + .clazz(EzyPrototypeSupplier.class) + .methodName("getObjectType") + .build(); + } + + private void printMethodContent(String methodContent) { + if(debug) getLogger().debug("reader: method content \n{}", methodContent); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonFactory.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonFactory.java new file mode 100644 index 00000000..e03972f7 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonFactory.java @@ -0,0 +1,112 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import static com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey.of; +import static com.tvd12.ezyfoxserver.reflect.EzyClasses.flatSuperAndInterfaceClasses; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +@SuppressWarnings({ "unchecked", "rawtypes" }) +public class EzySimpleSingletonFactory + extends EzySimpleBeanFactory + implements EzySingletonFactory { + + protected final Map objectsByKey + = new ConcurrentHashMap<>(); + protected final Map objectsByProperties + = new ConcurrentHashMap<>(); + + @Override + public Object addSingleton(Object singleton) { + Class type = singleton.getClass(); + return addSingleton(getBeanName(type), singleton); + } + + @Override + public Object addSingleton(String name, Object singleton) { + Class type = singleton.getClass(); + return addSingleton(name, singleton, getProperties(type)); + } + + @Override + public Object addSingleton(String name, Object singleton, Map properties) { + Class type = singleton.getClass(); + EzyBeanKey key = of(name, type); + + if(objectsByKey.containsKey(key)) + return objectsByKey.get(key); + + objectsByKey.put(key, singleton); + objectsByProperties.put(singleton, properties); + + String defname = getDefaultBeanName(type); + mapBeanName(defname, type, name); + + Set subTypes = flatSuperAndInterfaceClasses(type, true); + for(Class subType : subTypes) + checkAndAddSingleton(name, subType, singleton); + return singleton; + } + + private void checkAndAddSingleton(String name, Class type, Object singleton) { + EzyBeanKey key = of(name, type); + if(objectsByKey.containsKey(key)) + return; + objectsByKey.put(key, singleton); + } + + @Override + public Object getSingleton(String name, Class type) { + String realname = translateBeanName(name, type); + return objectsByKey.get(of(realname, type)); + } + + @Override + public Object getSingleton(Map properties) { + for(Entry entry : objectsByProperties.entrySet()) + if(EzyMaps.containsAll(entry.getValue(), properties)) + return entry.getKey(); + return null; + } + + @Override + public List getSingletons(Map properties) { + List list = new ArrayList<>(); + for(Entry entry : objectsByProperties.entrySet()) + if(EzyMaps.containsAll(entry.getValue(), properties)) + list.add(entry.getKey()); + return list; + } + + @Override + public List getSingletons(Class annoClass) { + List list = new ArrayList<>(); + for(EzyBeanKey key : objectsByKey.keySet()) { + Class type = key.getType(); + if(type.isAnnotationPresent(annoClass)) + list.add(objectsByKey.get(type)); + } + return list; + } + + @Override + public Map getProperties(Object singleton) { + return objectsByProperties.get(singleton); + } + + private String getBeanName(Class type) { + return EzyBeanNameParser.getSingletonName(type); + } + + private Map getProperties(Class type) { + return EzyKeyValueParser.getSingletonProperties(type); + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonLoader.java new file mode 100644 index 00000000..c3436820 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySimpleSingletonLoader.java @@ -0,0 +1,200 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import java.lang.reflect.Constructor; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPropertyFetcher; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.bean.exception.EzyNewSingletonException; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; + +@SuppressWarnings("rawtypes") +public abstract class EzySimpleSingletonLoader + extends EzySimpleObjectBuilder + implements EzySingletonLoader { + + protected final Object configurator; + protected final Map, EzyMethod> methodsByType; + + protected EzySimpleSingletonLoader(EzyClass clazz) { + this(clazz, null, new HashMap<>()); + } + + protected EzySimpleSingletonLoader( + EzyClass clazz, Object configurator, Map, EzyMethod> methodsByType) { + super(clazz); + this.configurator = configurator; + this.methodsByType = methodsByType; + } + + @Override + public final Object load(EzyBeanContext context) { + try { + return process(context); + } + catch(EzyNewSingletonException e) { + throw e; + } + catch(Exception e) { + throw new IllegalStateException("can not create singleton of class " + clazz, e); + } + } + + protected Class getSingletonClass() { + return clazz.getClazz(); + } + + private Object process(EzyBeanContext context) throws Exception { + EzySingletonFactory factory = context.getSingletonFactory(); + Class[] parameterTypes = getConstructorParameterTypes(); + StringBuilder log = new StringBuilder().append(getSingletonClass()); + detectCircularDependency(parameterTypes, log); + String name = getSingletonName(); + Object singleton = getOrCreateSingleton(context, name, parameterTypes); + Map properties = getAnnotationProperties(); + Object answer = factory.addSingleton(name, singleton, properties); + setPropertiesToFields(singleton, context); + setPropertiesToMethods(singleton, context); + setValueToBindingFields(answer, context); + setValueToBindingMethods(answer, context); + callPostInit(answer); + return answer; + } + + private Object getOrCreateSingleton( + EzyBeanContext context, + String name, Class[] parameterTypes) throws Exception { + EzySingletonFactory factory = context.getSingletonFactory(); + Object singleton = factory.getSingleton(name, getSingletonClass()); + if(singleton == null) { + singleton = newSingletonByConstructor(context, parameterTypes); + getLogger().debug("add singleton with name {} of {}, object = {}", name, singleton.getClass(), singleton); + } + return singleton; + } + + protected String getSingletonName() { + return EzyBeanNameParser.getSingletonName(getSingletonClass()); + } + + protected Map getAnnotationProperties() { + return EzyKeyValueParser.getSingletonProperties(getSingletonClass()); + } + + protected abstract Object newSingletonByConstructor( + EzyBeanContext context, Class[] parameterTypes) throws Exception; + + private void setPropertiesToFields(Object singleton, EzyPropertyFetcher fetcher) { + for(EzyField field : propertyFields) + setValueToPropertyField(field, singleton, fetcher); + } + + @SuppressWarnings("unchecked") + private void setValueToPropertyField(EzyField field, Object singleton, EzyPropertyFetcher fetcher) { + String propertyName = getPropertyName(field); + if(fetcher.containsProperty(propertyName)) + field.set(singleton, fetcher.getProperty(propertyName, field.getType())); + } + + private void setPropertiesToMethods(Object singleton, EzyPropertyFetcher fetcher) { + for(EzySetterMethod method : propertyMethods) + setValueToPropertyMethod(method, singleton, fetcher); + } + + @SuppressWarnings("unchecked") + private void setValueToPropertyMethod(EzySetterMethod method, Object singleton, EzyPropertyFetcher fetcher) { + String propertyName = getPropertyName(method); + if(fetcher.containsProperty(propertyName)) + method.invoke(singleton, fetcher.getProperty(propertyName, method.getType())); + } + + private void setValueToBindingFields(Object singleton, EzyBeanContext context) { + for(EzyField field : bindingFields) + setValueToBindingField(field, singleton, context); + } + + private void setValueToBindingField(EzyField field, Object singleton, EzyBeanContext context) { + Object value = getOrCreateSingleton( + field.getType(), getBeanName(field), context); + field.set(singleton, value); + getLogger().debug("{} set field: {} with value: {}", clazz, field.getName(), value); + } + + private void setValueToBindingMethods(Object singleton, EzyBeanContext context) { + for(EzySetterMethod method : bindingMethods) + setValueToBindingMethod(method, singleton, context); + } + + private void setValueToBindingMethod( + EzySetterMethod method, Object singleton, EzyBeanContext context) { + Object value = getOrCreateSingleton( + method.getType(), getBeanName(method), context); + method.invoke(singleton, value); + getLogger().debug("{} invoke method: {} with value: {}", clazz, method.getName(), value); + } + + private void callPostInit(Object singleton) { + List methods = getPostInitMethods(); + methods.forEach(m -> m.invoke(singleton)); + } + + protected final Object[] getArguments(Class[] parameterTypes, EzyBeanContext context) { + Object[] arguments = new Object[parameterTypes.length]; + String[] argumentNames = getConstructorArgumentNames(); + for(int i = 0 ; i < parameterTypes.length ; i++) { + arguments[i] = getOrCreateSingleton(parameterTypes[i], argumentNames[i], context); + } + return arguments; + } + + private Object getOrCreateSingleton( + Class type, String beanName, EzyBeanContext context) { + EzySingletonFactory factory = context.getSingletonFactory(); + Object singleton = factory.getSingleton(beanName, type); + if(singleton == null) + singleton = createNewSingleton(type, beanName, context); + return singleton; + } + + private Object createNewSingleton( + Class paramType, String beanName, EzyBeanContext context) { + EzyMethod method = methodsByType.remove(paramType); + if(method != null) { + getLogger().debug("add singleton of {} with method {}", paramType, method); + return new EzyByMethodSingletonLoader(method, configurator, methodsByType).load(context); + } + if(isAbstractClass(paramType)) { + throw new EzyNewSingletonException(getSingletonClass(), paramType, beanName); + } + return new EzyByConstructorSingletonLoader(new EzyClass(paramType)).load(context); + } + + protected void detectCircularDependency(Class[] parameterTypes, StringBuilder log) { + for(Class paramType : parameterTypes) { + log.append(" => ").append(paramType); + if(paramType.equals(clazz.getClazz())) { + throw new IllegalStateException("circular dependency detected, " + log); + } + else { + detectCircularDependency(getConstructorParameterTypes(paramType), log); + } + } + } + + protected Class[] getConstructorParameterTypes(Class clazz) { + try { + Constructor constructor = getConstructor(new EzyClass(clazz)); + return constructor.getParameterTypes(); + } + catch(Exception e) { + return new Class[0]; + } + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySingletonLoader.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySingletonLoader.java new file mode 100644 index 00000000..76311a7a --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/impl/EzySingletonLoader.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.bean.impl; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; + +public interface EzySingletonLoader { + + Object load(EzyBeanContext context); + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyArrayListSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyArrayListSupplier.java new file mode 100644 index 00000000..3a593747 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyArrayListSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.ArrayList; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyArrayListSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new ArrayList<>(); + } + + @Override + public Class getObjectType() { + return ArrayList.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCollectionSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCollectionSupplier.java new file mode 100644 index 00000000..9d067660 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCollectionSupplier.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.ArrayList; +import java.util.Collection; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyCollectionSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new ArrayList<>(); + } + + @Override + public Class getObjectType() { + return Collection.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyConcurrentHashMapSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyConcurrentHashMapSupplier.java new file mode 100644 index 00000000..7bba52f1 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyConcurrentHashMapSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyConcurrentHashMapSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new ConcurrentHashMap<>(); + } + + @Override + public Class getObjectType() { + return ConcurrentHashMap.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArrayListSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArrayListSupplier.java new file mode 100644 index 00000000..e4bf961e --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArrayListSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.concurrent.CopyOnWriteArrayList; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyCopyOnWriteArrayListSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new CopyOnWriteArrayList<>(); + } + + @Override + public Class getObjectType() { + return CopyOnWriteArrayList.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArraySetSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArraySetSupplier.java new file mode 100644 index 00000000..f16367a6 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyCopyOnWriteArraySetSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.concurrent.CopyOnWriteArraySet; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyCopyOnWriteArraySetSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new CopyOnWriteArraySet<>(); + } + + @Override + public Class getObjectType() { + return CopyOnWriteArraySet.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashMapSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashMapSupplier.java new file mode 100644 index 00000000..f22bfb0d --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashMapSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.HashMap; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyHashMapSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new HashMap<>(); + } + + @Override + public Class getObjectType() { + return HashMap.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashSetSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashSetSupplier.java new file mode 100644 index 00000000..4e82da13 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyHashSetSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.HashSet; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyHashSetSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new HashSet<>(); + } + + @Override + public Class getObjectType() { + return HashSet.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyLinkedListSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyLinkedListSupplier.java new file mode 100644 index 00000000..dcfe099d --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyLinkedListSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.LinkedList; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyLinkedListSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new LinkedList<>(); + } + + @Override + public Class getObjectType() { + return LinkedList.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyListSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyListSupplier.java new file mode 100644 index 00000000..32fe74a6 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyListSupplier.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.ArrayList; +import java.util.List; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyListSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new ArrayList<>(); + } + + @Override + public Class getObjectType() { + return List.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyMapSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyMapSupplier.java new file mode 100644 index 00000000..2144b95f --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyMapSupplier.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyMapSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new HashMap<>(); + } + + @Override + public Class getObjectType() { + return Map.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyQueueSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyQueueSupplier.java new file mode 100644 index 00000000..327fdaf0 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyQueueSupplier.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.LinkedList; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyQueueSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new LinkedList<>(); + } + + @Override + public Class getObjectType() { + return Queue.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzySetSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzySetSupplier.java new file mode 100644 index 00000000..f07a7b85 --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzySetSupplier.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.HashSet; +import java.util.Set; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzySetSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new HashSet<>(); + } + + @Override + public Class getObjectType() { + return Set.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyStackSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyStackSupplier.java new file mode 100644 index 00000000..27fd17be --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyStackSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.Stack; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyStackSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new Stack<>(); + } + + @Override + public Class getObjectType() { + return Stack.class; + } + +} diff --git a/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyTreeMapSupplier.java b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyTreeMapSupplier.java new file mode 100644 index 00000000..9bb1217c --- /dev/null +++ b/ezyfox-server-bean/src/main/java/com/tvd12/ezyfoxserver/bean/supplier/EzyTreeMapSupplier.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.supplier; + +import java.util.TreeMap; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; + +public class EzyTreeMapSupplier implements EzyPrototypeSupplier { + + @Override + public Object supply(EzyBeanContext context) { + return new TreeMap<>(); + } + + @Override + public Class getObjectType() { + return TreeMap.class; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanKeyTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanKeyTest.java new file mode 100644 index 00000000..9808b132 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanKeyTest.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzyBeanKey; +import com.tvd12.test.base.BaseTest; + +public class EzyBeanKeyTest extends BaseTest { + + @Test + public void test() { + new EzyBeanKey("hello", getClass()).toString(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameParserTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameParserTest.java new file mode 100644 index 00000000..deab59dd --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameParserTest.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.bean.impl.EzyBeanNameParser; +import com.tvd12.test.base.BaseTest; + +public class EzyBeanNameParserTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyBeanNameParser.class; + } + + @Test + public void test() { + assert EzyBeanNameParser.getBeanName(A.class).equals("x"); + assert EzyBeanNameParser.getBeanName(B.class).equals("y"); + assert EzyBeanNameParser.getBeanName(C.class).equals("c"); + } + + @EzyPrototype("x") + public static class A { + + } + + @EzySingleton("y") + public static class B { + + } + + public static class C { + + } +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameTranslatorTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameTranslatorTest.java new file mode 100644 index 00000000..9428da90 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyBeanNameTranslatorTest.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import java.util.HashMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.bean.testing.combine.ClassA12; +import com.tvd12.ezyfoxserver.bean.testing.combine.Singleton12; +import com.tvd12.ezyfoxserver.bean.testing.combine.SingletonX1; +import com.tvd12.ezyfoxserver.bean.testing.combine.SingletonX2; +import com.tvd12.ezyfoxserver.bean.testing.combine.SingletonX3; +import com.tvd12.ezyfoxserver.properties.EzySimplePropertiesReader; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.test.base.BaseTest; + +public class EzyBeanNameTranslatorTest extends BaseTest { + + @Test + public void test() { + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .scan( + "com.tvd12.ezyfoxserver.bean.testing.combine" + ) + .addProperties(new HashMap<>()) + .propertiesReader(new EzySimplePropertiesReader()) + .addSingletonClasses(new Class[] { + SingletonX1.class, + SingletonX2.class, + Singleton12.class + }) + .addPrototypeClasses(new Class[] { + ClassA12.class + }) + .addSingleton("singleton2", new SingletonX3()); + EzyBeanContext context = builder.build(); + EzyBeanNameTranslator translator = context.getBeanNameTranslator(); + translator.map("map", ConcurrentHashMap.class, EzyClasses.getVariableName(ConcurrentHashMap.class)); + Object concurrentHashMap = context.getBean(ConcurrentHashMap.class); + assert concurrentHashMap != null; + Object map = context.getBean("map", ConcurrentHashMap.class); + assert map != null; + assert map instanceof ConcurrentHashMap; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldPrototypeSupplierBuilderTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldPrototypeSupplierBuilderTest.java new file mode 100644 index 00000000..f7299bfb --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldPrototypeSupplierBuilderTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzyByFieldPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyFields; + +public class EzyByFieldPrototypeSupplierBuilderTest { + + public ClassA classA; + + @Test + public void test() throws Exception { + EzyByFieldPrototypeSupplierLoader.setDebug(true); + + EzyField field = new EzyField(EzyFields.getField(getClass(), "classA")); + EzyByFieldPrototypeSupplierLoader builder = new EzyByFieldPrototypeSupplierLoader( + field, this); + builder.load(new EzySimplePrototypeFactory()); + } + + public static class ClassA { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldSingletonLoaderTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldSingletonLoaderTest.java new file mode 100644 index 00000000..227ea1d5 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByFieldSingletonLoaderTest.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import java.util.HashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzyByFieldSingletonLoader; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.test.base.BaseTest; + +public class EzyByFieldSingletonLoaderTest extends BaseTest { + + public A a; + + @Test + public void test() throws Exception { + ExEzyByFieldSingletonLoader loader = new ExEzyByFieldSingletonLoader( + new EzyField(getClass().getDeclaredField("a")), this); + loader.getConstructorArgumentNames(); + loader.getConstructorParameterTypes(getClass()); + } + + public static class ExEzyByFieldSingletonLoader extends EzyByFieldSingletonLoader { + public ExEzyByFieldSingletonLoader(EzyField field, Object configurator) { + super(field, configurator, new HashMap<>()); + } + + @Override + public String[] getConstructorArgumentNames() { + return super.getConstructorArgumentNames(); + } + + @SuppressWarnings("rawtypes") + @Override + public Class[] getConstructorParameterTypes(Class clazz) { + return super.getConstructorParameterTypes(clazz); + } + } + + public static class A { + public String value = "v"; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByMethodSingletonLoaderTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByMethodSingletonLoaderTest.java new file mode 100644 index 00000000..aeef5ec3 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyByMethodSingletonLoaderTest.java @@ -0,0 +1,50 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import java.lang.reflect.Method; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.impl.EzyByMethodSingletonLoader; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyByMethodSingletonLoaderTest extends BaseTest { + + public A newA() { + return new A(); + } + + public B newB() { + return new B(); + } + + @Test + public void test() throws Exception { + EzyBeanContext context = EzyBeanContext.builder() + .build(); + EzyMethod methodA = new EzyMethod(getClass().getDeclaredMethod("newA")); + EzyMethod methodB = new EzyMethod(getClass().getDeclaredMethod("newB")); + EzyByMethodSingletonLoader loader = new EzyByMethodSingletonLoader( + methodA, this, EzyMaps.newHashMap(B.class, methodB)); + loader.load(context); + + Method getConstructorParameterTypes = EzyByMethodSingletonLoader.class + .getDeclaredMethod("getConstructorParameterTypes", Class.class); + getConstructorParameterTypes.setAccessible(true); + getConstructorParameterTypes.invoke(loader, B.class); + getConstructorParameterTypes.invoke(loader, Object.class); + } + + public static class A { + @EzyAutoBind + public B b; + } + + public static class B { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationBeforeClassSorterTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationBeforeClassSorterTest.java new file mode 100644 index 00000000..171db92d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationBeforeClassSorterTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import com.tvd12.ezyfoxserver.bean.impl.EzyConfigurationBeforeClassSorter; +import com.tvd12.test.base.BaseTest; + +public class EzyConfigurationBeforeClassSorterTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyConfigurationBeforeClassSorter.class; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationClassSorterTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationClassSorterTest.java new file mode 100644 index 00000000..cefab697 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyConfigurationClassSorterTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import com.tvd12.ezyfoxserver.bean.impl.EzyConfigurationClassSorter; +import com.tvd12.test.base.BaseTest; + +public class EzyConfigurationClassSorterTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyConfigurationClassSorter.class; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyKeyValueParserTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyKeyValueParserTest.java new file mode 100644 index 00000000..956f81b8 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzyKeyValueParserTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import com.tvd12.ezyfoxserver.bean.impl.EzyKeyValueParser; +import com.tvd12.test.base.BaseTest; + +public class EzyKeyValueParserTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyKeyValueParser.class; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimplePrototypeFactoryTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimplePrototypeFactoryTest.java new file mode 100644 index 00000000..ab532980 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimplePrototypeFactoryTest.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.test.base.BaseTest; + +public class EzySimplePrototypeFactoryTest extends BaseTest { + + @Test + public void test() { + EzySimplePrototypeFactory factory = new EzySimplePrototypeFactory(); + factory.addSupplier("classA2", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassA2(); + } + + @Override + public Class getObjectType() { + return ClassA2.class; + } + }); + factory.addSupplier("classA1", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassA2(); + } + + @Override + public Class getObjectType() { + return ClassA2.class; + } + }); + factory.addSupplier("classA2", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassA2(); + } + + @Override + public Class getObjectType() { + return ClassA2.class; + } + }); + assert factory.getSupplier("classA2", ClassA2.class) != null; + assert factory.getSupplier("classA1", ClassA1.class) == null; + } + + @EzyPrototype(properties = { + @EzyKeyValue(key = "hello", value = "world") + }) + public static class ClassA1 { + + } + + @EzyPrototype(properties = { + @EzyKeyValue(key = "hello", value = "world") + }) + public static class ClassA2 { + + } + + public static void main(String[] args) { + System.out.println(Object.class.getSuperclass()); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimpleSingletonFactoryTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimpleSingletonFactoryTest.java new file mode 100644 index 00000000..7b9e3068 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/EzySimpleSingletonFactoryTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleSingletonFactory; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleSingletonFactoryTest extends BaseTest { + + @Test + public void test() { + EzySimpleSingletonFactory factory = new EzySimpleSingletonFactory(); + factory.addSingleton("a", new A()); + assert factory.getSingleton("a", A1.class) == null; + } + + public static class A { + + } + + public static class A1 { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/SuperAndInterfaceTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/SuperAndInterfaceTest.java new file mode 100644 index 00000000..bd7d599e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/SuperAndInterfaceTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean.testing; + +import java.util.Arrays; + +public class SuperAndInterfaceTest { + + public static void main(String[] args) { + System.out.println(Arrays.toString(B.class.getInterfaces())); + } + + public static interface A { + + } + + public static interface B extends A { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ClassA.java new file mode 100644 index 00000000..a45cf6cf --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ClassA.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.bean.testing.annotation; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@IncludeAnnotation(properties = { + @EzyKeyValue(key = "hello", value = "world") +}) +@EzyPrototype(value = "hello", properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "1"), + @EzyKeyValue(key = "priority", value = "1") +}) +public class ClassA { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ExampleAnnotation.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ExampleAnnotation.java new file mode 100644 index 00000000..00756999 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/ExampleAnnotation.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.bean.testing.annotation; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.LOCAL_VARIABLE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PACKAGE; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_PARAMETER; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Documented +@Retention(RUNTIME) +@Target({ + TYPE, + FIELD, + METHOD, + PARAMETER, + CONSTRUCTOR, + LOCAL_VARIABLE, + ANNOTATION_TYPE, + PACKAGE, + TYPE_PARAMETER, + TYPE_USE +}) +public @interface ExampleAnnotation { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/IncludeAnnotation.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/IncludeAnnotation.java new file mode 100644 index 00000000..38511e77 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/annotation/IncludeAnnotation.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.bean.testing.annotation; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.LOCAL_VARIABLE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PACKAGE; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_PARAMETER; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +@Documented +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, + TYPE_USE }) +public @interface IncludeAnnotation { + + EzyKeyValue[] properties() default {}; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassA.java new file mode 100644 index 00000000..c430ef6e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassA.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.circular; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class ClassA { + + @EzyAutoBind + public ClassA(ClassC classC) { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassB.java new file mode 100644 index 00000000..a98253bd --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassB.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.circular; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class ClassB { + + @EzyAutoBind + public ClassB(ClassA classA) { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassC.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassC.java new file mode 100644 index 00000000..7f653187 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/ClassC.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.circular; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class ClassC { + + @EzyAutoBind + public ClassC(ClassB classB) { + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/GeneratedClassAFactory2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/GeneratedClassAFactory2.java new file mode 100644 index 00000000..41289c00 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/circular/GeneratedClassAFactory2.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.bean.testing.circular; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzyPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class GeneratedClassAFactory2 { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyPrototypeSupplierLoader builder = + new EzyByConstructorPrototypeSupplierLoader(new EzyClass(ClassA.class)); + + EzyPrototypeSupplier supplier = builder.load(new EzySimplePrototypeFactory()); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.circular") + .build(); + System.out.println(supplier.getObjectType()); + supplier.supply(context); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/ClassA12.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/ClassA12.java new file mode 100644 index 00000000..e8f3b2e9 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/ClassA12.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack1.ClassA1; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack2.ClassA2; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class ClassA12 { + + @EzyAutoBind + private Singleton12 singleton12; + + @EzyAutoBind("a1") + private ClassA1 classA1; + + @EzyAutoBind("a2") + private ClassA2 classA2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Combine2Test.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Combine2Test.java new file mode 100644 index 00000000..c5821458 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Combine2Test.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import java.lang.reflect.Field; +import java.util.HashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack1.Singleton1; +import com.tvd12.ezyfoxserver.properties.EzySimplePropertiesReader; + +public class Combine2Test { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .scan( + "com.tvd12.ezyfoxserver.bean.testing.combine" + ) + .addProperties(new HashMap<>()) + .propertiesReader(new EzySimplePropertiesReader()) + .addSingletonClasses(new Class[] { + SingletonX1.class, + SingletonX2.class, + Singleton12.class + }) + .addPrototypeClasses(new Class[] { + ClassA12.class + }) + .addSingleton("singleton2", new SingletonX3()); + + Field prototypeFactoryField = EzySimpleBeanContext.Builder.class + .getDeclaredField("prototypeFactory"); + prototypeFactoryField.setAccessible(true); + EzyPrototypeFactory prototypeFactory = (EzyPrototypeFactory) prototypeFactoryField.get(builder); + prototypeFactory.addSupplier(new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassA12(); + } + + @Override + public Class getObjectType() { + return ClassA12.class; + } + }); + + EzyBeanContext context = builder.build(); + SingletonX1 x1 = (SingletonX1) context.getBean("singletonX1", SingletonX1.class); + SingletonX2 x2 = (SingletonX2) context.getBean("singletonX2", SingletonX2.class); + + assert x1.getSingletonX1() == x1; + assert x1.getSingletonX2() == x2; + assert x2.getSingletonX1() == x1; + assert x2.getSingletonX2() == x2; + + Singleton1 singleton1 = (Singleton1) context.getBean("s1", Singleton1.class); + assert singleton1 != null; + assert singleton1.getMap() != null; + + ClassA12 a121 = (ClassA12) context.getBean("classA12", ClassA12.class); + ClassA12 a122 = (ClassA12) context.getBean("classA12", ClassA12.class); + assert a121 != a122; + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/CombineTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/CombineTest.java new file mode 100644 index 00000000..67122f94 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/CombineTest.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack1.ClassA1; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack1.Singleton1; + +public class CombineTest { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .scan( + "com.tvd12.ezyfoxserver.bean.testing.combine.pack0", + "com.tvd12.ezyfoxserver.bean.testing.combine.pack1", + "com.tvd12.ezyfoxserver.bean.testing.combine.pack2" + ) + .addProperty("hello", "world") + .addProperty("foo", "bar") + .addProperty("array", "1,2,3,4,5") + .addProperty("ints", Lists.newArrayList(1, 2, 3)) + .addSingletonClasses(new Class[] { + SingletonX1.class, + SingletonX2.class, + Singleton12.class + }) + .addPrototypeClasses(new Class[] { + ClassA12.class + }) + .addSingleton("singleton2", new SingletonX3()); + EzyBeanContext context = builder.build(); + SingletonX1 x1 = (SingletonX1) context.getBean("singletonX1", SingletonX1.class); + SingletonX2 x2 = (SingletonX2) context.getBean("singletonX2", SingletonX2.class); + + assert x1.getSingletonX1() == x1; + assert x1.getSingletonX2() == x2; + assert x2.getSingletonX1() == x1; + assert x2.getSingletonX2() == x2; + + Singleton1 singleton1 = (Singleton1) context.getBean("s1", Singleton1.class); + assert singleton1 != null; + assert singleton1.getMap() != null; + + ClassA12 a121 = (ClassA12) context.getBean("classA12", ClassA12.class); + ClassA12 a122 = (ClassA12) context.getBean("classA12", ClassA12.class); + assert a121 != a122; + + EzySingletonFactory singletonFactory = context.getSingletonFactory(); + EzyPrototypeFactory prototypeFactory = context.getPrototypeFactory(); + + EzyPrototypeSupplier a1Supplier = prototypeFactory.getSupplier("a1", ClassA1.class); + prototypeFactory.getProperties(a1Supplier); + + Object s1Singleton = singletonFactory.getSingleton("s1", Object.class); + singletonFactory.getProperties(s1Singleton); + + List singletons = singletonFactory.getSingletons(EzyCombine0Ann.class); + assert singletons.size() == 2; + + List prototypeSuppliers = prototypeFactory.getSuppliers(EzyCombine0Ann.class); + assert prototypeSuppliers.size() == 2; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/EzyCombine0Ann.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/EzyCombine0Ann.java new file mode 100644 index 00000000..ef321026 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/EzyCombine0Ann.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD }) +public @interface EzyCombine0Ann { + + String value() default ""; + + EzyKeyValue[] properties() default {}; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Singleton12.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Singleton12.java new file mode 100644 index 00000000..a35b5e9a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/Singleton12.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack1.Singleton1; +import com.tvd12.ezyfoxserver.bean.testing.combine.pack2.Singleton2; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Singleton12 { + + @EzyAutoBind("s1") + private Singleton1 singleton1; + + @EzyAutoBind("s2") + private Singleton2 singleton2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX1.java new file mode 100644 index 00000000..20395229 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX1.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class SingletonX1 { + + @EzyAutoBind("") + private SingletonX1 singletonX1; + + @EzyAutoBind + private SingletonX2 singletonX2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX2.java new file mode 100644 index 00000000..ee9a705a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX2.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class SingletonX2 { + + @EzyAutoBind + private SingletonX1 singletonX1; + + @EzyAutoBind + private SingletonX2 singletonX2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX3.java new file mode 100644 index 00000000..b6aa826c --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/SingletonX3.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine; + +public class SingletonX3 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/Configuration1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/Configuration1.java new file mode 100644 index 00000000..9189ffde --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/Configuration1.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack0; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPackagesScan; +import com.tvd12.ezyfoxserver.util.EzyPropertiesAware; + +import java.util.Properties; + +import com.tvd12.ezyfoxserver.bean.EzyBeanConfig; +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; + +@EzyConfiguration +@EzyPackagesScan({"com.tvd12.ezyfoxserver.bean.testing.combine.pack3"}) +public class Configuration1 implements EzyBeanConfig, EzyPropertiesAware { + + @Override + public void setProperties(Properties properties) { + } + + @Override + public void config() { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration1.java new file mode 100644 index 00000000..db31f403 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration1.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack0; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfigurationBefore; +import com.tvd12.ezyfoxserver.bean.testing.combine.EzyCombine0Ann; + +@EzyCombine0Ann +@EzyConfigurationBefore(priority = 0) +public class FirstConfiguration1 { + + public FirstConfiguration1() { + System.out.println("\nHi! I will init before load bean, my priority = 0\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration2.java new file mode 100644 index 00000000..d929438b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack0/FirstConfiguration2.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack0; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfigurationBefore; + +@EzyConfigurationBefore(priority = -1) +public class FirstConfiguration2 { + + public FirstConfiguration2() { + System.out.println("\nHi! I will init before load bean, my priority = -1\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/ClassA1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/ClassA1.java new file mode 100644 index 00000000..c2f8f375 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/ClassA1.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack1; + +import com.tvd12.ezyfoxserver.annotation.EzyProperty; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.testing.combine.EzyCombine0Ann; + +import lombok.Setter; + +@Setter +@EzyCombine0Ann +@EzyPrototype("a1") +public class ClassA1 { + + @EzyProperty("hello") + private String hello; + + @EzyProperty + public String foo; + + @EzyPostInit + public void post() { + System.out.println("\n\nI have hello = " + hello + ", and foo = " + foo + "\n\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/Singleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/Singleton1.java new file mode 100644 index 00000000..53e4f708 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack1/Singleton1.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack1; + +import java.util.HashMap; +import java.util.List; + +import com.tvd12.ezyfoxserver.annotation.EzyProperty; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.bean.testing.combine.EzyCombine0Ann; +import com.tvd12.ezyfoxserver.io.EzyPrints; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzyCombine0Ann +@EzySingleton("s1") +public class Singleton1 { + + @Setter + @EzyAutoBind + private HashMap map; + + @Setter + @EzyProperty("array") + private Integer[] array; + + @EzyProperty("ints") + public List ints; + + @EzyPostInit + public void post() { + System.out.println("\n\nsingleton1: I have array: " + EzyPrints.print(array) + ", and ints: " + EzyPrints.print(ints) + "\n\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ClassA2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ClassA2.java new file mode 100644 index 00000000..e8f58585 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ClassA2.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.testing.combine.EzyCombine0Ann; + +@EzyCombine0Ann +@EzyPrototype("a2") +public class ClassA2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ConfigurationPack2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ConfigurationPack2.java new file mode 100644 index 00000000..1fb4c88e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ConfigurationPack2.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzyConfiguration +public class ConfigurationPack2 { + + @EzySingleton + public ISingleton10 sgt10 = new ISingleton10() { + }; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton10.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton10.java new file mode 100644 index 00000000..192e42e1 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton10.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +public interface ISingleton10 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton21.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton21.java new file mode 100644 index 00000000..c595c8c4 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton21.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +public interface ISingleton21 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton22.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton22.java new file mode 100644 index 00000000..5f4f6af6 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/ISingleton22.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +public interface ISingleton22 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton2.java new file mode 100644 index 00000000..313e533b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton2.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +import java.util.ArrayList; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzySingleton("s2") +public class Singleton2 { + + @Setter + @EzyAutoBind + private ArrayList list; + + @Setter + @EzyAutoBind + private ISingleton10 sgt10; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton21.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton21.java new file mode 100644 index 00000000..9d7a2d1a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton21.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +import java.util.ArrayList; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzySingleton +public class Singleton21 implements ISingleton21 { + + @Setter + @EzyAutoBind + private ArrayList list; + + @Setter + @EzyAutoBind + private ISingleton10 sgt10; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton22.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton22.java new file mode 100644 index 00000000..ebb7215d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack2/Singleton22.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack2; + +import java.util.ArrayList; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzySingleton("s22") +public class Singleton22 { + + @Setter + @EzyAutoBind + private ArrayList list; + + @EzyAutoBind({"singleton21", "abc"}) + public Singleton22(ISingleton21 singleton21) { + + } + +// @EzyAutoBind({"singleton21", "abc"}) + public Singleton22(ISingleton21 singleton21, ISingleton10 singleton10, ISingleton22 singleton22) { + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/ClassA3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/ClassA3.java new file mode 100644 index 00000000..e5a802de --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/ClassA3.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype("a2") +public class ClassA3 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1.java new file mode 100644 index 00000000..ad8b94b1 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +public interface Pack3A1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1Impl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1Impl.java new file mode 100644 index 00000000..93769340 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A1Impl.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class Pack3A1Impl implements Pack3A1 { + + @EzyAutoBind + public Pack3A2 pack3A2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2.java new file mode 100644 index 00000000..043a3053 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +public interface Pack3A2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2Impl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2Impl.java new file mode 100644 index 00000000..f6dc91fa --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A2Impl.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class Pack3A2Impl implements Pack3A2 { + + @EzyAutoBind + public Pack3A3 pack3A3x; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3.java new file mode 100644 index 00000000..60d4829d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +public interface Pack3A3 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3Impl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3Impl.java new file mode 100644 index 00000000..c240dd3d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A3Impl.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class Pack3A3Impl implements Pack3A3 { + + @EzyAutoBind + public Pack3A4 pack3A4; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A4.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A4.java new file mode 100644 index 00000000..5bb387c7 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Pack3A4.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +public interface Pack3A4 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Singleton3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Singleton3.java new file mode 100644 index 00000000..b1bf5049 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine/pack3/Singleton3.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine.pack3; + +import java.util.ArrayList; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzySingleton("s3") +public class Singleton3 { + + @Setter + @EzyAutoBind + private ArrayList list; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Combine1Test.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Combine1Test.java new file mode 100644 index 00000000..6574aa2c --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Combine1Test.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine1; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.test.base.BaseTest; + +public class Combine1Test extends BaseTest { + + @Test + public void test() { + EzyBeanContext context = EzyBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.combine1") + .build(); + Singleton1 s1 = (Singleton1)context.getBean(Singleton1.class); + assert s1.getSingleton0() == context.getBean(Singleton0.class); + assert s1.getSingleton2() == context.getBean(Singleton2.class); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Configuration1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Configuration1.java new file mode 100644 index 00000000..94b4a7ee --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Configuration1.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@EzyConfiguration +public class Configuration1 extends EzyLoggable { + + @EzySingleton + public Singleton0 newSingleton0() { + getLogger().debug("\nnew singleton 0 call\n"); + return new Singleton0(); + } + + @EzySingleton + public Singleton1 newSingleton1() { + getLogger().debug("\nnew singleton 1 call\n"); + return new Singleton1(); + } + + @EzySingleton + public Singleton2 newSingleton2() { + getLogger().debug("\nnew singleton 2 call\n"); + return new Singleton2(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton0.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton0.java new file mode 100644 index 00000000..83bbd855 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton0.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine1; + +public class Singleton0 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton1.java new file mode 100644 index 00000000..d0292a02 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton1.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Singleton1 { + + @EzyAutoBind + private Singleton0 singleton0; + + @EzyAutoBind + private Singleton2 singleton2; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton2.java new file mode 100644 index 00000000..51b709a5 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine1/Singleton2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine1; + +public class Singleton2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/Combine2Test.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/Combine2Test.java new file mode 100644 index 00000000..7dc71eaa --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/Combine2Test.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleErrorHandler; + +public class Combine2Test { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .scan( + "com.tvd12.ezyfoxserver.bean.testing.combine2" + ) + .errorHandler(new EzySimpleErrorHandler()); + EzyBeanContext context = builder.build(); + context.getPrototypeFactory(); + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/A.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/A.java new file mode 100644 index 00000000..b69a92d6 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/A.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface A { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/AImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/AImpl.java new file mode 100644 index 00000000..f5fb4bdd --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/AImpl.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Setter; + +@EzySingleton +public class AImpl implements A { + + @EzyAutoBind + public B b; + + @EzyAutoBind + public C c; + + @EzyAutoBind + public D d; + + @Setter + @EzyAutoBind + private F f; + + @EzyAutoBind + public G g; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/B.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/B.java new file mode 100644 index 00000000..32471519 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/B.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface B { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/BImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/BImpl.java new file mode 100644 index 00000000..93dc9832 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/BImpl.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class BImpl implements B { + + @EzyAutoBind + public C c; + + @EzyAutoBind + public D d; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/C.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/C.java new file mode 100644 index 00000000..e4fdcfdc --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/C.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface C { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/CImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/CImpl.java new file mode 100644 index 00000000..5c053898 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/CImpl.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +import lombok.Setter; + +//@EzyCombine0Ann +public class CImpl implements C { + + @Setter + @EzyAutoBind + private F f; + + @EzyPostInit + public void done() { + System.out.println("\n\ni'm C and i'm done, my f = " + f + "\n\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/D.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/D.java new file mode 100644 index 00000000..b87a03a6 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/D.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface D { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/DImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/DImpl.java new file mode 100644 index 00000000..b6218ee3 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/DImpl.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class DImpl implements D { + + @EzyAutoBind + public C c; +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/E.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/E.java new file mode 100644 index 00000000..6deca4aa --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/E.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface E { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/EImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/EImpl.java new file mode 100644 index 00000000..e7506e8f --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/EImpl.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class EImpl implements E { + + @EzyAutoBind + public A a; + + @EzyAutoBind + public B b; + + @EzyAutoBind + public C c; + + @EzyAutoBind + public D d; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/F.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/F.java new file mode 100644 index 00000000..0c251ef6 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/F.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface F { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/FImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/FImpl.java new file mode 100644 index 00000000..08a694fc --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/FImpl.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class FImpl implements F { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/G.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/G.java new file mode 100644 index 00000000..b66bbb14 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/G.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +public interface G { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/Pack1Configuration.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/Pack1Configuration.java new file mode 100644 index 00000000..7f8b2144 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine2/pack1/Pack1Configuration.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine2.pack1; + +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslatorAware; +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Setter; + +@EzyConfiguration +public class Pack1Configuration implements EzyBeanNameTranslatorAware { + + @Setter + private EzyBeanNameTranslator beanNameTranslator; + + @EzySingleton + public C c = new CImpl(); + + @EzySingleton + public ClassA newClassA(ClassB classB) { + return new ClassA(); + } + + @EzySingleton + public ClassB newClassB() { + return new ClassB(); + } + + + public static class ClassA { + + } + + public static class ClassB { + + } +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/Combine3Test.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/Combine3Test.java new file mode 100644 index 00000000..3251bf1e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/Combine3Test.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleErrorHandler; +import com.tvd12.ezyfoxserver.bean.testing.combine3.pack1.A; +import com.tvd12.ezyfoxserver.bean.testing.combine3.pack1.H; + +public class Combine3Test { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .scan( + "com.tvd12.ezyfoxserver.bean.testing.combine3" + ) + .errorHandler(new EzySimpleErrorHandler()); + EzyBeanContext context = builder.build(); + A a = context.getSingleton("a", A.class); + H h = context.getSingleton("h", H.class); + assert a != null; + assert h != null; + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/A.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/A.java new file mode 100644 index 00000000..4dcd15d1 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/A.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface A { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/AImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/AImpl.java new file mode 100644 index 00000000..ae1d3cb8 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/AImpl.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class AImpl implements A { + + @EzyAutoBind + public AImpl(B b, C c, D d, E e, F f) { + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/B.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/B.java new file mode 100644 index 00000000..1f23b24e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/B.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface B { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/BImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/BImpl.java new file mode 100644 index 00000000..af7004a2 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/BImpl.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +//@EzyCombine0Ann +public class BImpl implements B { + +// @EzyAutoBind +// public C c; +// +// @EzyAutoBind +// public D d; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/C.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/C.java new file mode 100644 index 00000000..c9f0a12d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/C.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface C { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/CImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/CImpl.java new file mode 100644 index 00000000..098b96af --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/CImpl.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +//@EzyCombine0Ann +public class CImpl implements C { + +// @Setter +// @EzyAutoBind +// private F f; +// +// @EzyPostInit +// public void done() { +// System.out.println("\n\ni'm C and i'm done, my f = " + f + "\n\n"); +// } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/D.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/D.java new file mode 100644 index 00000000..29e59b7a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/D.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface D { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/DImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/DImpl.java new file mode 100644 index 00000000..c78133af --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/DImpl.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +//@EzyCombine0Ann +public class DImpl implements D { + +// @EzyAutoBind +// public C c; +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/E.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/E.java new file mode 100644 index 00000000..43e77354 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/E.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface E { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/EImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/EImpl.java new file mode 100644 index 00000000..e0df4506 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/EImpl.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class EImpl implements E { + + @EzyAutoBind + public EImpl(B b, C c, D d, F f) { + System.out.println("EImpl: b = " + b + ", c = " + c + ", d = " + d + ", f = " + f); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/F.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/F.java new file mode 100644 index 00000000..da1fa52c --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/F.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface F { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/FImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/FImpl.java new file mode 100644 index 00000000..b7caf1e4 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/FImpl.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class FImpl implements F { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/G.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/G.java new file mode 100644 index 00000000..25e00ea3 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/G.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface G { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/GImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/GImpl.java new file mode 100644 index 00000000..ca316f3c --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/GImpl.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class GImpl implements G { + + @EzyAutoBind + public GImpl(A a, E e, F f) { + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/H.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/H.java new file mode 100644 index 00000000..2a806fdd --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/H.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +public interface H { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/HImpl.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/HImpl.java new file mode 100644 index 00000000..236cf1c7 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/HImpl.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class HImpl implements H { + + @EzyAutoBind + public HImpl(A a, B b, C c, D d, E e, G g) { + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/Pack1Configuration.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/Pack1Configuration.java new file mode 100644 index 00000000..b9fb3bad --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/combine3/pack1/Pack1Configuration.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.bean.testing.combine3.pack1; + +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslator; +import com.tvd12.ezyfoxserver.bean.EzyBeanNameTranslatorAware; +import com.tvd12.ezyfoxserver.bean.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Setter; + +@EzyConfiguration +public class Pack1Configuration implements EzyBeanNameTranslatorAware { + + @Setter + private EzyBeanNameTranslator beanNameTranslator; + + @EzySingleton + public B b = new BImpl(); + + @EzySingleton + public C c = new CImpl(); + + @EzySingleton + public D d = new DImpl(); + + @EzySingleton + public ClassA newClassA(ClassB classB) { + return new ClassA(); + } + + @EzySingleton + public ClassB newClassB() { + return new ClassB(); + } + + + public static class ClassA { + + } + + public static class ClassB { + + } +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/AvailableSingleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/AvailableSingleton1.java new file mode 100644 index 00000000..c16f8499 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/AvailableSingleton1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class AvailableSingleton1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA.java new file mode 100644 index 00000000..9c5287fb --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +public class ConfigClassA { + + @EzySingleton + public Singleton1 singleton1 = new Singleton1(); + + @EzySingleton + public Singleton1 singleton1duplicate = new Singleton1(); + + @EzySingleton + public Singleton2 getSingleton2() { + return new Singleton2(); + } + + @EzySingleton + public Singleton3 getSingleton3(Singleton1 s1, SingletonA1 a1, Singleton3A2 a2) { + return new Singleton3(s1); + } + + @EzySingleton + public Singleton3A2 newSignleton3A2() { + return new Singleton3A2(); + } + + @EzySingleton + public void newInvalidSingleton() { + } + + public Singleton1 newDuplicateSingleton1() { + return new Singleton1(); + } + + @EzySingleton + public AvailableSingleton1 newAvailableSingleton1() { + return new AvailableSingleton1(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA2.java new file mode 100644 index 00000000..0dbc5709 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigClassA2.java @@ -0,0 +1,50 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +public class ConfigClassA2 { + + @EzySingleton + public Singleton1 singleton1 = new Singleton1(); + + @EzySingleton + public Singleton1 singleton1duplicate = new Singleton1(); + + @EzyPrototype + public PrototypeEx11 prototypeEx11 = new PrototypeEx11(); + + @EzySingleton + public Singleton2 getSingleton2() { + return new Singleton2(); + } + + @EzySingleton + public Singleton3 getSingleton3(Singleton1 s1, SingletonA1 a1, Singleton3A2 a2) { + return new Singleton3(s1); + } + + @EzySingleton + public Singleton3A2 newSignleton3A2() { + return new Singleton3A2(); + } + + @EzySingleton + public void newInvalidSingleton() { + } + + public Singleton1 newDuplicateSingleton1() { + return new Singleton1(); + } + + @EzySingleton + public AvailableSingleton1 newAvailableSingleton1() { + return new AvailableSingleton1(); + } + + @EzyPrototype + public PrototypeEx12 newPrototypeEx12() { + return new PrototypeEx12(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest1.java new file mode 100644 index 00000000..a48c83af --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest1.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleConfigurationLoader; +import com.tvd12.test.base.BaseTest; + +public class ConfigurationTest1 extends BaseTest { + + @Test + public void test() { + EzyBeanContext context = EzyBeanContext.builder().build(); + context.getSingletonFactory().addSingleton(new AvailableSingleton1()); + + new EzySimpleConfigurationLoader() + .clazz(ConfigClassA.class) + .context(context) + .load(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest2.java new file mode 100644 index 00000000..f513f583 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/ConfigurationTest2.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleConfigurationLoader; +import com.tvd12.test.base.BaseTest; + +public class ConfigurationTest2 extends BaseTest { + + @Test + public void test() { + EzyBeanContext context = EzyBeanContext.builder().build(); + context.getSingletonFactory().addSingleton(new Singleton1()); + context.getPrototypeFactory().addSupplier(new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new PrototypeEx11(); + } + + @Override + public Class getObjectType() { + return PrototypeEx11.class; + } + }); + + context.getPrototypeFactory().addSupplier(new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new PrototypeEx12(); + } + + @Override + public Class getObjectType() { + return PrototypeEx12.class; + } + }); + + new EzySimpleConfigurationLoader() + .clazz(ConfigClassA2.class) + .context(context) + .load(); + + + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/NotIncludeSingleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/NotIncludeSingleton1.java new file mode 100644 index 00000000..610bc0da --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/NotIncludeSingleton1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class NotIncludeSingleton1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx11.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx11.java new file mode 100644 index 00000000..b8d39a93 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx11.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class PrototypeEx11 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx12.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx12.java new file mode 100644 index 00000000..3382c1c2 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/PrototypeEx12.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class PrototypeEx12 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton0.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton0.java new file mode 100644 index 00000000..0b4ca11f --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton0.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class Singleton0 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton1.java new file mode 100644 index 00000000..a0c41578 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton1.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Singleton1 { + + @EzyAutoBind + private Singleton0 singleton0; + + @EzyPostInit + public void hi() { + System.out.println("\nHi! I come from Singleton1, do you know me?\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton2.java new file mode 100644 index 00000000..23f4973b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class Singleton2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3.java new file mode 100644 index 00000000..c6a77a87 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +import lombok.Getter; + +@Getter +public class Singleton3 { + + private final Singleton1 s1; + + public Singleton3(Singleton1 s1) { + this.s1 = s1; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3A2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3A2.java new file mode 100644 index 00000000..d732b516 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/Singleton3A2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class Singleton3A2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/SingletonA1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/SingletonA1.java new file mode 100644 index 00000000..00e383a0 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration/SingletonA1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration; + +public class SingletonA1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/AvailableSingleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/AvailableSingleton1.java new file mode 100644 index 00000000..521aff0f --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/AvailableSingleton1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class AvailableSingleton1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigClassA.java new file mode 100644 index 00000000..31c2c388 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigClassA.java @@ -0,0 +1,60 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextAware; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactory; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeFactoryAware; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactoryAware; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Setter; + +public class ConfigClassA + implements + EzyBeanContextAware, + EzySingletonFactoryAware, + EzyPrototypeFactoryAware { + + @Setter + private EzyBeanContext context; + @Setter + private EzySingletonFactory singletonFactory; + @Setter + private EzyPrototypeFactory prototypeFactory; + + @EzySingleton + public Singleton1 singleton1 = new Singleton1(); + + @EzySingleton + public Singleton1 singleton1duplicate = new Singleton1(); + + @EzySingleton + public Singleton2 getSingleton2() { + return new Singleton2(); + } + + @EzySingleton + public Singleton3 getSingleton3(Singleton1 s1, SingletonA1 a1, Singleton3A2 a2) { + return new Singleton3(s1); + } + + @EzySingleton + public Singleton3A2 newSignleton3A2() { + return new Singleton3A2(); + } + + @EzySingleton + public void newInvalidSingleton() { + } + + public Singleton1 newDuplicateSingleton1() { + return new Singleton1(); + } + + @EzySingleton + public AvailableSingleton1 newAvailableSingleton1() { + return new AvailableSingleton1(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigurationTest1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigurationTest1.java new file mode 100644 index 00000000..272431dd --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/ConfigurationTest1.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleConfigurationLoader; +import com.tvd12.test.base.BaseTest; + +public class ConfigurationTest1 extends BaseTest { + + @Test + public void test() { + EzyBeanContext context = EzyBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.configuration1") + .build(); + context.getSingletonFactory().addSingleton(new AvailableSingleton1()); + + new EzySimpleConfigurationLoader() + .clazz(ConfigClassA.class) + .context(context) + .load(); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton1.java new file mode 100644 index 00000000..eb486524 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class NotIncludeSingleton1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton2.java new file mode 100644 index 00000000..b6aa0610 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/NotIncludeSingleton2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class NotIncludeSingleton2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton0.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton0.java new file mode 100644 index 00000000..f9150a40 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton0.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class Singleton0 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton1.java new file mode 100644 index 00000000..07a6a403 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton1.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Singleton1 { + + @EzyAutoBind + private Singleton0 singleton0; + + @EzyPostInit + public void hi() { + System.out.println("\nHi! I come from Singleton1, do you know me?\n"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton2.java new file mode 100644 index 00000000..5623171e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class Singleton2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3.java new file mode 100644 index 00000000..bfaa334a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +import lombok.Getter; + +@Getter +public class Singleton3 { + + private final Singleton1 s1; + + public Singleton3(Singleton1 s1) { + this.s1 = s1; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3A2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3A2.java new file mode 100644 index 00000000..fd0bc93a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/Singleton3A2.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class Singleton3A2 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/SingletonA1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/SingletonA1.java new file mode 100644 index 00000000..5b3cd842 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration1/SingletonA1.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration1; + +public class SingletonA1 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigClass1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigClass1.java new file mode 100644 index 00000000..cfa21ccb --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigClass1.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; +import com.tvd12.ezyfoxserver.bean.testing.configuration.Singleton1; + +import lombok.Setter; + +public class ConfigClass1 { + + @Setter + @EzyAutoBind + private Singleton0 singleton0; + + @Setter + @EzyAutoBind + private Singleton1 singleton1; + + @EzyPrototype + public Prototype3 prototype3 = new Prototype3(); + + @EzyPrototype + public Prototype0 newPrototype0() { + return new Prototype0(); + } + + @EzyPrototype("p1") + public Prototype1 newPrototype1(Prototype0 prototype0) { + return new Prototype1(prototype0); + } + + @EzyPostInit + public void sayReady() { + System.out.println("I'm ready, I have " + singleton0); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigurationTest1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigurationTest1.java new file mode 100644 index 00000000..b285c7c2 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/ConfigurationTest1.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleConfigurationLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeSupplierLoader; +import com.tvd12.test.base.BaseTest; + +public class ConfigurationTest1 extends BaseTest { + + @Test + public void test() { + EzySimplePrototypeSupplierLoader.setDebug(true); + EzyBeanContext context = EzyBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.configuration2") + .build(); + + new EzySimpleConfigurationLoader() + .clazz(ConfigClass1.class) + .context(context) + .load(); + + context.getBean("p1", Prototype1.class); + + System.out.println("=========== second get ========="); + context.getBean("p1", Prototype1.class); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype0.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype0.java new file mode 100644 index 00000000..23ac3f46 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype0.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +public class Prototype0 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype1.java new file mode 100644 index 00000000..0870fc4b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype1.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Prototype1 { + + @Getter + private final Prototype0 prototype0; + + @EzyAutoBind + private Singleton0 singleton0; + + public Prototype1(Prototype0 prototype0) { + this.prototype0 = prototype0; + } + + @EzyPostInit + public void sayThank() { + System.out.println("thank you! I have " + prototype0 + " and " + singleton0); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype2.java new file mode 100644 index 00000000..ef7d8f9b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype2.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class Prototype2 { + + @Getter + private final Prototype0 prototype0; + + @EzyAutoBind + private Singleton0 singleton0; + + public Prototype2(Prototype0 prototype0) { + this.prototype0 = prototype0; + } + + @EzyPostInit + public void sayThank() { + System.out.println("thank you! I have " + prototype0 + " and " + singleton0); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype3.java new file mode 100644 index 00000000..eb26abec --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Prototype3.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +public class Prototype3 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Singleton0.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Singleton0.java new file mode 100644 index 00000000..cee42f5f --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/configuration2/Singleton0.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.configuration2; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class Singleton0 { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassA.java new file mode 100644 index 00000000..75cac3c9 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassA.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@EzyPrototype +public class ClassA { + + private final ClassB classB; + private final ClassD classD; + + @EzyAutoBind + @Setter + private ClassC classC; + + @EzyAutoBind + public ClassE classE; + + @EzyAutoBind("classB") + public ClassA(ClassB classB, ClassD classD) { + this.classB = classB; + this.classD = classD; + } + + @EzyPostInit + public void haha() { + System.out.println("hello world"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassB.java new file mode 100644 index 00000000..e8ce2428 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassB.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype +public class ClassB { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassC.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassC.java new file mode 100644 index 00000000..7e74c083 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassC.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype +public class ClassC { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassD.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassD.java new file mode 100644 index 00000000..877885a1 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassD.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype +public class ClassD { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassE.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassE.java new file mode 100644 index 00000000..15bedfd6 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/ClassE.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype +public class ClassE { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/EzySimplePrototypeSupplierBuilderTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/EzySimplePrototypeSupplierBuilderTest.java new file mode 100644 index 00000000..fecd34ce --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/EzySimplePrototypeSupplierBuilderTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.asm.EzyFunction.EzyBody; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzySimplePrototypeSupplierBuilderTest extends BaseTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() { + new ExSimplePrototypeSupplierBuilder( + new EzyClass(ClassA.class)).load(new EzySimplePrototypeFactory()); + } + + public static class ExSimplePrototypeSupplierBuilder extends EzyByConstructorPrototypeSupplierLoader { + + public ExSimplePrototypeSupplierBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected EzyInstruction newConstructInstruction(EzyBody body, List cparams) { + throw new RuntimeException(); + } + + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory.java new file mode 100644 index 00000000..04d3d23f --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory.java @@ -0,0 +1,79 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzyPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class GeneratedClassAFactory { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyPrototypeSupplierLoader builder = + new EzyByConstructorPrototypeSupplierLoader(new EzyClass(ClassA.class)); + + EzyPrototypeSupplier supplier = builder.load(new EzySimplePrototypeFactory()); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .addPrototypeSupplier("classB", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassB(); + } + + @Override + public Class getObjectType() { + return ClassB.class; + } + }) + .addPrototypeSupplier("classC", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassC(); + } + + @Override + public Class getObjectType() { + return ClassC.class; + } + }) + .addPrototypeSupplier("classD", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassD(); + } + + @Override + public Class getObjectType() { + return ClassD.class; + } + }) + .addPrototypeSupplier("classE", new EzyPrototypeSupplier() { + + @Override + public Object supply(EzyBeanContext context) { + return new ClassE(); + } + + @Override + public Class getObjectType() { + return ClassE.class; + } + }) + .build(); + System.out.println(supplier.getObjectType()); + ClassA classA = (ClassA) supplier.supply(context); + System.out.println(classA.getClassB()); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory2.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory2.java new file mode 100644 index 00000000..c10c209b --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory2.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzyPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class GeneratedClassAFactory2 { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyPrototypeSupplierLoader builder = + new EzyByConstructorPrototypeSupplierLoader(new EzyClass(ClassA.class)); + + EzyPrototypeSupplier supplier = builder.load(new EzySimplePrototypeFactory()); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.prototype") + .build(); + System.out.println(supplier.getObjectType()); + ClassA classA = (ClassA) supplier.supply(context); + System.out.println(classA.getClassB()); + classA = (ClassA) supplier.supply(context); + System.out.println(classA.getClassB()); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory3.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory3.java new file mode 100644 index 00000000..f8c9a0e3 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype/GeneratedClassAFactory3.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyPrototypeSupplier; +import com.tvd12.ezyfoxserver.bean.impl.EzyPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzySimplePrototypeFactory; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class GeneratedClassAFactory3 { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(false); + + EzyPrototypeSupplierLoader builder = + new EzyByConstructorPrototypeSupplierLoader(new EzyClass(ClassA.class)); + + EzyPrototypeSupplier supplier = builder.load(new EzySimplePrototypeFactory()); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.prototype") + .build(); + System.out.println(supplier.getObjectType()); + ClassA classA = (ClassA) supplier.supply(context); + System.out.println(classA.getClassB()); + classA = (ClassA) supplier.supply(context); + System.out.println(classA.getClassB()); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassA.java new file mode 100644 index 00000000..94a51e4a --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassA.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype(value = "hello", properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "1"), + @EzyKeyValue(key = "priority", value = "1") +}) +public class ClassA { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassB.java new file mode 100644 index 00000000..32912c59 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassB.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype(value = "hello", properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "2"), + @EzyKeyValue(key = "priority", value = "1") +}) +public class ClassB { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassC.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassC.java new file mode 100644 index 00000000..294520f1 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/ClassC.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +@EzyPrototype(value = "hello", properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "2"), + @EzyKeyValue(key = "priority", value = "-1") +}) +public class ClassC { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/EzySimpleBeanContextTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/EzySimpleBeanContextTest.java new file mode 100644 index 00000000..27f6b77d --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/prototype1/EzySimpleBeanContextTest.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.bean.testing.prototype1; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.util.EzyMapBuilder; + +public class EzySimpleBeanContextTest { + + @SuppressWarnings("unchecked") + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.prototype1") + .build(); + List prototypes = context.getPrototypes(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "2") + .build()); + System.out.println(prototypes); + assert prototypes.size() == 2; + + prototypes = context.getPrototypes(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "1") + .build()); + System.out.println(prototypes); + assert prototypes.size() == 1; + + Object prototype = context.getPrototype(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "1") + .build()); + assert prototype != null; + + prototype = context.getPrototype(EzyMapBuilder.mapBuilder() + .put("type", "request_listenerzz") + .put("cmd", "1zz") + .build()); + assert prototype == null; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassA.java new file mode 100644 index 00000000..c92ac1f2 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassA.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; + +@Getter +@EzySingleton("a") +public class ClassA { + + private String value1 = "1"; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassB.java new file mode 100644 index 00000000..d2903f71 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassB.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; + +@Getter +@EzySingleton("b") +public class ClassB { + + private String value2 = "2"; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassC.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassC.java new file mode 100644 index 00000000..d43858b4 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/ClassC.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; + +@Getter +@EzySingleton +public class ClassC { + + private String value3 = "3"; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/Combine.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/Combine.java new file mode 100644 index 00000000..2ba3f49e --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/Combine.java @@ -0,0 +1,84 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +import lombok.Getter; +import lombok.Setter; + +@EzySingleton +public class Combine { + + @Setter + @Getter + private ClassA classA; + + @Getter + private ClassA classA1; + + @Setter + @Getter + private ClassB classB; + + @Getter + private ClassB classB1; + + @Setter + @Getter + @EzyAutoBind + private ClassC classC; + + @Setter + @Getter + @EzyAutoBind("xa") + private XClassA xClassA; + + @EzyAutoBind + public XClassB xClassB; + + @EzyAutoBind + protected XClassB xClassB1; + + public XClassB xClassB2; + + @EzyAutoBind("xb") + public XClassB xClassB3; + + @EzyAutoBind({"a", "b"}) + public Combine(ClassA classA, ClassB classB) { + this.classA = classA; + this.classB = classB; + } + + @EzyAutoBind + public void setXClassB(XClassB xClassB) { + this.xClassB = xClassB; + } + + @EzyAutoBind + public void setXClassBB(XClassB xClassB) { + this.xClassB = xClassB; + } + + @EzyAutoBind + public void setClassA1(ClassA clazzA1) { + this.classA1 = clazzA1; + } + + @EzyAutoBind("b") + public void setClassB1(ClassB clazzB1) { + this.classB1 = clazzB1; + } + + @EzyPostInit + public void hello() { + System.out.println("hung dep trai"); + } + + @EzyPostInit + public void hello1(String value) { + System.out.println("hung dep trai"); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/EzySimpleBeanContextTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/EzySimpleBeanContextTest.java new file mode 100644 index 00000000..addeef4c --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/EzySimpleBeanContextTest.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; + +public class EzySimpleBeanContextTest { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.singleton") + .build(); + context.getBean("combine", Combine.class); + + Combine combine = (Combine) context.getBean("combine", Combine.class); + ClassA classA = (ClassA) context.getBean("a", ClassA.class); + assert classA != null; + assert combine.getClassA() != null; + assert combine.getClassA() == classA; + + XClassA xClassA = (XClassA) context.getBean("xa", XClassA.class); + assert xClassA != null; + assert combine.getXClassA() != null; + assert combine.getXClassA() == xClassA; + + assert context.getSingletonFactory().getSingleton("a", ClassA.class) == classA; + assert context.getPrototypeFactory() != null; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.singleton") + .build(); + context.getPrototype("unknown", Class.class); + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/SingletonTest1.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/SingletonTest1.java new file mode 100644 index 00000000..c4118d43 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/SingletonTest1.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; + +public class SingletonTest1 { + + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.singleton") + .build(); + context.getBean("combine", Combine.class); + + Combine combine = (Combine) context.getBean("combine", Combine.class); + ClassA classA = (ClassA) context.getBean("a", ClassA.class); + assert classA != null; + assert combine.getClassA() != null; + assert combine.getClassA() == classA; + + XClassA xClassA = (XClassA) context.getBean("xa", XClassA.class); + assert xClassA != null; + assert combine.getXClassA() != null; + assert combine.getXClassA() == xClassA; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassA.java new file mode 100644 index 00000000..e93a6b42 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassA.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton("xa") +public class XClassA { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassB.java new file mode 100644 index 00000000..0b482712 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton/XClassB.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton; + +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton +public class XClassB { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassA.java new file mode 100644 index 00000000..cd51aec5 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassA.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton(properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "1"), + @EzyKeyValue(key = "priority", value = "1") +}) +public class ClassA { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassB.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassB.java new file mode 100644 index 00000000..5a193fb4 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassB.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton(properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "2"), + @EzyKeyValue(key = "priority", value = "1") +}) +public class ClassB { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassC.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassC.java new file mode 100644 index 00000000..e7975f65 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/ClassC.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton1; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; + +@EzySingleton(properties = { + @EzyKeyValue(key = "type", value = "request_listener"), + @EzyKeyValue(key = "cmd", value = "2"), + @EzyKeyValue(key = "priority", value = "-1") +}) +public class ClassC { + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/EzySimpleBeanContextTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/EzySimpleBeanContextTest.java new file mode 100644 index 00000000..d42e1664 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/singleton1/EzySimpleBeanContextTest.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.bean.testing.singleton1; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.bean.impl.EzySimpleBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.impl.EzyByConstructorPrototypeSupplierLoader; +import com.tvd12.ezyfoxserver.util.EzyMapBuilder; + +public class EzySimpleBeanContextTest { + + @SuppressWarnings("unchecked") + @Test + public void test() throws Exception { + EzyByConstructorPrototypeSupplierLoader.setDebug(true); + + EzyBeanContext context = EzySimpleBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.singleton1") + .build(); + List singletons = context.getSingletons(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "2") + .build()); + System.out.println(singletons); + assert singletons.size() == 2; + assert singletons.containsAll(Lists.newArrayList( + context.getBean("classB", ClassB.class), + context.getBean("classC", ClassC.class) + )); + + singletons = context.getSingletons(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "1") + .build()); + System.out.println(singletons); + assert singletons.size() == 1; + assert singletons.containsAll(Lists.newArrayList( + context.getBean("classA", ClassA.class) + )); + + Object singleton = context.getSingleton(EzyMapBuilder.mapBuilder() + .put("type", "request_listener") + .put("cmd", "1") + .build()); + assert singleton == context.getBean("classA", ClassA.class); + + singleton = context.getSingleton(EzyMapBuilder.mapBuilder() + .put("type", "request_listenerzz") + .put("cmd", "1zz") + .build()); + assert singleton == null; + } + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/ClassA.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/ClassA.java new file mode 100644 index 00000000..6d5a4ccf --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/ClassA.java @@ -0,0 +1,59 @@ +package com.tvd12.ezyfoxserver.bean.testing.supplier; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPrototype; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyPrototype("ca") +@SuppressWarnings("rawtypes") +public class ClassA { + + @EzyAutoBind + private Map map; + @EzyAutoBind + private HashMap hashMap; + @EzyAutoBind + private ConcurrentHashMap concurrentHashMap; + @EzyAutoBind + private Set set; + @EzyAutoBind + private TreeMap treeMap; + @EzyAutoBind + private HashSet hashSet; + @EzyAutoBind + private CopyOnWriteArrayList copyOnWriteArrayList; + @EzyAutoBind + private CopyOnWriteArraySet copyOnWriteArraySet; + @EzyAutoBind + private LinkedList linkedList; + @EzyAutoBind + private Queue queue; + @EzyAutoBind + private List list; + @EzyAutoBind + private ArrayList arrayList; + @EzyAutoBind + private Stack stack; + @EzyAutoBind + private Collection collection; + +} diff --git a/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/SuppliersTest.java b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/SuppliersTest.java new file mode 100644 index 00000000..ec5a3e90 --- /dev/null +++ b/ezyfox-server-bean/src/test/java/com/tvd12/ezyfoxserver/bean/testing/supplier/SuppliersTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.bean.testing.supplier; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.test.base.BaseTest; + +public class SuppliersTest extends BaseTest { + + @Test + public void test() { + EzyBeanContext context = EzyBeanContext.builder() + .scan("com.tvd12.ezyfoxserver.bean.testing.supplier") + .build(); + ClassA classA = (ClassA)context.getBean(ClassA.class); + assert classA.getHashSet() != null; + } + +} diff --git a/ezyfox-server-bean/src/test/resources/AllTests.tng.xml b/ezyfox-server-bean/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..82a522c5 --- /dev/null +++ b/ezyfox-server-bean/src/test/resources/AllTests.tng.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-bean/src/test/resources/logback.xml b/ezyfox-server-bean/src/test/resources/logback.xml new file mode 100644 index 00000000..efd85297 --- /dev/null +++ b/ezyfox-server-bean/src/test/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-binding/assembly.xml b/ezyfox-server-binding/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-binding/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-binding/pom.xml b/ezyfox-server-binding/pom.xml new file mode 100644 index 00000000..fa35e83d --- /dev/null +++ b/ezyfox-server-binding/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-binding + 1.0.0 + ezyfox-server-binding + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyAccessType.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyAccessType.java new file mode 100644 index 00000000..7c6b702b --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyAccessType.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.binding; + +public final class EzyAccessType { + + public static final int NONE = 0x00; + public static final int FIELDS = 0x01; + public static final int METHODS = 0x02; + public static final int ALL = 0x03; + public static final int DECLARED_FIELDS = 0x04; + public static final int DECLARED_METHODS = 0x08; + public static final int DECLARED_ELEMENTS = 0x0C; + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingConfig.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingConfig.java new file mode 100644 index 00000000..b7b4d3c0 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingConfig.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyBindingConfig { + + void config(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContext.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContext.java new file mode 100644 index 00000000..7587c995 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContext.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.binding; + +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; + +@SuppressWarnings("rawtypes") +public interface EzyBindingContext { + + EzyMarshaller newMarshaller(); + + EzyUnmarshaller newUnmarshaller(); + + void addReader(EzyReader reader); + + void addWriter(EzyWriter writer); + + void addTemplate(Object template); + + void bindReader(Class clazz, EzyReader reader); + + void bindWriter(Class clazz, EzyWriter writer); + + void bindTemplate(Class clazz, Object template); + + static EzyBindingContextBuilder builder() { + return EzySimpleBindingContext.builder(); + } +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextAware.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextAware.java new file mode 100644 index 00000000..a82a6b73 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyBindingContextAware { + + void setContext(EzyBindingContext context); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextBuilder.java new file mode 100644 index 00000000..8f87cd3e --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyBindingContextBuilder.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.binding; + +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; + +@SuppressWarnings("rawtypes") +public interface EzyBindingContextBuilder { + + EzyBindingContextBuilder scan(String packageName); + + EzyBindingContextBuilder scan(String... packageNames); + + EzyBindingContextBuilder scan(Iterable packageNames); + + EzyBindingContextBuilder addClass(Class clazz); + + EzyBindingContextBuilder addObjectBindingClass(Class clazz); + + EzyBindingContextBuilder addArrayBindingClass(Class clazz); + + EzyBindingContextBuilder addClasses(Class... classes); + + EzyBindingContextBuilder addClasses(Iterable classes); + + EzyBindingContextBuilder addTemplate(Object template); + + EzyBindingContextBuilder addTemplateClass(Class clazz); + + EzyBindingContextBuilder addTemplateClasses(Iterable> classes); + + EzyBindingContextBuilder addTemplate(Class type, Object template); + + EzySimpleBindingContext build(); + +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyDataBinding.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyDataBinding.java new file mode 100644 index 00000000..37e68c9e --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyDataBinding.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyDataBinding { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyMarshaller.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyMarshaller.java new file mode 100644 index 00000000..78a907c8 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyMarshaller.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyMarshaller { + + T marshal(Object object); + + @SuppressWarnings("rawtypes") + T marshal(Class writerClass, Object object); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyReader.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyReader.java new file mode 100644 index 00000000..0f9a6ba5 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyReader.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyReader { + + R read(EzyUnmarshaller unmarshaller, T value); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyTemplate.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyTemplate.java new file mode 100644 index 00000000..d8e32994 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyTemplate.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyTemplate extends EzyReader, EzyWriter { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnmarshaller.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnmarshaller.java new file mode 100644 index 00000000..f6734f78 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnmarshaller.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.binding; + +import java.util.Collection; +import java.util.Map; + +public interface EzyUnmarshaller { + + /** + * unwrap a value to pojo + * + * @param value the value + * @param output the output type + * @return a pojo + */ + void unwrap(Object value, Object output); + + /** + * unmarshal a value to pojo + * + * @param value the value + * @param outType the pojo type + * @return a pojo + */ + T unmarshal(Object value, Class outType); + + /** + * unmarshal a value to collection + * + * @param value the value + * @param collectionType the collection type + * @param itemType the item type + * @return a collection + */ + @SuppressWarnings("rawtypes") + Collection unmarshalCollection( + Object value, Class collectionType, Class itemType); + + /** + * unmarshal value to map + * + * @param value the value + * @param mapType the map type + * @param keyType the key type + * @param valueType the value type + * @return the map + */ + @SuppressWarnings("rawtypes") + Map unmarshalMap( + Object value, Class mapType, Class keyType, Class valueType); + + /** + * unmarshal value to object + * + * @param readerClass the reader class + * @param value the value + * @return a object + */ + @SuppressWarnings("rawtypes") + T unmarshal(Class readerClass, Object value); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnwrapper.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnwrapper.java new file mode 100644 index 00000000..15201f7a --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyUnwrapper.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyUnwrapper { + + void unwrap(EzyUnmarshaller unmarshaller, I input, O output); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyWriter.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyWriter.java new file mode 100644 index 00000000..ac6823df --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/EzyWriter.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding; + +public interface EzyWriter { + + R write(EzyMarshaller marshaller, T object); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyArrayBinding.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyArrayBinding.java new file mode 100644 index 00000000..6a573833 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyArrayBinding.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyArrayBinding { + + /** + * @return make reader implementation nor not + */ + boolean read() default true; + + /** + * @return make writer implementation nor not + */ + boolean write() default true; + + /** + * @return binding all sub types + */ + boolean subTypes() default false; + + /** + * @return array of properties names + */ + String[] indexes() default {}; + + /** + * @return the access type + */ + int accessType() default EzyAccessType.ALL; + + /** + * @return sub type classes to include + */ + Class[] subTypeClasses() default {}; + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyConfiguration.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyConfiguration.java new file mode 100644 index 00000000..a6ae154c --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyConfiguration.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * @author tavandung12 + * + */ +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyConfiguration { + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIgnore.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIgnore.java new file mode 100644 index 00000000..bd8efd72 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIgnore.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.METHOD }) +public @interface EzyIgnore { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIndex.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIndex.java new file mode 100644 index 00000000..c9f6f733 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyIndex.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.METHOD }) +public @interface EzyIndex { + + /** + * the key mapped to value + * + * @return the key mapped to value + */ + public int value(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyObjectBinding.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyObjectBinding.java new file mode 100644 index 00000000..ac378dd3 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyObjectBinding.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyObjectBinding { + + /** + * @return make reader implementation nor not + */ + boolean read() default true; + + /** + * @return make writer implementation nor not + */ + boolean write() default true; + + /** + * @return binding all sub types + */ + boolean subTypes() default false; + + /** + * @return the access type + */ + int accessType() default EzyAccessType.ALL; + + /** + * @return sub type classes to include + */ + Class[] subTypeClasses() default {}; + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyPackagesScan.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyPackagesScan.java new file mode 100644 index 00000000..b423ea24 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyPackagesScan.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates that a class configure which packages bean context need to load + * + * @author tavandung12 + * + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyPackagesScan { + + /** + * packages to load + * + * @return array of package names + */ + public String[] value(); +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReader.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReader.java new file mode 100644 index 00000000..d1d95442 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReader.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.METHOD }) +public @interface EzyReader { + + /** + * the key mapped to value + * + * @return the key mapped to value + */ + @SuppressWarnings("rawtypes") + public Class value(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReaderImpl.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReaderImpl.java new file mode 100644 index 00000000..19287c49 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyReaderImpl.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyReaderImpl { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyTemplateImpl.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyTemplateImpl.java new file mode 100644 index 00000000..3f43461b --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyTemplateImpl.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyTemplateImpl { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyValue.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyValue.java new file mode 100644 index 00000000..e8965ca7 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyValue.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.METHOD }) +public @interface EzyValue { + + /** + * the key mapped to value + * + * @return the key mapped to value + */ + public String value() default ""; + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriter.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriter.java new file mode 100644 index 00000000..5f5eb0d7 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriter.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.FIELD, ElementType.METHOD }) +public @interface EzyWriter { + + /** + * the key mapped to value + * + * @return the key mapped to value + */ + @SuppressWarnings("rawtypes") + public Class value(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriterImpl.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriterImpl.java new file mode 100644 index 00000000..1bfa2788 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/annotation/EzyWriterImpl.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author tavandung12 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyWriterImpl { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractBuilder.java new file mode 100644 index 00000000..3101bb5c --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractBuilder.java @@ -0,0 +1,82 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.lang.reflect.Type; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; +import com.tvd12.ezyfoxserver.reflect.EzyAnnotatedElement; +import com.tvd12.ezyfoxserver.reflect.EzyByFieldMethod; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGenericElement; +import com.tvd12.ezyfoxserver.reflect.EzyKnownTypeElement; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzyAbstractBuilder extends EzyLoggable { + + protected final EzyClass clazz; + protected final EzyElementsFetcher elementsFetcher; + protected final int accessType; + + public EzyAbstractBuilder(EzyClass clazz) { + this.clazz = clazz; + this.elementsFetcher = newElementsFetcher(); + this.accessType = getAccessType(clazz); + } + + protected abstract int getAccessType(EzyClass clazz); + protected abstract EzyElementsFetcher newElementsFetcher(); + + protected List getElements() { + return elementsFetcher.getElements(clazz, accessType); + } + + protected String getFieldName(EzyReflectElement element) { + if(element instanceof EzyField) + return ((EzyField)element).getName(); + return ((EzyByFieldMethod)element).getFieldName(); + } + + protected String getFieldKey(EzyField field) { + if(field.isAnnotated(EzyValue.class)) + return getAnnotatedElementKey(field, field.getName()); + return field.getName(); + } + + protected String getMethodKey(M method) { + if(method.isAnnotated(EzyValue.class)) + return getAnnotatedElementKey(method, getFieldName(method)); + String fieldName = getFieldName(method); + EzyField field = clazz.getField(fieldName); + return field != null ? getFieldKey(field) : fieldName; + } + + @SuppressWarnings("unchecked") + protected String getKey(EzyReflectElement element) { + if(element instanceof EzyField) + return getFieldKey((EzyField) element); + return getMethodKey((M) element); + } + + protected String getAnnotatedElementKey( + EzyAnnotatedElement element, String elementName) { + EzyValue kv = element.getAnnotation(EzyValue.class); + return StringUtils.isEmpty(kv.value()) ? elementName : kv.value(); + } + + @SuppressWarnings("rawtypes") + protected Class getElementType(Object element) { + if(element == null) + return Object.class; + return ((EzyKnownTypeElement)element).getType(); + } + + protected Type getElementGenericType(Object element) { + return ((EzyGenericElement)element).getGenericType(); + } + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractElementsFetcher.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractElementsFetcher.java new file mode 100644 index 00000000..efe96b8a --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractElementsFetcher.java @@ -0,0 +1,79 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.DECLARED_FIELDS; +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.DECLARED_METHODS; +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.FIELDS; +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.METHODS; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyIgnore; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyByFieldMethod; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +/** + * + * @author tavandung12 + * + */ + +public abstract class EzyAbstractElementsFetcher + extends EzyLoggable + implements EzyElementsFetcher { + + protected final List getFields(EzyClass clazz, int accessType) { + List fields = new ArrayList<>(); + if((accessType & FIELDS) > 0) { + fields.addAll(clazz.getFields()); + } + else if((accessType & DECLARED_FIELDS) > 0) { + fields.addAll(clazz.getDeclaredFields()); + } + return EzyLists.filter(fields, f -> !f.isAnnotated(EzyIgnore.class)); + } + + protected final List getMethods(EzyClass clazz, int accessType) { + List methods = new ArrayList<>(); + if((accessType & METHODS) > 0) { + methods.addAll(getMethods(clazz)); + } + else if((accessType & DECLARED_METHODS) > 0) { + methods.addAll(getDeclaredMethods(clazz)); + } + return EzyLists.filter(methods, m -> !isIgnoredMethod(m, clazz)); + } + + protected boolean isValidGenericField(EzyField field) { + return true; + } + protected boolean isValidGenericMethod(EzyMethod method) { + return true; + } + + protected abstract List getMethods(EzyClass clazz); + protected abstract List getDeclaredMethods(EzyClass clazz); + + protected final Map getMethodsByFieldName(EzyClass clazz) { + return mapMethodsByFieldName(getMethods(clazz)); + } + + private final Map + mapMethodsByFieldName(List methods) { + return EzyMaps.newHashMap(methods, m -> ((EzyByFieldMethod)m).getFieldName()); + } + + private boolean isIgnoredMethod(EzyMethod method, EzyClass clazz) { + boolean ignored = method.isAnnotated(EzyIgnore.class); + if(ignored) return true; + String fieldName = ((EzyByFieldMethod)method).getFieldName(); + EzyField field = clazz.getField(fieldName); + return field == null ? false : field.isAnnotated(EzyIgnore.class); + } +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReader.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReader.java new file mode 100644 index 00000000..bd87803d --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReader.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +public abstract class EzyAbstractReader + extends EzyEntityBuilders + implements EzyReader { + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReaderBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReaderBuilder.java new file mode 100644 index 00000000..ac18fb60 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractReaderBuilder.java @@ -0,0 +1,164 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; +import com.tvd12.ezyfoxserver.reflect.EzyTypes; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtNewMethod; + +@SuppressWarnings("rawtypes") +public abstract class EzyAbstractReaderBuilder + extends EzyAbstractBuilder { + + public EzyAbstractReaderBuilder(EzyClass clazz) { + super(clazz); + } + + @SuppressWarnings("unchecked") + public T build() { + try { + return (T)make(); + } + catch(Exception e) { + throw new IllegalStateException(e); + } + } + + protected Object make() throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyMethod readMethod = getReadMethod(); + readMethod.setDisplayName(getReadMethodName() + "$impl"); + String implMethodContent = makeImplMethodContent(readMethod); + readMethod.setDisplayName(getReadMethodName()); + String methodContent = makeMethodContent(readMethod); + printMethodContent(methodContent); + printMethodContent(implMethodContent); + implClass.setInterfaces(new CtClass[] { pool.makeClass(getReaderInterface().getName()) }); + implClass.addMethod(CtNewMethod.make(implMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(methodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + getLogger().debug("class {} has generated", implClassName); + return answerClass.newInstance(); + } + + protected String getReadMethodName() { + return "read"; + } + protected Class getReaderInterface() { + return EzyReader.class; + } + + protected String makeMethodContent(EzyMethod readMethod) { + String[] paramNames = new String[readMethod.getParameterCount()]; + for(int i = 0 ; i < paramNames.length ; i++) + paramNames[i] = "arg" + i; + String paramNamesChain = StringUtils.join(paramNames, ", "); + return new EzyFunction(readMethod) + .body() + .append(new EzyInstruction("\t", "\n", false) + .append("try {")) + .append(new EzyInstruction("\t\t", "\n") + .append("return this." + getReadMethodName() + "$impl( " + paramNamesChain + ")")) + .append(new EzyInstruction("\t", "\n", false) + .append("} catch(") + .clazz(Exception.class) + .append(" e) {")) + .append(new EzyInstruction("\t\t", "\n\t}\n") + .append("throw new ") + .clazz(IllegalStateException.class) + .bracketopen() + .string("can't read value ") + .append("+ arg1, e") + .bracketclose()) + .function() + .toString(); + } + + protected EzyInstruction newOutputObjectInstruction() { + return new EzyInstruction("", "", false) + .append("new ") + .constructor(clazz.getClazz()); + } + + protected abstract String getImplClassName(); + protected abstract String makeImplMethodContent(EzyMethod readMethod); + + protected EzyMethod getReadMethod() { + return EzyMethod.builder() + .clazz(getReaderInterface()) + .methodName(getReadMethodName()) + .parameterTypes(getReaderMethodParameterTypes()) + .build(); + } + + protected Class[] getReaderMethodParameterTypes() { + return new Class[] {EzyUnmarshaller.class, Object.class}; + } + + protected Class getReaderImplClass(EzyReflectElement element) { + com.tvd12.ezyfoxserver.binding.annotation.EzyReader rd = + getReaderAnnotation(element); + if(rd != null) return rd.value(); + if(element instanceof EzyField) return null; + EzyField field = clazz.getField(getFieldName(element)); + return field == null ? null : getReaderImplClass(field); + } + + protected com.tvd12.ezyfoxserver.binding.annotation.EzyReader + getReaderAnnotation(EzyReflectElement element) { + return element.getAnnotation( + com.tvd12.ezyfoxserver.binding.annotation.EzyReader.class); + } + + protected EzyInstruction wrapUnmarshalInstruction( + EzyInstruction instruction, Class outType) { + String value = instruction.toString(); + EzyInstruction answer = new EzyInstruction("", "", false); + if(outType == boolean.class) + answer.cast(Boolean.class, value).append(".booleanValue()"); + else if(outType == byte.class) + answer.cast(Byte.class, value).append(".byteValue()"); + else if(outType == char.class) + answer.cast(Character.class, value).append(".charValue()"); + else if(outType == double.class) + answer.cast(Double.class, value).append(".doubleValue()"); + else if(outType == float.class) + answer.cast(Float.class, value).append(".floatValue()"); + else if(outType == int.class) + answer.cast(Integer.class, value).append(".intValue()"); + else if(outType == long.class) + answer.cast(Long.class, value).append(".longValue()"); + else if(outType == short.class) + answer.cast(Short.class, value).append(".shortValue()"); + else + answer.cast(outType, value); + return answer; + } + + protected Set getCommonGenericTypes() { + return EzyTypes.COMMON_GENERIC_TYPES; + } + + protected void printMethodContent(String methodContent) { + if(isDebug()) getLogger().debug("reader: method content \n{}", methodContent); + } + + protected abstract boolean isDebug(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractTemplate.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractTemplate.java new file mode 100644 index 00000000..09f3048d --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractTemplate.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.binding.EzyTemplate; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +public abstract class EzyAbstractTemplate + extends EzyEntityBuilders + implements EzyTemplate { + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriter.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriter.java new file mode 100644 index 00000000..29d75b48 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriter.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +public abstract class EzyAbstractWriter + extends EzyEntityBuilders + implements EzyWriter { +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriterBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriterBuilder.java new file mode 100644 index 00000000..ea4a19ee --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyAbstractWriterBuilder.java @@ -0,0 +1,113 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGetterMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtNewMethod; + +@SuppressWarnings("rawtypes") +public abstract class EzyAbstractWriterBuilder + extends EzyAbstractBuilder + implements EzyBuilder { + + public EzyAbstractWriterBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + public EzyWriter build() { + try { + return make(); + } + catch(Exception e) { + throw new IllegalStateException("can not build writer for class " + clazz, e); + } + } + + protected EzyWriter make() throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyMethod writeMethod = getWriteMethod(); + writeMethod.setDisplayName("write$impl"); + String implMethodContent = makeImplMethodContent(writeMethod); + writeMethod.setDisplayName("write"); + String methodContent = makeMethodContent(writeMethod); + printMethodContent(methodContent); + printMethodContent(implMethodContent); + implClass.setInterfaces(new CtClass[] { pool.makeClass(EzyWriter.class.getName()) }); + implClass.addMethod(CtNewMethod.make(implMethodContent, implClass)); + implClass.addMethod(CtNewMethod.make(methodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + getLogger().debug("class {} has generated", implClassName); + return (EzyWriter) answerClass.newInstance(); + } + + protected String makeMethodContent(EzyMethod writeMethod) { + return new EzyFunction(writeMethod) + .body() + .append(new EzyInstruction("\t", "\n", false) + .append("try {")) + .append(new EzyInstruction("\t\t", "\n") + .append("return this.write$impl(arg0, arg1)")) + .append(new EzyInstruction("\t", "\n", false) + .append("} catch(") + .clazz(Exception.class) + .append(" e) {")) + .append(new EzyInstruction("\t\t", "\n\t}\n") + .append("throw new ") + .clazz(IllegalStateException.class) + .bracketopen() + .string("can't write object ") + .append("+ arg1, e") + .bracketclose()) + .function() + .toString(); + } + + protected abstract String getImplClassName(); + protected abstract String makeImplMethodContent(EzyMethod writeMethod); + + protected com.tvd12.ezyfoxserver.binding.annotation.EzyWriter + getWriterClass(EzyReflectElement element) { + com.tvd12.ezyfoxserver.binding.annotation.EzyWriter wrt = + getWriterAnnotation(element); + if(wrt != null) return wrt; + if(element instanceof EzyField) return wrt; + EzyField field = clazz.getField(getFieldName(element)); + return field == null ? wrt : getWriterAnnotation(field); + } + + protected com.tvd12.ezyfoxserver.binding.annotation.EzyWriter + getWriterAnnotation(EzyReflectElement element) { + return element.getAnnotation( + com.tvd12.ezyfoxserver.binding.annotation.EzyWriter.class); + } + + protected EzyMethod getWriteMethod() { + return EzyMethod.builder() + .clazz(EzyWriter.class) + .methodName("write") + .parameterTypes(EzyMarshaller.class) + .parameterTypes(Object.class) + .build(); + } + + protected void printMethodContent(String methodContent) { + if(isDebug()) getLogger().debug("writer: method content \n{}", methodContent); + } + + protected abstract boolean isDebug(); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayElementsFetcher.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayElementsFetcher.java new file mode 100644 index 00000000..1cba5738 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayElementsFetcher.java @@ -0,0 +1,260 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.NONE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIndex; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyAnnotatedElement; +import com.tvd12.ezyfoxserver.reflect.EzyByFieldMethod; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +//================== fetcher by array ================ +public abstract class EzyArrayElementsFetcher extends EzyAbstractElementsFetcher { + + private Map methodsByFieldName; + + @Override + public final List getElements(EzyClass clazz, int accessType) { + getLogger().debug("start scan {}", clazz); + + initialize(clazz, accessType); + + List elements = doGetElements(clazz, accessType); + + getLogger().debug("finish scan {}", clazz); + + return elements; + } + + private void initialize(EzyClass clazz, int accessType) { + this.methodsByFieldName = getMethodsByFieldName(clazz); + } + + private List doGetElements(EzyClass clazz, int accessType) { + String[] indexes = getIndexes(clazz); + if(indexes.length > 0) { + return getElementsByCustomIndexes(clazz, indexes); + } + else if(accessType == NONE) { + return getAnnotatedElements(clazz); + } + else { + return getElementsByNativeIndexes(clazz, accessType); + } + } + + private List getElementsByNativeIndexes(EzyClass clazz, int accessType) { + return getElementsByNativeIndexes( + getFields(clazz, accessType), + getMethods(clazz, accessType)); + } + + private List getElementsByCustomIndexes(EzyClass clazz, String[] indexes) { + return getElementsByCustomIndexes( + getFieldsByName(clazz), + indexes); + } + + private List getAnnotatedElements(EzyClass clazz) { + return getAnnotatedElements( + clazz, + getAnnotedFields(clazz), + getAnnotedMethods(clazz)); + } + + private List getElementsByNativeIndexes( + List fields, List methods) { + + List elements = new ArrayList<>(); + Set remainMethods = new HashSet<>(methods); + + for(EzyField field : fields) { + getLogger().debug("scan field {}", field.getName()); + + EzyMethod method = methodsByFieldName.get(field.getName()); + + if(method != null) { + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + elements.add(null); + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + remainMethods.remove(method); + } + else if(field.isPublic()) { + if(isValidGenericField(field)) { + elements.add(field); + } + else { + getLogger().debug("unknown generic type of field {}, ignore it", field.getName()); + elements.add(null); + } + } + else { + getLogger().debug("field {} has not getter/setter, ignore it", field.getName()); + } + } + for(EzyMethod method : remainMethods) { + getLogger().debug("scan method {}", method.getName()); + + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + } + return elements; + } + + private List getElementsByCustomIndexes(Map fieldsByName, String[] indexes) { + List elements = new ArrayList<>(); + + for(String property : indexes) { + getLogger().debug("scan property {}", property); + + EzyMethod method = methodsByFieldName.get(property); + + if(method != null) { + if(!isValidGenericMethod(method)) { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + else { + elements.add(method); continue; + } + } + else { + getLogger().debug("has no getter/setter method map to property {}", property); + } + + EzyField field = fieldsByName.get(property); + + if(field != null) { + if(!field.isPublic()) { + getLogger().debug("has no public field map to property {}", property); + } + else if(isValidGenericField(field)) { + elements.add(field); + } + else { + getLogger().debug("unknown generic type of field {}, ignore it", field.getName()); + } + } + else { + elements.add(null); + getLogger().debug("nothing map to property {}, ignore it value to its", property); + } + + } + return elements; + } + + private List getAnnotatedElements( + EzyClass clazz, List fields, List methods) { + + List elements = new ArrayList<>(); + + for(EzyField field : fields) { + getLogger().debug("scan field {}", field.getName()); + + EzyMethod method = methodsByFieldName.get(field.getName()); + + if(method != null) { + if(!isValidGenericMethod(method)) { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + else { + elements.add(method); + methods.remove(method); + } + } + else if(field.isPublic()) { + if(!isValidGenericField(field)) { + getLogger().debug("unknown generic type of field {}, ignore it", field.getName()); + } + else { + elements.add(field); + } + } + else { + getLogger().debug("field {} has not getter/setter, ignore it", field.getName()); + } + } + for(EzyMethod method : methods) { + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + } + + Object max = Collections.max(elements, (e1, e2) -> + getIndex(clazz, e1) - getIndex(clazz, e2) + ); + + int maxIndex = getIndex(clazz, max); + + Map elementsByIndex = EzyMaps.newHashMap(elements, e -> getIndex(clazz, e)); + List answer = new ArrayList<>(); + + for(int index = 0 ; index <= maxIndex ; index ++) { + if(elementsByIndex.containsKey(index)) { + answer.add(elementsByIndex.get(index)); + } + else { + answer.add(null); + getLogger().debug("has not property at index {}, so at this index value is null", index); + } + } + return answer; + } + + private Map getFieldsByName(EzyClass clazz) { + return EzyMaps.newHashMap(clazz.getFields(), f -> f.getName()); + } + + private List getAnnotedFields(EzyClass clazz) { + return clazz.getFields(f -> f.isAnnotated(EzyIndex.class)); + } + + private List getAnnotedMethods(EzyClass clazz) { + List methods = EzyLists.filter(clazz.getMethods(), this::shouldAddAnnotatedMethod); + return EzyLists.newArrayList(methods, this::newByFieldMethod); + } + + private boolean shouldAddAnnotatedMethod(EzyMethod method) { + return method.isPublic() && + method.isAnnotated(EzyIndex.class) && + isValidAnnotatedMethod(method); + } + + protected abstract EzyMethod newByFieldMethod(EzyMethod method); + protected abstract boolean isValidAnnotatedMethod(EzyMethod method); + + private String[] getIndexes(EzyClass clazz) { + EzyArrayBinding ann = clazz.getAnnotation(EzyArrayBinding.class); + return ann != null ? ann.indexes() : new String[0]; + } + + private int getIndex(EzyClass clazz, Object element) { + EzyIndex index = ((EzyAnnotatedElement)element).getAnnotation(EzyIndex.class); + if(index != null) return index.value(); + EzyByFieldMethod method = (EzyByFieldMethod)element; + return getIndex(clazz, clazz.getField(method.getFieldName())); + } + +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayReaderBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayReaderBuilder.java new file mode 100644 index 00000000..18d0ef0c --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayReaderBuilder.java @@ -0,0 +1,262 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGenericSetterValidator; +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; + +import lombok.Setter; + +@SuppressWarnings("rawtypes") +public class EzyArrayReaderBuilder extends EzyAbstractReaderBuilder { + + @Setter + protected static boolean debug; + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzyArrayReaderBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + EzyArrayBinding ann = clazz.getAnnotation(EzyArrayBinding.class); + return ann == null ? EzyAccessType.ALL : ann.accessType(); + } + + protected EzyElementsFetcher newElementsFetcher() { + return new EzyArrayReaderElementsFetcher(); + } + + @Override + protected String makeImplMethodContent(EzyMethod readMethod) { + EzyFunction.EzyBody methodBody = new EzyFunction(readMethod) + .modifier("protected") + .body() + .append(new EzyInstruction("\t", "\n") + .variable(EzyArray.class, "value") + .equal() + .cast(EzyArray.class, "arg1") + ) + .append(new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .append(newOutputObjectInstruction().toString(false)) + ); + List elements = getElements(); + for(int index = 0 ; index < elements.size() ; index ++) { + Object element = elements.get(index); + EzyInstruction instruction = null; + if(element == null) { + continue; + } + methodBody.append(checkNotNullInstruction((EzyReflectElement)element, index)); + if(element instanceof EzyField) { + EzyField field = (EzyField)element; + + instruction = new EzyInstruction("\t\t", "\n") + .append("object") + .dot() + .append(field.getName()) + .equal(); + EzyInstruction unmarshalInstruction = newUnmarshalInstruction( + field, index, ""); + instruction.append(unmarshalInstruction.toString()); + } + else { + EzySetterMethod method = (EzySetterMethod)element; + instruction = new EzyInstruction("\t\t", "\n") + .append("object") + .dot() + .append(method.getName()) + .bracketopen(); + EzyInstruction unmarshalInstruction = newUnmarshalInstruction( + method, index, "()"); + instruction + .append(unmarshalInstruction.toString()) + .bracketclose(); + } + methodBody.append(instruction); + } + + methodBody.append(new EzyInstruction("\t", "\n") + .answer() + .append("object")); + + EzyFunction method = methodBody.function(); + + return method.toString(); + } + + protected EzyInstruction checkNotNullInstruction(EzyReflectElement element, int index) { + return new EzyInstruction("\t", "\n", false) + .append("if") + .bracketopen() + .append("value") + .dot() + .append("isNotNullValue") + .bracketopen() + .append(index) + .bracketclose() + .bracketclose(); + } + + protected EzyInstruction newUnmarshalInstruction( + EzyReflectElement element, int index, String valueExpSuffix) { + Set commonGenericTypes = getCommonGenericTypes(); + Class type = getElementType(element); + Class readerImpl = getReaderImplClass(element); + EzyInstruction instruction = null; + if(readerImpl != null || !commonGenericTypes.contains(type)) + instruction = newUnmarshalNormalInstruction(element, readerImpl, index); + else + instruction = newUnmarshalGenericInstruction(element, index); + return wrapUnmarshalInstruction(instruction, type); + } + + protected EzyInstruction newUnmarshalGenericInstruction( + EzyReflectElement element, int index) { + Class genericType = getElementType(element); + if(Map.class.isAssignableFrom(genericType)) + return newUnmarshalMapInstruction(element, index); + return newUnmarshalCollectionInstruction(element, index); + } + + protected EzyInstruction newUnmarshalMapInstruction( + EzyReflectElement element, int index) { + Class mapType = getElementType(element); + Type genericType = getElementGenericType(element); + Class[] keyValueTypes = EzyGenerics.getTwoGenericClassArguments(genericType); + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshalMap") + .bracketopen() + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .append(index) + .comma() + .clazz(mapType, true) + .bracketclose() + .comma() + .clazz(mapType, true) + .comma() + .clazz(keyValueTypes[0], true) + .comma() + .clazz(keyValueTypes[1], true) + .bracketclose(); + return instruction; + } + + protected EzyInstruction newUnmarshalCollectionInstruction( + EzyReflectElement element, int index) { + Class collectionType = getElementType(element); + Type genericType = getElementGenericType(element); + Class itemType = EzyGenerics.getOneGenericClassArgument(genericType); + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshalCollection") + .bracketopen() + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .append(index) + .comma() + .clazz(collectionType, true) + .bracketclose() + .comma() + .clazz(collectionType, true) + .comma() + .clazz(itemType, true) + .bracketclose(); + return instruction; + } + + protected EzyInstruction newUnmarshalNormalInstruction( + EzyReflectElement element, Class readerImpl, int index) { + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshal") + .bracketopen(); + if(readerImpl != null) { + instruction + .clazz(readerImpl, true) + .comma(); + } + Class type = getElementType(element); + instruction + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .append(index) + .comma() + .clazz(type, true) + .bracketclose(); + if(readerImpl == null) { + instruction + .comma() + .clazz(type, true); + } + instruction.bracketclose(); + return instruction; + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyArrayReader$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + @Override + protected boolean isDebug() { + return debug; + } +} + +class EzyArrayReaderElementsFetcher extends EzyArrayElementsFetcher { + + private final EzyGenericSetterValidator setterValidator = new EzyGenericSetterValidator(); + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getSetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredSetterMethods(); + } + + @Override + protected boolean isValidGenericField(EzyField field) { + return setterValidator.validate(field.getGenericType()); + } + + @Override + protected boolean isValidGenericMethod(EzyMethod method) { + return setterValidator.validate(((EzySetterMethod)method).getGenericType()); + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzySetterMethod(method); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getParameterCount() == 1; + } +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayUnwrapperBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayUnwrapperBuilder.java new file mode 100644 index 00000000..a5c1967c --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayUnwrapperBuilder.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +@SuppressWarnings("rawtypes") +public class EzyArrayUnwrapperBuilder extends EzyArrayReaderBuilder { + + protected static AtomicInteger COUNT = new AtomicInteger(0); + + public EzyArrayUnwrapperBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected String getReadMethodName() { + return "unwrap"; + } + + @Override + protected Class getReaderInterface() { + return EzyUnwrapper.class; + } + + @Override + protected Class[] getReaderMethodParameterTypes() { + return new Class[] {EzyUnmarshaller.class, Object.class, Object.class}; + } + + @Override + protected EzyInstruction newOutputObjectInstruction() { + return new EzyInstruction("", "", false) + .cast(clazz.getClazz(), "arg2"); + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyArrayUnwrapper$EzyAutoImpl$" + COUNT.incrementAndGet(); + } +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayWriterBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayWriterBuilder.java new file mode 100644 index 00000000..0fe63709 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyArrayWriterBuilder.java @@ -0,0 +1,151 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGetterMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; + +import lombok.Setter; + +@SuppressWarnings("rawtypes") +public class EzyArrayWriterBuilder + extends EzyAbstractWriterBuilder { + + @Setter + protected static boolean debug; + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzyArrayWriterBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + EzyArrayBinding ann = clazz.getAnnotation(EzyArrayBinding.class); + return ann == null ? EzyAccessType.ALL : ann.accessType(); + } + + @Override + protected EzyElementsFetcher newElementsFetcher() { + return new EzyArrayWriterElementsFetcher(); + } + + @Override + protected String makeImplMethodContent(EzyMethod writeMethod) { + EzyFunction.EzyBody methodBody = new EzyFunction(writeMethod) + .modifier("protected") + .body() + .append(new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .cast(clazz.getClazz(), "arg1") + ) + .append(new EzyInstruction("\t", "\n") + .variable(EzyArrayBuilder.class, "builder") + .equal() + .clazz(EzyEntityFactory.class) + .dot() + .append("create") + .bracketopen() + .clazz(EzyArrayBuilder.class) + .append(".class") + .bracketclose() + ); + for(Object element : getElements()) { + EzyInstruction instruction = null; + if(element == null) { + instruction = newInstructionByNull(); + } + else if(element instanceof EzyField) { + EzyField field = (EzyField)element; + instruction = newInstruction(field, ""); + } + else { + EzyGetterMethod method = (EzyGetterMethod)element; + instruction = newInstruction(method, "()"); + } + methodBody.append(instruction); + } + methodBody.append(new EzyInstruction("\t", "\n") + .answer() + .append("builder.build()")); + + EzyFunction method = methodBody.function(); + + return method.toString(); + } + + protected EzyInstruction newInstructionByNull() { + return new EzyInstruction("\t", "\n") + .append("builder.append((java.lang.Object)null)"); + } + + protected EzyInstruction newInstruction( + EzyReflectElement element, String valueExpSuffix) { + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .append("builder") + .dot() + .append("append") + .bracketopen() + .brackets(Object.class) + .append("arg0.marshal("); + com.tvd12.ezyfoxserver.binding.annotation.EzyWriter wrt = + getWriterClass(element); + if(wrt != null) { + instruction + .clazz(wrt.value(), true) + .comma(); + } + Class type = getElementType(element); + String valueExpression = + "object." + element.getName() + valueExpSuffix; + instruction + .valueOf(type, valueExpression) + .append(")") + .bracketclose(); + return instruction; + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyArrayWriter$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + @Override + protected boolean isDebug() { + return debug; + } +} + +class EzyArrayWriterElementsFetcher extends EzyArrayElementsFetcher { + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getGetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredGetterMethods(); + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzyGetterMethod(method); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getReturnType() != void.class; + } +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyConfigurationLoader.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyConfigurationLoader.java new file mode 100644 index 00000000..7200e71e --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyConfigurationLoader.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; + +public interface EzyConfigurationLoader { + + void load(EzyBindingContext context); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyElementsFetcher.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyElementsFetcher.java new file mode 100644 index 00000000..8a0d2bc6 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyElementsFetcher.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.List; + +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public interface EzyElementsFetcher { + + List getElements(EzyClass clazz, int accessType); + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectElementsFetcher.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectElementsFetcher.java new file mode 100644 index 00000000..47fd3547 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectElementsFetcher.java @@ -0,0 +1,164 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import static com.tvd12.ezyfoxserver.binding.EzyAccessType.NONE; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +//=========================== fetcher by object ===================== +public abstract class EzyObjectElementsFetcher extends EzyAbstractElementsFetcher { + + private Map methodsByFieldName; + + @Override + public final List getElements(EzyClass clazz, int accessType) { + getLogger().debug("start scan {}", clazz); + + initialize(clazz, accessType); + + List elements = doGetElements(clazz, accessType); + + getLogger().debug("finish scan {}", clazz); + + return elements; + } + + private void initialize(EzyClass clazz, int accessType) { + this.methodsByFieldName = getMethodsByFieldName(clazz); + } + + private List doGetElements(EzyClass clazz, int accessType) { + return accessType == NONE + ? getAnnotatedElements(clazz) + : getNativeElements(clazz, accessType); + } + + private List getAnnotatedElements(EzyClass clazz) { + return getAnnotatedElements( + getAnnotatedFields(clazz), + getAnnotatedMethods(clazz)); + } + + private List getNativeElements(EzyClass clazz, int accessType) { + return getNativeElements( + getFields(clazz, accessType), + getMethods(clazz, accessType)); + } + + private List getNativeElements( + List fields, List methods) { + + List elements = new ArrayList<>(); + Set remainMethods = new HashSet<>(methods); + + for(EzyField field : fields) { + getLogger().debug("scan field {}", field.getName()); + + EzyMethod method = methodsByFieldName.get(field.getName()); + + if(method != null) { + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + remainMethods.remove(method); + } + else if(field.isPublic()) { + if(isValidGenericField(field)) { + elements.add(field); + } + else { + getLogger().debug("unknown generic type of field {}, ignore it", field.getName()); + } + } + else { + getLogger().debug("field {} has not getter/setter, ignore it", field.getName()); + } + } + for(EzyMethod method : remainMethods) { + getLogger().debug("scan method {}", method.getName()); + + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + } + return elements; + } + + private List getAnnotatedElements( + List fields, List methods) { + + List elements = new ArrayList<>(); + + for(EzyField field : fields) { + getLogger().debug("scan field {}", field.getName()); + + EzyMethod method = methodsByFieldName.get(field.getName()); + + if(method != null) { + if(!isValidGenericMethod(method)) { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + else { + elements.add(method); + methods.remove(method); + } + } + else if(field.isPublic()) { + if(!isValidGenericField(field)) { + getLogger().debug("unknown generic type of field {}, ignore it", field.getName()); + } + else { + elements.add(field); + } + } + else { + getLogger().debug("field {} has not getter/setter, ignore it", field.getName()); + } + } + + for(EzyMethod method : methods) { + getLogger().debug("scan method {}", method.getName()); + + if(isValidGenericMethod(method)) { + elements.add(method); + } + else { + getLogger().debug("unknown generic type of method {}, ignore it", method.getName()); + } + } + return elements; + } + + private List getAnnotatedFields(EzyClass clazz) { + return clazz.getFields(f -> f.isAnnotated(EzyValue.class)); + } + + private List getAnnotatedMethods(EzyClass clazz) { + List methods = EzyLists.filter(clazz.getMethods(), this::shouldAddAnnotatedMethod); + return EzyLists.newArrayList(methods, this::newByFieldMethod); + } + + private boolean shouldAddAnnotatedMethod(EzyMethod method) { + return method.isPublic() && + method.isAnnotated(EzyValue.class) && + isValidAnnotatedMethod(method); + } + + protected abstract EzyMethod newByFieldMethod(EzyMethod method); + protected abstract boolean isValidAnnotatedMethod(EzyMethod method); +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectReaderBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectReaderBuilder.java new file mode 100644 index 00000000..1704594a --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectReaderBuilder.java @@ -0,0 +1,260 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyByFieldMethod; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGenericSetterValidator; +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; + +import lombok.Setter; + +@SuppressWarnings("rawtypes") +public class EzyObjectReaderBuilder extends EzyAbstractReaderBuilder { + + @Setter + protected static boolean debug; + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzyObjectReaderBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + EzyObjectBinding ann = clazz.getAnnotation(EzyObjectBinding.class); + return ann == null ? EzyAccessType.ALL : ann.accessType(); + } + + @Override + protected EzyElementsFetcher newElementsFetcher() { + return new EzyObjectReaderElementsFetcher(); + } + + @Override + protected String makeImplMethodContent(EzyMethod readMethod) { + EzyFunction.EzyBody methodBody = new EzyFunction(readMethod) + .modifier("protected") + .body() + .append(new EzyInstruction("\t", "\n") + .variable(EzyObject.class, "value") + .equal() + .cast(EzyObject.class, "arg1") + ) + .append(new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .append(newOutputObjectInstruction().toString(false)) + ); + + for(Object element : getElements()) { + methodBody.append(checkNotNullInstruction((EzyReflectElement) element)); + methodBody.append(newInstructionByElement(element)); + } + + methodBody.append(new EzyInstruction("\t", "\n") + .answer() + .append("object")); + + EzyFunction method = methodBody.function(); + + return method.toString(); + } + + protected EzyInstruction newInstructionByElement(Object element) { + if(element instanceof EzyField) + return newInstructionByField((EzyField)element); + return newInstructionByMethod((EzyMethod)element); + } + + protected EzyInstruction newInstructionByField(EzyField field) { + EzyInstruction instruction = new EzyInstruction("\t\t", "\n") + .append("object") + .dot() + .append(field.getName()) + .equal(); + EzyInstruction unmarshalInstruction = newUnmarshalInstruction(field); + instruction.append(unmarshalInstruction.toString()); + return instruction; + } + + protected EzyInstruction newInstructionByMethod(EzyMethod method) { + EzyInstruction instruction = new EzyInstruction("\t\t", "\n") + .append("object") + .dot() + .append(method.getName()) + .bracketopen(); + EzyInstruction unmarshalInstruction = newUnmarshalInstruction(method); + instruction + .append(unmarshalInstruction.toString()) + .bracketclose(); + return instruction; + } + + protected EzyInstruction checkNotNullInstruction(EzyReflectElement element) { + return new EzyInstruction("\t", "\n", false) + .append("if") + .bracketopen() + .append("value") + .dot() + .append("isNotNullValue") + .bracketopen() + .string(getKey(element)) + .bracketclose() + .bracketclose(); + } + + protected EzyInstruction newUnmarshalInstruction(EzyReflectElement element) { + Set commonGenericTypes = getCommonGenericTypes(); + Class type = getElementType(element); + Class readerImpl = getReaderImplClass(element); + EzyInstruction instruction = null; + if(readerImpl != null || !commonGenericTypes.contains(type)) + instruction = newUnmarshalNormalInstruction(element, readerImpl); + else + instruction = newUnmarshalGenericInstruction(element); + + return wrapUnmarshalInstruction(instruction, type); + } + + protected EzyInstruction newUnmarshalGenericInstruction(EzyReflectElement element) { + Class genericType = getElementType(element); + if(Map.class.isAssignableFrom(genericType)) + return newUnmarshalMapInstruction(element); + return newUnmarshalCollectionInstruction(element); + } + + protected EzyInstruction newUnmarshalMapInstruction(EzyReflectElement element) { + Class mapType = getElementType(element); + Type genericType = getElementGenericType(element); + Class[] keyValueTypes = EzyGenerics.getTwoGenericClassArguments(genericType); + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshalMap") + .bracketopen() + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .string(getKey(element)) + .comma() + .clazz(mapType, true) + .bracketclose() + .comma() + .clazz(mapType, true) + .comma() + .clazz(keyValueTypes[0], true) + .comma() + .clazz(keyValueTypes[1], true) + .bracketclose(); + return instruction; + } + + protected EzyInstruction newUnmarshalCollectionInstruction(EzyReflectElement element) { + Class collectionType = getElementType(element); + Type genericType = getElementGenericType(element); + Class itemType = EzyGenerics.getOneGenericClassArgument(genericType); + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshalCollection") + .bracketopen() + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .string(getKey(element)) + .comma() + .clazz(collectionType, true) + .bracketclose() + .comma() + .clazz(collectionType, true) + .comma() + .clazz(itemType, true) + .bracketclose(); + return instruction; + } + + protected EzyInstruction newUnmarshalNormalInstruction(EzyReflectElement element, Class readerImpl) { + EzyInstruction instruction = new EzyInstruction("", "", false) + .append("arg0.unmarshal") + .bracketopen(); + if(readerImpl != null) { + instruction + .clazz(readerImpl, true) + .comma(); + } + Class type = getElementType(element); + instruction + .bracketopen() + .clazz(Object.class) + .bracketclose() + .append("value.getValue(") + .string(getKey(element)) + .comma() + .clazz(type, true) + .bracketclose(); + if(readerImpl == null) { + instruction + .comma() + .clazz(type, true); + } + instruction.bracketclose(); + return instruction; + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyObjectReader$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + @Override + protected boolean isDebug() { + return debug; + } +} + +class EzyObjectReaderElementsFetcher extends EzyObjectElementsFetcher { + + private EzyGenericSetterValidator setterValidator = new EzyGenericSetterValidator(); + + @Override + protected boolean isValidGenericField(EzyField field) { + return setterValidator.validate(field.getGenericType()); + } + + @Override + protected boolean isValidGenericMethod(EzyMethod method) { + return setterValidator.validate(((EzyByFieldMethod)method).getGenericType()); + } + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getSetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredSetterMethods(); + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzySetterMethod(method); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getParameterCount() == 1; + } +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectUnwrapperBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectUnwrapperBuilder.java new file mode 100644 index 00000000..7768b3fc --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectUnwrapperBuilder.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +@SuppressWarnings("rawtypes") +public class EzyObjectUnwrapperBuilder extends EzyObjectReaderBuilder { + + protected static AtomicInteger COUNT = new AtomicInteger(0); + + public EzyObjectUnwrapperBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected String getReadMethodName() { + return "unwrap"; + } + + @Override + protected Class getReaderInterface() { + return EzyUnwrapper.class; + } + + @Override + protected Class[] getReaderMethodParameterTypes() { + return new Class[] {EzyUnmarshaller.class, Object.class, Object.class}; + } + + @Override + protected EzyInstruction newOutputObjectInstruction() { + return new EzyInstruction("", "", false) + .cast(clazz.getClazz(), "arg2"); + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyObjectUnwrapper$EzyAutoImpl$" + COUNT.incrementAndGet(); + } +} \ No newline at end of file diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectWriterBuilder.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectWriterBuilder.java new file mode 100644 index 00000000..697945d1 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzyObjectWriterBuilder.java @@ -0,0 +1,147 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyGetterMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; + +import lombok.Setter; + +@SuppressWarnings("rawtypes") +public class EzyObjectWriterBuilder + extends EzyAbstractWriterBuilder { + + @Setter + protected static boolean debug; + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzyObjectWriterBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + EzyObjectBinding ann = clazz.getAnnotation(EzyObjectBinding.class); + return ann == null ? EzyAccessType.ALL : ann.accessType(); + } + + @Override + protected EzyElementsFetcher newElementsFetcher() { + return new EzyObjectWriterElementsFetcher(); + } + + @Override + protected String makeImplMethodContent(EzyMethod writeMethod) { + EzyFunction.EzyBody methodBody = new EzyFunction(writeMethod) + .modifier("protected") + .body() + .append(new EzyInstruction("\t", "\n") + .variable(clazz.getClazz(), "object") + .equal() + .cast(clazz.getClazz(), "arg1") + ) + .append(new EzyInstruction("\t", "\n") + .variable(EzyObjectBuilder.class, "builder") + .equal() + .clazz(EzyEntityFactory.class) + .dot() + .append("create") + .bracketopen() + .clazz(EzyObjectBuilder.class) + .append(".class") + .bracketclose() + ); + for(Object element : getElements()) { + methodBody.append(newInstructionByElement(element)); + } + methodBody.append(new EzyInstruction("\t", "\n") + .answer() + .append("builder.build()")); + + EzyFunction method = methodBody.function(); + + return method.toString(); + } + + protected EzyInstruction newInstructionByElement(Object element) { + if(element instanceof EzyField) + return newInstructionByField((EzyField)element); + return newInstructionByMethod((EzyMethod)element); + } + + protected EzyInstruction newInstructionByField(EzyField field) { + return newInstruction(field, ""); + } + + protected EzyInstruction newInstructionByMethod(EzyMethod method) { + return newInstruction(method, "()"); + } + + protected EzyInstruction newInstruction( + EzyReflectElement element, String valueExpSuffix) { + EzyInstruction instruction = new EzyInstruction("\t", "\n") + .append("builder") + .dot() + .append("append") + .bracketopen() + .string(getKey(element)) + .comma() + .brackets(Object.class) + .append("arg0.marshal("); + com.tvd12.ezyfoxserver.binding.annotation.EzyWriter wrt = getWriterClass(element); + if(wrt != null) { + instruction + .clazz(wrt.value(), true) + .comma(); + } + Class type = getElementType(element); + instruction + .valueOf(type, "object." + element.getName() + valueExpSuffix) + .append(")") + .bracketclose(); + return instruction; + } + + @Override + protected String getImplClassName() { + return clazz.getName() + "$EzyObjectWriter$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + @Override + protected boolean isDebug() { + return debug; + } +} + +class EzyObjectWriterElementsFetcher extends EzyObjectElementsFetcher { + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getGetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredGetterMethods(); + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzyGetterMethod(method); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getReturnType() != void.class; + } +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleBindingContext.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleBindingContext.java new file mode 100644 index 00000000..d55d92fc --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleBindingContext.java @@ -0,0 +1,391 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.lang.annotation.Annotation; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyBindingContextBuilder; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyPackagesScan; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReaderImpl; +import com.tvd12.ezyfoxserver.binding.annotation.EzyTemplateImpl; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriterImpl; +import com.tvd12.ezyfoxserver.binding.template.EzyMapArrayWriter; +import com.tvd12.ezyfoxserver.binding.template.EzyMapObjectWriter; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings({ "rawtypes" }) +public class EzySimpleBindingContext + extends EzyLoggable + implements EzyBindingContext { + + protected Set writers = new HashSet<>(); + protected Set readers = new HashSet<>(); + protected Map writersByObjectType = new ConcurrentHashMap<>(); + protected Map readersByObjectType = new ConcurrentHashMap<>(); + protected Map unwrappersByObjectType = new ConcurrentHashMap<>(); + + @Override + public EzyMarshaller newMarshaller() { + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.addWriters(writers); + marshaller.addWriters(writersByObjectType); + return marshaller; + } + + @Override + public EzyUnmarshaller newUnmarshaller() { + EzySimpleUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + unmarshaller.addReaders(readers); + unmarshaller.addReaders(readersByObjectType); + unmarshaller.addUnwrappers(unwrappersByObjectType); + return unmarshaller; + } + + @Override + public void addReader(EzyReader reader) { + readers.add(reader); + } + + @Override + public void addWriter(EzyWriter writer) { + writers.add(writer); + } + + @Override + public void addTemplate(Object template) { + if(template instanceof EzyReader) + addReader((EzyReader)template); + if(template instanceof EzyWriter) + addWriter((EzyWriter)template); + } + + @Override + public void bindReader(Class clazz, EzyReader reader) { + readersByObjectType.put(clazz, reader); + } + + @Override + public void bindWriter(Class clazz, EzyWriter writer) { + writersByObjectType.put(clazz, writer); + } + + @Override + public void bindTemplate(Class clazz, Object template) { + if(template instanceof EzyReader) + bindReader(clazz, (EzyReader)template); + if(template instanceof EzyWriter) + bindWriter(clazz, (EzyWriter)template); + if(template instanceof EzyUnwrapper) + bindUnwrapper(clazz, (EzyUnwrapper)template); + } + + public void bindUnwrapper(Class clazz, EzyUnwrapper unwrapper) { + unwrappersByObjectType.put(clazz, unwrapper); + } + + public static EzyBindingContextBuilder builder() { + return new Builder(); + } + + public static class Builder implements EzyBindingContextBuilder { + + protected Set writers = new HashSet<>(); + protected Set readers = new HashSet<>(); + protected Map writersByObjectType = new HashMap<>(); + protected Map readersByObjectType = new HashMap<>(); + protected Map unwrappersByObjectType = new HashMap<>(); + + protected Set writerImplClasses = new HashSet<>(); + protected Set readerImplClasses = new HashSet<>(); + protected Set objectBindingClasses = new HashSet<>(); + protected Set arrayBindingClasses = new HashSet<>(); + protected Set packagesScanClasses = new HashSet<>(); + protected Set configurationClasses = new HashSet<>(); + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#scan(java.lang.String) + */ + @Override + public EzyBindingContextBuilder scan(String packageName) { + objectBindingClasses.addAll( + getAnnotatedClasses(packageName, EzyObjectBinding.class)); + arrayBindingClasses.addAll( + getAnnotatedClasses(packageName, EzyArrayBinding.class)); + writerImplClasses.addAll( + getAnnotatedClasses(packageName, EzyWriterImpl.class)); + readerImplClasses.addAll( + getAnnotatedClasses(packageName, EzyReaderImpl.class)); + addTemplateClasses( + getAnnotatedClasses(packageName, EzyTemplateImpl.class)); + packagesScanClasses.addAll( + getAnnotatedClasses(packageName, EzyPackagesScan.class)); + configurationClasses.addAll( + getAnnotatedClasses(packageName, EzyConfiguration.class)); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#scan(java.lang.String) + */ + @Override + public EzyBindingContextBuilder scan(String... packageNames) { + return scan(Sets.newHashSet(packageNames)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#scan(java.lang.Iterable) + */ + @Override + public EzyBindingContextBuilder scan(Iterable packageNames) { + packageNames.forEach(this::scan); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addClass(java.lang.Class) + */ + @Override + @SuppressWarnings("unchecked") + public EzyBindingContextBuilder addClass(Class clazz) { + if(clazz.isAnnotationPresent(EzyArrayBinding.class)) + arrayBindingClasses.add(clazz); + else + objectBindingClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addObjectBindingClass(java.lang.Class) + */ + @Override + public EzyBindingContextBuilder addObjectBindingClass(Class clazz) { + objectBindingClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addArrayBindingClass(java.lang.Class) + */ + @Override + public EzyBindingContextBuilder addArrayBindingClass(Class clazz) { + arrayBindingClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addClasses(java.lang.Class) + */ + @Override + public EzyBindingContextBuilder addClasses(Class... classes) { + return addClasses(Sets.newHashSet(classes)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addClasses(java.lang.Iterable) + */ + @Override + public EzyBindingContextBuilder addClasses(Iterable classes) { + classes.forEach(this::addClass); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addTemplate(java.lang.Object) + */ + @Override + public EzyBindingContextBuilder addTemplate(Object template) { + if(template instanceof EzyWriter) + writers.add((EzyWriter) template); + if(template instanceof EzyReader) + readers.add((EzyReader) template); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addTemplateClass(java.lang.Class) + */ + @Override + public EzyBindingContextBuilder addTemplateClass(Class clazz) { + if(EzyWriter.class.isAssignableFrom(clazz)) + writerImplClasses.add(clazz); + if(EzyReader.class.isAssignableFrom(clazz)) + readerImplClasses.add(clazz); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addTemplateClasses(java.lang.Iterable) + */ + @Override + public EzyBindingContextBuilder addTemplateClasses(Iterable> classes) { + classes.forEach(this::addTemplateClass); + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#addTemplate(java.lang.Class, java.lang.Object) + */ + @Override + public EzyBindingContextBuilder addTemplate(Class type, Object template) { + if(template instanceof EzyWriter) { + writers.add((EzyWriter) template); + writersByObjectType.put(type, (EzyWriter) template); + } + if(template instanceof EzyReader) { + readers.add((EzyReader) template); + readersByObjectType.put(type, (EzyReader) template); + } + if(template instanceof EzyUnwrapper) { + unwrappersByObjectType.put(type, (EzyUnwrapper)template); + } + return this; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.binding.impl.EzyBindingContextBuilder#build() + */ + @Override + public EzySimpleBindingContext build() { + EzySimpleBindingContext context = new EzySimpleBindingContext(); + scanPackagesScanClasses(); + parseObjectBindingClasses(); + parseArrayBindingClasses(); + parseTemplateClasses(); + mapSubTypesToReaders(); + mapSubTypesToWriters(); + context.writers.add(new EzyMapArrayWriter()); + context.writers.add(new EzyMapObjectWriter()); + context.writers.addAll(writers); + context.readers.addAll(readers); + context.writersByObjectType.putAll(writersByObjectType); + context.readersByObjectType.putAll(readersByObjectType); + context.unwrappersByObjectType.putAll(unwrappersByObjectType); + loadConfigurationClasses(context); + return context; + } + + private void parseObjectBindingClasses() { + objectBindingClasses.forEach(this::parseObjectBindingClass); + } + + private void parseArrayBindingClasses() { + arrayBindingClasses.forEach(this::parseArrayBindingClass); + } + + private void parseObjectBindingClass(Class clazz) { + EzyObjectBinding anno = clazz.getAnnotation(EzyObjectBinding.class); + if(anno == null || anno.write()) { + addTemplate(clazz, new EzyObjectWriterBuilder(new EzyClass(clazz)).build()); + } + if(anno == null || anno.read()) { + addTemplate(clazz, new EzyObjectReaderBuilder(new EzyClass(clazz)).build()); + addTemplate(clazz, new EzyObjectUnwrapperBuilder(new EzyClass(clazz)).build()); + } + } + + private void parseArrayBindingClass(Class clazz) { + EzyArrayBinding anno = clazz.getAnnotation(EzyArrayBinding.class); + if(anno == null || anno.write()) { + addTemplate(clazz, new EzyArrayWriterBuilder(new EzyClass(clazz)).build()); + } + if(anno == null || anno.read()) { + addTemplate(clazz, new EzyArrayReaderBuilder(new EzyClass(clazz)).build()); + addTemplate(clazz, new EzyArrayUnwrapperBuilder(new EzyClass(clazz)).build()); + } + } + + private void parseTemplateClasses() { + writerImplClasses.forEach(this::parseTemplateClass); + readerImplClasses.forEach(this::parseTemplateClass); + } + + @SuppressWarnings("unchecked") + private void parseTemplateClass(Class templateClass) { + addTemplate(EzyClasses.newInstance(templateClass)); + } + + private void scanPackagesScanClasses() { + packagesScanClasses.forEach(this::scanPackagesScanClass); + } + + private void scanPackagesScanClass(Class clazz) { + scan(clazz.getAnnotation(EzyPackagesScan.class).value()); + } + + private void loadConfigurationClasses(EzyBindingContext context) { + for(Class clazz : configurationClasses) + loadConfigurationClass(clazz, context); + } + + private void loadConfigurationClass(Class clazz, EzyBindingContext context) { + new EzySimpleConfigurationLoader(new EzyClass(clazz)).load(context); + } + + private void mapSubTypesToWriters() { + Set classes = new HashSet<>(writersByObjectType.keySet()); + for(Class clazz : classes) + mapSubTypesToWriter(clazz, writersByObjectType.get(clazz)); + } + + private void mapSubTypesToWriter(Class clazz, EzyWriter writer) { + Set subTypes = getSubTypes(clazz); + for(Class subType : subTypes) + writersByObjectType.put(subType, writer); + } + + private void mapSubTypesToReaders() { + Set classes = new HashSet<>(readersByObjectType.keySet()); + for(Class clazz : classes) + mapSubTypesToReader(clazz, readersByObjectType.get(clazz)); + } + + private void mapSubTypesToReader(Class clazz, EzyReader writer) { + Set subTypes = getSubTypes(clazz); + for(Class subType : subTypes) + readersByObjectType.put(subType, writer); + } + + private Set getSubTypes(Class clazz) { + boolean includeSubTypes = false; + Set answer = new HashSet<>(); + if(clazz.isAnnotationPresent(EzyObjectBinding.class)) { + EzyObjectBinding anno = clazz.getAnnotation(EzyObjectBinding.class); + includeSubTypes = anno.subTypes(); + answer.addAll(Sets.newHashSet(anno.subTypeClasses())); + } + else if(clazz.isAnnotationPresent(EzyArrayBinding.class)) { + EzyArrayBinding anno = clazz.getAnnotation(EzyArrayBinding.class); + includeSubTypes = anno.subTypes(); + answer.addAll(Sets.newHashSet(anno.subTypeClasses())); + } + if(!includeSubTypes) + return new HashSet<>(); + if(!answer.isEmpty()) + return answer; + return EzyClasses.flatSuperAndInterfaceClasses(clazz); + } + + private Set> getAnnotatedClasses( + String packageName, Class annClass) { + return EzyPackages.getAnnotatedClasses(packageName, annClass); + } + + } + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleConfigurationLoader.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleConfigurationLoader.java new file mode 100644 index 00000000..18cbf917 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleConfigurationLoader.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import com.tvd12.ezyfoxserver.binding.EzyBindingConfig; +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyBindingContextAware; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzySimpleConfigurationLoader implements EzyConfigurationLoader { + + private final EzyClass clazz; + + public EzySimpleConfigurationLoader(EzyClass clazz) { + this.clazz = clazz; + } + + @Override + public void load(EzyBindingContext context) { + Object configurator = clazz.newInstance(); + if(configurator instanceof EzyBindingContextAware) + ((EzyBindingContextAware)configurator).setContext(context); + if(configurator instanceof EzyBindingConfig) + ((EzyBindingConfig)configurator).config(); + } +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleMarshaller.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleMarshaller.java new file mode 100644 index 00000000..37329f04 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleMarshaller.java @@ -0,0 +1,154 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyTypes; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +import groovyjarjarantlr.collections.List; + +public class EzySimpleMarshaller + extends EzyEntityBuilders + implements EzyMarshaller { + + @SuppressWarnings("rawtypes") + protected final Map writersByType; + @SuppressWarnings("rawtypes") + protected final Map writersByObjectType; + + public EzySimpleMarshaller() { + this.writersByObjectType = defaultWriters(); + this.writersByType = defaultWritersByType(); + } + + @SuppressWarnings("rawtypes") + public void addWriter(EzyWriter writer) { + writersByType.put(writer.getClass(), writer); + } + + @SuppressWarnings("rawtypes") + public void addWriters(Iterable writers) { + writers.forEach(this::addWriter); + } + + @SuppressWarnings("rawtypes") + public void addWriter(Class type, EzyWriter writer) { + writersByObjectType.put(type, writer); + writersByType.put(writer.getClass(), writer); + } + + @SuppressWarnings("rawtypes") + public void addWriters(Map writers) { + writers.keySet().forEach(key -> addWriter(key, writers.get(key))); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public T marshal(Object object) { + if(object == null) + return null; + Class objectType = object.getClass(); + EzyWriter writer = EzyMaps.getValue(writersByObjectType, objectType); + if(writer != null) + return (T) writer.write(this, object); + if(objectType.isArray()) + return (T) writeArray((Object[])object); + throw new IllegalArgumentException("has no writer for " + object.getClass()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public T marshal(Class writerClass, Object object) { + if(writersByType.containsKey(writerClass)) + return (T) writersByType.get(writerClass).write(this, object); + throw new IllegalArgumentException("can't marshal object " + + object + ", " + writerClass.getName() + " is not writer class"); + } + + @SuppressWarnings("rawtypes") + private Map defaultWritersByType() { + Map map = new ConcurrentHashMap<>(); + writersByObjectType.values().forEach(w -> map.put(w.getClass(), w)); + return map; + } + + @SuppressWarnings("rawtypes") + private Map defaultWriters() { + Map map = new ConcurrentHashMap<>(); + Set normalTypes = EzyTypes.ALL_TYPES; + for(Class normalType : normalTypes) + map.put(normalType, defaultWriter()); + map.put(Date.class, defaultWriter()); + map.put(Class.class, defaultWriter()); + map.put(LocalDate.class, defaultWriter()); + map.put(LocalDateTime.class, defaultWriter()); + map.put(EzyArray.class, defaultWriter()); + map.put(EzyObject.class, defaultWriter()); + map.put(Map.class, mapWriter()); + map.put(HashMap.class, mapWriter()); + map.put(TreeMap.class, mapWriter()); + map.put(ConcurrentHashMap.class, mapWriter()); + map.put(List.class, collectionWriter()); + map.put(Set.class, collectionWriter()); + map.put(ArrayList.class, collectionWriter()); + map.put(HashSet.class, collectionWriter()); + map.put(Collection.class, collectionWriter()); + return map; + } + + @SuppressWarnings("rawtypes") + private EzyWriter defaultWriter() { + return (m, o) -> o; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private EzyWriter mapWriter() { + return (m, o) -> { + EzyObjectBuilder builder = newObjectBuilder(); + Map map = (Map)o; + map.entrySet().forEach(e -> writeEntry(builder, (Entry) e)); + return builder.build(); + }; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private EzyWriter collectionWriter() { + return (m, o) -> { + EzyArrayBuilder builder = newArrayBuilder(); + Collection collection = (Collection)o; + collection.forEach(i -> builder.append((Object)marshal(i))); + return builder.build(); + }; + } + + private EzyArray writeArray(Object[] array) { + EzyArrayBuilder builder = newArrayBuilder(); + Arrays.stream(array).forEach(o -> builder.append((Object)marshal(o))); + return builder.build(); + } + + @SuppressWarnings("rawtypes") + private void writeEntry(EzyObjectBuilder builder, Entry entry) { + builder.append(marshal(entry.getKey()), (Object)marshal(entry.getValue())); + } + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleUnmarshaller.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleUnmarshaller.java new file mode 100644 index 00000000..a647e810 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/impl/EzySimpleUnmarshaller.java @@ -0,0 +1,165 @@ +package com.tvd12.ezyfoxserver.binding.impl; + +import java.lang.reflect.Array; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.reflect.EzyTypes; +import com.tvd12.ezyfoxserver.util.EzyCollectionFactory; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; +import com.tvd12.ezyfoxserver.util.EzyMapFactory; + +public class EzySimpleUnmarshaller + extends EzyEntityBuilders + implements EzyUnmarshaller { + + @SuppressWarnings("rawtypes") + protected final Map readersByType; + @SuppressWarnings("rawtypes") + protected final Map readersByObjectType; + @SuppressWarnings("rawtypes") + protected Map unwrappersByObjectType; + + protected final EzyMapFactory mapFactory = new EzyMapFactory(); + protected final EzyCollectionFactory collectionFactory = new EzyCollectionFactory(); + + public EzySimpleUnmarshaller() { + this.readersByObjectType = defaultReaders(); + this.readersByType = defaultReadersByType(); + this.unwrappersByObjectType = new ConcurrentHashMap<>(); + } + + @SuppressWarnings("rawtypes") + public void addReader(EzyReader reader) { + readersByType.put(reader.getClass(), reader); + } + + @SuppressWarnings("rawtypes") + public void addReaders(Iterable readers) { + readers.forEach(this::addReader); + } + + @SuppressWarnings("rawtypes") + public void addReader(Class type, EzyReader reader) { + readersByObjectType.put(type, reader); + readersByType.put(reader.getClass(), reader); + } + + @SuppressWarnings("rawtypes") + public void addReaders(Map readers) { + readers.keySet().forEach(key -> addReader(key, readers.get(key))); + } + + @SuppressWarnings("rawtypes") + public void addUnwrapper(Class type, EzyUnwrapper unwrapper) { + unwrappersByObjectType.put(type, unwrapper); + } + + @SuppressWarnings("rawtypes") + public void addUnwrappers(Map unwrappers) { + unwrappers.keySet().forEach(key -> addUnwrapper(key, unwrappers.get(key))); + } + + @SuppressWarnings("unchecked") + @Override + public void unwrap(Object value, Object output) { + unwrappersByObjectType.get(output.getClass()).unwrap(this, value, output);; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public T unmarshal(Object value, Class outType) { + if(value == null) + return null; + EzyReader reader = EzyMaps.getValue(readersByObjectType, outType); + if(reader != null) + return (T) reader.read(this, value); + if(outType.isArray()) + return (T) readArray((EzyArray)value, outType.getComponentType()); + throw new IllegalArgumentException("has no reader for " + outType); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public Map unmarshalMap( + Object value, Class mapType, Class keyType, Class valueType) { + Map map = mapFactory.newMap(mapType); + EzyObject object = (EzyObject)value; + for(Object key : object.keySet()) + map.put(unmarshal(key, keyType), unmarshal((Object)object.get(key), valueType)); + return map; + } + + @SuppressWarnings("rawtypes") + @Override + public Collection unmarshalCollection( + Object value, Class collectionType, Class itemType) { + if(value instanceof Collection) + return unmarshalCollection(((Collection)value).iterator(), collectionType, itemType); + return unmarshalCollection(((EzyArray)value).iterator(), collectionType, itemType); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private Collection unmarshalCollection( + Iterator iterator, Class collectionType, Class itemType) { + Collection collection = collectionFactory.newCollection(collectionType); + while(iterator.hasNext()) + collection.add(unmarshal(iterator.next(), itemType)); + return collection; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public T unmarshal(Class readerClass, Object value) { + if(readersByType.containsKey(readerClass)) + return (T) readersByType.get(readerClass).read(this, value); + throw new IllegalArgumentException("can't unmarshal value " + + value + ", " + readerClass.getName() + " is not reader class"); + } + + @SuppressWarnings("rawtypes") + private Map defaultReadersByType() { + Map map = new ConcurrentHashMap<>(); + readersByObjectType.values().forEach(w -> map.put(w.getClass(), w)); + return map; + } + + @SuppressWarnings("rawtypes") + private Map defaultReaders() { + Map map = new ConcurrentHashMap<>(); + Set normalTypes = EzyTypes.ALL_TYPES; + for(Class normalType : normalTypes) + map.put(normalType, defaultReader()); + map.put(Date.class, defaultReader()); + map.put(Class.class, defaultReader()); + map.put(LocalDate.class, defaultReader()); + map.put(LocalDateTime.class, defaultReader()); + return map; + } + + @SuppressWarnings("rawtypes") + private EzyReader defaultReader() { + return (um, o) -> o; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private Object[] readArray(EzyArray array, Class componentType) { + Object[] answer = (Object[]) Array.newInstance(componentType, array.size()); + for(int i = 0 ; i < array.size() ; i++) + answer[i] = unmarshal((Object)array.get(i), componentType); + return answer; + } + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapArrayWriter.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapArrayWriter.java new file mode 100644 index 00000000..3086de89 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapArrayWriter.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.binding.template; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +@SuppressWarnings("rawtypes") +public class EzyMapArrayWriter + extends EzyEntityBuilders + implements EzyWriter { + + @Override + public EzyArray write(EzyMarshaller marshaller, Map map) { + EzyArrayBuilder arrayBuilder = newArrayBuilder(); + for(Object key : map.keySet()) { + EzyObjectBuilder objectBuilder = newObjectBuilder(); + Object tkey = marshaller.marshal(key); + Object tvalue = marshaller.marshal(map.get(key)); + objectBuilder.append("k", tkey); + objectBuilder.append("v", tvalue); + arrayBuilder.append(objectBuilder); + } + return arrayBuilder.build(); + } + +} diff --git a/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapObjectWriter.java b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapObjectWriter.java new file mode 100644 index 00000000..7da5e8a5 --- /dev/null +++ b/ezyfox-server-binding/src/main/java/com/tvd12/ezyfoxserver/binding/template/EzyMapObjectWriter.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.binding.template; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +@SuppressWarnings("rawtypes") +public class EzyMapObjectWriter + extends EzyEntityBuilders + implements EzyWriter { + + @Override + public EzyObject write(EzyMarshaller marshaller, Map map) { + EzyObjectBuilder builder = newObjectBuilder(); + for(Object key : map.keySet()) { + Object tkey = marshaller.marshal(key); + Object tvalue = marshaller.marshal(map.get(key)); + builder.append(tkey, tvalue); + } + return builder.build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/BasePoint.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/BasePoint.java new file mode 100644 index 00000000..aa805629 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/BasePoint.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class BasePoint { + protected int x; + protected int y; + + public String getXY() { + return x + "-" + y; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractBuilderTest.java new file mode 100644 index 00000000..8db98563 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractBuilderTest.java @@ -0,0 +1,86 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Field; +import java.util.List; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectElementsFetcher; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractBuilderTest extends BaseTest { + + @Test + public void test() throws Exception { + Field name = A.class.getDeclaredField("name"); + EzyField field = new EzyField(name); + EzyElementBuilder builder = new EzyElementBuilder(new EzyClass(A.class)); + assertEquals(builder.getFieldName(field), "name"); + builder.getElementType(null); + } + + public static class A { + public String name; + } + + @SuppressWarnings("rawtypes") + public static class EzyElementBuilder extends EzyAbstractBuilder { + + public EzyElementBuilder(EzyClass clazz) { + super(clazz); + } + + @Override + public Class getElementType(Object element) { + return super.getElementType(element); + } + + @Override + protected int getAccessType(EzyClass clazz) { + return EzyAccessType.ALL; + } + + @Override + protected EzyObjectElementsFetcher newElementsFetcher() { + return new EzyObjectElementsFetcher() { + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getGetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredGetterMethods(); + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzySetterMethod(method); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getParameterCount() == 1; + } + + }; + } + + @Override + public String getFieldName(EzyReflectElement element) { + return super.getFieldName(element); + } + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractReaderBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractReaderBuilderTest.java new file mode 100644 index 00000000..fa3e335d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractReaderBuilderTest.java @@ -0,0 +1,83 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyElementsFetcher; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectElementsFetcher; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractReaderBuilderTest extends BaseTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test1() { + new Builder1(new EzyClass(getClass())).build(); + } + + public static class Builder1 extends EzyAbstractReaderBuilder { + public Builder1(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + return EzyAccessType.ALL; + } + + @Override + protected EzyElementsFetcher newElementsFetcher() { + return new EzyObjectElementsFetcher() { + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getSetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredSetterMethods(); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getParameterCount() == 1; + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzySetterMethod(method); + } + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected EzyReader make() throws Exception { + throw new Exception(); + } + + @Override + protected String getImplClassName() { + return ""; + } + + @Override + protected String makeImplMethodContent(EzyMethod readMethod) { + return ""; + } + + @Override + protected boolean isDebug() { + return false; + } + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractTemplateTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractTemplateTest.java new file mode 100644 index 00000000..774ec2cc --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractTemplateTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractTemplate; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractTemplateTest extends BaseTest { + + @SuppressWarnings("rawtypes") + @Test + public void test() { + new EzyAbstractTemplate() { + @Override + public Object read(EzyUnmarshaller unmarshaller, Object value) { + return null; + } + + @Override + public Object write(EzyMarshaller marshaller, Object object) { + return null; + } + }; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractWriterBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractWriterBuilderTest.java new file mode 100644 index 00000000..82f5524e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAbstractWriterBuilderTest.java @@ -0,0 +1,85 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyElementsFetcher; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectElementsFetcher; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyGetterMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractWriterBuilderTest extends BaseTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() { + new Builder1(new EzyClass(getClass())).build(); + } + + public static class Builder1 extends EzyAbstractWriterBuilder { + + public Builder1(EzyClass clazz) { + super(clazz); + } + + @Override + protected int getAccessType(EzyClass clazz) { + return EzyAccessType.ALL; + } + + @Override + protected EzyElementsFetcher newElementsFetcher() { + return new EzyObjectElementsFetcher() { + + @Override + protected List getMethods(EzyClass clazz) { + return clazz.getGetterMethods(); + } + + @Override + protected List getDeclaredMethods(EzyClass clazz) { + return clazz.getDeclaredGetterMethods(); + } + + @Override + protected boolean isValidAnnotatedMethod(EzyMethod method) { + return method.getReturnType() != void.class; + } + + @Override + protected EzyMethod newByFieldMethod(EzyMethod method) { + return new EzyGetterMethod(method); + } + + }; + } + + @SuppressWarnings("rawtypes") + @Override + protected EzyWriter make() throws Exception { + throw new Exception(); + } + + @Override + protected String getImplClassName() { + return ""; + } + + @Override + protected String makeImplMethodContent(EzyMethod writeMethod) { + return ""; + } + + @Override + protected boolean isDebug() { + return false; + } + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAccessTypeTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAccessTypeTest.java new file mode 100644 index 00000000..5a9ae3e2 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyAccessTypeTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.test.base.BaseTest; + +public class EzyAccessTypeTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyAccessType.class; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayReaderBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayReaderBuilderTest.java new file mode 100644 index 00000000..10b455c0 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayReaderBuilderTest.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.util.HashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyReader; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2Object; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2ObjectReader; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzyArrayReaderBuilderTest extends BaseTest { + + @Test + public void test() { + EzyArrayReaderBuilder builder + = new EzyArrayReaderBuilder(new EzyClass(ClassA.class)); + builder.build(); + } + + @SuppressWarnings("rawtypes") + public static class ClassA { + public Map map = new HashMap<>(); + @EzyReader(Scan2ObjectReader.class) + public Scan2Object object = new Scan2Object(); + public ClassB classB; + + public void setValue(String value) { + + } + } + + @SuppressWarnings({ "rawtypes", "serial" }) + public static class ClassB extends HashMap { + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayWriterBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayWriterBuilderTest.java new file mode 100644 index 00000000..51f8d900 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyArrayWriterBuilderTest.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReader; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2Object; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2ObjectReader; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2ObjectWriter; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzyArrayWriterBuilderTest extends BaseTest { + + @Test + public void test() { + EzyArrayWriterBuilder builder = new EzyArrayWriterBuilder(new EzyClass(ClassA.class)); + builder.build(); + } + + @Test + public void test2() { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayWriterBuilder builder = new EzyArrayWriterBuilder(new EzyClass(ClassB.class)); + builder.build(); + } + + public static class ClassA { + + @EzyReader(Scan2ObjectReader.class) + @EzyWriter(Scan2ObjectWriter.class) + public Scan2Object object = new Scan2Object(); + + protected String value1 = "value1"; + + protected void setValue1(String value1) { + this.value1 = value1; + } + + } + + @EzyArrayBinding + public static class ClassB { + + private String value1 = "value1"; + protected String value2 = "value2"; + protected String value3 = "value3"; + + protected void setValue1(String value1) { + this.value1 = value1; + } + + protected String getValue1() { + return value1; + } + + public String getValue3x() { + return ""; + } + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyObjectReaderBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyObjectReaderBuilderTest.java new file mode 100644 index 00000000..31d7d455 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyObjectReaderBuilderTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.util.Collection; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzyObjectReaderBuilderTest extends BaseTest { + + @Test + public void test() { + EzyObjectReaderBuilder.setDebug(true); + EzyObjectReaderBuilder builder = new EzyObjectReaderBuilder(new EzyClass(ClassA.class)); + builder.build(); + } + + @SuppressWarnings("rawtypes") + public static class ClassA { + public Map map; + public void setCollection(Collection collection) { + } + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointReaderImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointReaderImpl.java new file mode 100644 index 00000000..75998104 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointReaderImpl.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +@SuppressWarnings("rawtypes") +public class EzyPointReaderImpl implements EzyReader { + + @Override + public Object read(EzyUnmarshaller arg0, Object arg1) { + EzyObject value = (EzyObject)arg1; + Point object = new Point(); + if(value.isNotNullValue("a1")) + object.a1 = (String)arg0.unmarshal((Object)value.getValue("a1", String.class), String.class); + if(value.isNotNullValue("3")) + object.setX(((Integer)arg0.unmarshal((Object)value.getValue("3", int.class), int.class)).intValue()); + if(value.isNotNullValue("x")) + object.setX(((Integer)arg0.unmarshal((Object)value.getValue("x", int.class), int.class)).intValue()); + if(value.isNotNullValue("y")) + object.setY(((Integer)arg0.unmarshal((Object)value.getValue("y", int.class), int.class)).intValue()); + if(value.isNotNullValue("point")) + object.setPoint((Point)arg0.unmarshal((Object)value.getValue("point", Point.class), Point.class)); + if(value.isNotNullValue("data")) + object.setData((EzyTestData)arg0.unmarshal((Object)value.getValue("data", EzyTestData.class), EzyTestData.class)); + if(value.isNotNullValue("date")) + object.setDate((Date)arg0.unmarshal((Object)value.getValue("date", Date.class), Date.class)); + if(value.isNotNullValue("localDate")) + object.setLocalDate((LocalDate)arg0.unmarshal((Object)value.getValue("localDate", LocalDate.class), LocalDate.class)); + if(value.isNotNullValue("localDateTime")) + object.setLocalDateTime((LocalDateTime)arg0.unmarshal((Object)value.getValue("localDateTime", LocalDateTime.class), LocalDateTime.class)); + if(value.isNotNullValue("clazz")) + object.setClazz((Class)arg0.unmarshal((Object)value.getValue("clazz", Class.class), Class.class)); + if(value.isNotNullValue("data1")) + object.setData1((EzyTestData1)arg0.unmarshal(TestData1ReaderImpl.class, (Object)value.getValue("data1", EzyTestData1.class))); + return object; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample10.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample10.java new file mode 100644 index 00000000..4b4a1085 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample10.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.binding.testing.scan1.Scan1ClassA; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class EzyPointWriterExample10 { + + @Test + public void test() throws Exception { + + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.scan1") + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + EzyObject outObject = marshaller.marshal(new Scan1ClassA()); + outObject.put("hung", "xau trai"); + System.out.println(outObject); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + Scan1ClassA outEntity = unmarshaller.unmarshal(outObject, Scan1ClassA.class); + System.out.println(outEntity); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample3.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample3.java new file mode 100644 index 00000000..5da66ef1 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample3.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyPointWriterExample3 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyClass pointClazz = new EzyClass(Point.class); + EzyClass dataClazz = new EzyClass(EzyTestData.class); + EzyObjectWriterBuilder pointWriterBuilder = new EzyObjectWriterBuilder(pointClazz); + EzyObjectWriterBuilder dataWriterBuilder = new EzyObjectWriterBuilder(dataClazz); + EzyWriter pointWriter = pointWriterBuilder.build(); + EzyWriter dataWriter = dataWriterBuilder.build(); + + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.addWriter(Point.class, pointWriter); + marshaller.addWriter(EzyTestData.class, dataWriter); + marshaller.addWriter(new TestData1WriterImpl()); + + System.out.println(pointWriter.write(marshaller, new Point())); + +// long time1 = Performance.create() +// .loop(1000000) +// .test(() -> +// writer.write(new Point()) +// ) +// .getTime(); +// +// System.out.println(time1); +// +// ExWriter wr = new ExWriter(); +// long time2 = Performance.create() +// .loop(1000000) +// .test(() -> +// wr.write(new Point()) +// ) +// .getTime(); +// +// System.out.println(time2); +// +// long time3 = Performance.create() +// .loop(1000000) +// .test(() -> { +// Point point = new Point(); +// EzyObjectBuilder ebuilder = EzyEntityFactory.create(EzyObjectBuilder.class); +// ebuilder.append("x", point.getX()); +// ebuilder.append("x", point.getY()); +// ebuilder.append("xY", point.getXY()); +// ebuilder.build(); +// }) +// .getTime(); +// +// System.out.println(time3); + + + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample4.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample4.java new file mode 100644 index 00000000..c724fbac --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample4.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyPointWriterExample4 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyWriter pointWriter = new EzyPointWriterImpl(); + EzyWriter dataWriter = new EzyTestDataWriterImpl(); + EzyWriter data1Writer = new TestData1WriterImpl(); + + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.addWriter(Point.class, pointWriter); + marshaller.addWriter(EzyTestData.class, dataWriter); + marshaller.addWriter(data1Writer); + + System.out.println(pointWriter.write(marshaller, new Point())); + + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample5.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample5.java new file mode 100644 index 00000000..e434ee0f --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample5.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; + +public class EzyPointWriterExample5 { + + @Test + public void test() throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(Point.class) + .addClass(EzyTestData.class) + .addTemplate(new TestData1WriterImpl()) + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + + System.out.println(marshaller.marshal(new Point()).toString()); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample6.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample6.java new file mode 100644 index 00000000..275720a0 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample6.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.binding.testing.scan1.Scan1ClassA; + +public class EzyPointWriterExample6 { + + @Test + public void test() throws Exception { + + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.scan1") + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + + System.out.println(marshaller.marshal(new Scan1ClassA()).toString()); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample7.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample7.java new file mode 100644 index 00000000..7b9a1fe9 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample7.java @@ -0,0 +1,80 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.test.performance.Performance; + +public class EzyPointWriterExample7 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyWriter pointWriter = new EzyPointWriterImpl(); + EzyWriter dataWriter = new EzyTestDataWriterImpl(); + EzyWriter data1Writer = new TestData1WriterImpl(); + + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.addWriter(Point.class, pointWriter); + marshaller.addWriter(EzyTestData.class, dataWriter); + marshaller.addWriter(data1Writer); + + EzyObject outObject = pointWriter.write(marshaller, new Point()); + + System.out.println(outObject); + + EzyReader pointReader = new EzyPointReaderImpl(); + EzyReader dataReader = new EzyTestDataReaderImpl(); + EzyReader data1Reader = new TestData1ReaderImpl(); + + EzySimpleUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + unmarshaller.addReader(Point.class, pointReader); + unmarshaller.addReader(EzyTestData.class, dataReader); + unmarshaller.addReader(data1Reader); + + Point outPoint = pointReader.read(unmarshaller, outObject); + System.out.println(outPoint); + + long time1 = Performance.create() + .loop(10000) + .test(() -> + pointWriter.write(marshaller, new Point()) + ) + .getTime(); + + System.out.println(time1); + + long time2 = Performance.create() + .loop(10000) + .test(() -> + pointWriter.write(marshaller, new Point()) + ) + .getTime(); + + System.out.println(time2); + + long time3 = Performance.create() + .loop(10000) + .test(() -> + pointReader.read(unmarshaller, outObject) + ) + .getTime(); + + System.out.println(time3); + + long time4 = Performance.create() + .loop(10000) + .test(() -> + pointReader.read(unmarshaller, outObject) + ) + .getTime(); + + System.out.println(time4); + + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample8.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample8.java new file mode 100644 index 00000000..87dedf97 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterExample8.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class EzyPointWriterExample8 { + + @Test + public void test() throws Exception { + + EzyBindingContext context = EzyBindingContext.builder() + .addClass(Point.class) + .addClass(EzyTestData.class) + .addTemplate(new TestData1WriterImpl()) + .addTemplate(new TestData1ReaderImpl()) + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + EzyObject outObject = marshaller.marshal(new Point()); + System.out.println(outObject); + + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + Point outPoint = unmarshaller.unmarshal(outObject, Point.class); + System.out.println(outPoint); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterImpl.java new file mode 100644 index 00000000..07f7d7fb --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyPointWriterImpl.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; + +@SuppressWarnings("rawtypes") +public class EzyPointWriterImpl implements EzyWriter { + + public EzyObject write(EzyMarshaller arg0, Object arg1) { + Point object = ((Point)(arg1)); + EzyObjectBuilder builder = EzyEntityFactory.create(com.tvd12.ezyfoxserver.builder.EzyObjectBuilder.class); + builder.append("a1", (Object)arg0.marshal(object.a1)); + builder.append("xY", (Object)arg0.marshal(object.getXY())); + builder.append("3", (Object)arg0.marshal(object.getX())); + builder.append("x", (Object)arg0.marshal(object.getX())); + builder.append("y", (Object)arg0.marshal(object.getY())); + builder.append("b", (Object)arg0.marshal(object.getB())); + builder.append("point", (Object)arg0.marshal(object.getPoint())); + builder.append("data", (Object)arg0.marshal(object.getData())); + builder.append("date", (Object)arg0.marshal(object.getDate())); + builder.append("localDate", (Object)arg0.marshal(object.getLocalDate())); + builder.append("localDateTime", (Object)arg0.marshal(object.getLocalDateTime())); + builder.append("clazz", (Object)arg0.marshal(object.getClazz())); + builder.append("data1", (Object)arg0.marshal(TestData1WriterImpl.class, object.getData1())); + return builder.build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextArrayTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextArrayTest.java new file mode 100644 index 00000000..b94c57d9 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextArrayTest.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +public class EzySimpleBindingContextArrayTest extends BaseTest { + + @Test + public void test() { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addArrayBindingClass(A1.class) + .addArrayBindingClass(A2.class) + .addArrayBindingClass(A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyArray array = marshaller.marshal(new A1()); + A1 a = unmarshaller.unmarshal(array, A1.class); + System.out.println(a); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addArrayBindingClass(A1.class) + .addArrayBindingClass(A2.class) + .addArrayBindingClass(A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyArray array = marshaller.marshal(new A2()); + A2 a = unmarshaller.unmarshal(array, A2.class); + System.out.println(a); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addArrayBindingClass(A1.class) + .addArrayBindingClass(A2.class) + .addArrayBindingClass(A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + marshaller.marshal(new A3()); + } + + @Getter + @Setter + @ToString + public static class A1 { + private String name = "n"; + private String value = "v"; + } + + @Getter + @Setter + @ToString + @EzyArrayBinding(read = false) + public static class A2 { + private String name = "n"; + private String value = "v"; + } + + @Getter + @Setter + @ToString + @EzyArrayBinding(write = false) + public static class A3 { + private String name = "n"; + private String value = "v"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextObjectTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextObjectTest.java new file mode 100644 index 00000000..be93d271 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleBindingContextObjectTest.java @@ -0,0 +1,85 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +public class EzySimpleBindingContextObjectTest extends BaseTest { + + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClasses(A1.class, A2.class, A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyObject object = marshaller.marshal(new A1()); + A1 a = unmarshaller.unmarshal(object, A1.class); + System.out.println(a); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClasses(A1.class, A2.class, A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyObject object = marshaller.marshal(new A2()); + A2 a = unmarshaller.unmarshal(object, A2.class); + System.out.println(a); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClasses(A1.class, A2.class, A3.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + marshaller.marshal(new A3()); + } + + @Getter + @Setter + @ToString + public static class A1 { + private String name = "n"; + private String value = "v"; + } + + @Getter + @Setter + @ToString + @EzyObjectBinding(read = false) + public static class A2 { + private String name = "n"; + private String value = "v"; + } + + @Getter + @Setter + @ToString + @EzyObjectBinding(write = false) + public static class A3 { + private String name = "n"; + private String value = "v"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleMarshallerTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleMarshallerTest.java new file mode 100644 index 00000000..1937ca2f --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleMarshallerTest.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleMarshallerTest extends BaseTest { + + @Test + public void test1() { + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.addWriter(ClassA.class, new EzyObjectWriterBuilder(new EzyClass(ClassA.class)).build()); + ClassA[] arrayInput = new ClassA[] {new ClassA(), new ClassA(), new ClassA()}; + EzyArray arrayOutput = marshaller.marshal(arrayInput); + assert arrayOutput.size() == 3; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.marshal(new Object()); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + EzySimpleMarshaller marshaller = new EzySimpleMarshaller(); + marshaller.marshal(ExWriter.class, new Object()); + } + + public static class ClassA { + + } + + @SuppressWarnings("rawtypes") + public static class ExWriter implements EzyWriter { + + @Override + public Object write(EzyMarshaller marshaller, Object object) { + return null; + } + + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleUnmarshallerTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleUnmarshallerTest.java new file mode 100644 index 00000000..2b9a66a5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzySimpleUnmarshallerTest.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.util.Collection; +import java.util.List; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleUnmarshallerTest extends BaseTest { + + @Test + public void test1() { + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + Object object1 = unmarshaller.unmarshal((Object)null, Object.class); + assertNull(object1); + + Integer[] arrayInput = new Integer[] {1, 2, 3}; + Integer[] arrayOutput = unmarshaller.unmarshal(arrayInput, Integer[].class); + assertEquals(arrayInput, arrayOutput); + + Collection collectionInput = Lists.newArrayList(1, 2, 3); + Collection collectionOutput = unmarshaller.unmarshalCollection( + (Object)collectionInput, List.class, Integer.class); + assertEquals(collectionInput, collectionOutput); + + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + unmarshaller.unmarshal(new Object(), Object.class); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + unmarshaller.unmarshal(ExReader.class, new Object()); + } + + @SuppressWarnings("rawtypes") + public static class ExReader implements EzyReader { + + @Override + public Object read(EzyUnmarshaller unmarshaller, Object value) { + return null; + } + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData.java new file mode 100644 index 00000000..0ef83211 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzyTestData { + + private int data1 = 100; + private int data2 = 100; + private int data3 = 100; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData1.java new file mode 100644 index 00000000..e67db71e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestData1.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzyTestData1 { + + private int data1 = 100; + private int data2 = 100; + private int data3 = 100; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataReaderImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataReaderImpl.java new file mode 100644 index 00000000..f8dd09a4 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataReaderImpl.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractReader; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +@SuppressWarnings("rawtypes") +public class EzyTestDataReaderImpl extends EzyAbstractReader { + + @Override + public Object read(EzyUnmarshaller arg0, Object arg1) { + EzyObject value = ((EzyObject)arg1); + EzyTestData data = new EzyTestData(); + if(value.isNotNullValue("1")) + data.setData1(((Integer)arg0.unmarshal((Object)value.getValue("1", int.class), int.class)).intValue()); + if(value.isNotNullValue("2")) + data.setData2(((Integer)arg0.unmarshal((Object)value.getValue("2", int.class), int.class)).intValue()); + if(value.isNotNullValue("3")) + data.setData2(((Integer)arg0.unmarshal((Object)value.getValue("3", int.class), int.class)).intValue()); + return data; + } + + + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataWriterImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataWriterImpl.java new file mode 100644 index 00000000..df3112f8 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/EzyTestDataWriterImpl.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; + +@SuppressWarnings("rawtypes") +public class EzyTestDataWriterImpl implements EzyWriter { + + @Override + public EzyObject write(EzyMarshaller arg0, Object arg1) { + EzyTestData object = ((EzyTestData)(arg1)); + EzyObjectBuilder builder = EzyEntityFactory.create(com.tvd12.ezyfoxserver.builder.EzyObjectBuilder.class); + builder.append("1", (Object)arg0.marshal(object.getData1())); + builder.append("2", (Object)arg0.marshal(object.getData1())); + builder.append("3", (Object)arg0.marshal(object.getData1())); + return builder.build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Point.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Point.java new file mode 100644 index 00000000..ea879f75 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Point.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyIgnore; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReader; +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriter; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class Point extends BasePoint { + + @EzyValue("3") + public int z = 100; + + @EzyIgnore + public String a = "a"; + + @Getter(AccessLevel.NONE) + @Setter(AccessLevel.NONE) + public String a1 = "a1"; + + private Point point; + + private EzyTestData data = new EzyTestData(); + + @EzyWriter(TestData1WriterImpl.class) + @EzyReader(TestData1ReaderImpl.class) + private EzyTestData1 data1 = new EzyTestData1(); + + private Date date = new Date(); + private LocalDate localDate = LocalDate.now(); + private LocalDateTime localDateTime = LocalDateTime.now(); + @SuppressWarnings("rawtypes") + private Class clazz = Point.class; + + public Point() { + this.point = new Point(1, 0); + } + + public Point(int x, int y) { + this.x = x; + this.y = y; + } + + public void move(int x, int y) { + this.x = x; + this.y = y; + } + + public String getB() { + return "b"; + } + + @EzyIgnore + public String getC() { + return "c"; + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Scan23Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Scan23Test.java new file mode 100644 index 00000000..9d7cfcad --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Scan23Test.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import org.testng.annotations.Test; +import org.testng.collections.Lists; + +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2Object; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2ObjectReader; +import com.tvd12.ezyfoxserver.binding.testing.scan2.Scan2ObjectWriter; +import com.tvd12.ezyfoxserver.binding.testing.scan3.Scan3Array; +import com.tvd12.test.base.BaseTest; + +public class Scan23Test extends BaseTest { + + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.scan2", "com.tvd12.ezyfoxserver.binding.testing.scan3") + .addClasses(Scan2Object.class, Scan3Array.class) + .addObjectBindingClass(Scan2Object.class) + .addArrayBindingClass(Scan3Array.class) + .addTemplateClass(Integer.class) + .addTemplateClasses(Lists.newArrayList(Scan2ObjectReader.class, Scan2ObjectWriter.class)) + .build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1ReaderImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1ReaderImpl.java new file mode 100644 index 00000000..05dd707d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1ReaderImpl.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReaderImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractReader; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +@EzyReaderImpl +public class TestData1ReaderImpl extends EzyAbstractReader { + + @Override + public EzyTestData1 read(EzyUnmarshaller arg0, EzyArray array) { + EzyTestData1 data = new EzyTestData1(); + data.setData1(((Integer)arg0.unmarshal((Object)array.getValue(0, int.class), int.class)).intValue()); + data.setData2(((Integer)arg0.unmarshal((Object)array.getValue(1, int.class), int.class)).intValue()); + data.setData3(((Integer)arg0.unmarshal((Object)array.getValue(2, int.class), int.class)).intValue()); + return data; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1WriterImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1WriterImpl.java new file mode 100644 index 00000000..7b6640f5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/TestData1WriterImpl.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriterImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractWriter; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +@EzyWriterImpl +public class TestData1WriterImpl + extends EzyAbstractWriter { + + @Override + public EzyArray write(EzyMarshaller marshaller, EzyTestData1 object) { + return newArrayBuilder() + .append(object.getData1()) + .append(object.getData2()) + .append(object.getData3()) + .build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Tmp.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Tmp.java new file mode 100644 index 00000000..19b74ccf --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/Tmp.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.binding.testing; + +public class Tmp { + + @SuppressWarnings("rawtypes") + public java.lang.Object read(com.tvd12.ezyfoxserver.binding.EzyUnmarshaller arg0, java.lang.Object arg1) { + com.tvd12.ezyfoxserver.entity.EzyObject value = ((com.tvd12.ezyfoxserver.entity.EzyObject)(arg1)); + com.tvd12.ezyfoxserver.binding.testing.Point object = new com.tvd12.ezyfoxserver.binding.testing.Point(); + if(value.isNotNullValue("a1")) + object.a1 = ((java.lang.String)(arg0.unmarshal((java.lang.Object)value.getValue("a1", java.lang.String.class), java.lang.String.class))); + if(value.isNotNullValue("data")) + object.setData(((com.tvd12.ezyfoxserver.binding.testing.EzyTestData)(arg0.unmarshal((java.lang.Object)value.getValue("data", com.tvd12.ezyfoxserver.binding.testing.EzyTestData.class), com.tvd12.ezyfoxserver.binding.testing.EzyTestData.class)))); + if(value.isNotNullValue("y")) + object.setY(((java.lang.Integer)(arg0.unmarshal((java.lang.Object)value.getValue("y", int.class), int.class))).intValue()); + if(value.isNotNullValue("x")) + object.setX(((java.lang.Integer)(arg0.unmarshal((java.lang.Object)value.getValue("x", int.class), int.class))).intValue()); + if(value.isNotNullValue("localDateTime")) + object.setLocalDateTime(((java.time.LocalDateTime)(arg0.unmarshal((java.lang.Object)value.getValue("localDateTime", java.time.LocalDateTime.class), java.time.LocalDateTime.class)))); + if(value.isNotNullValue("date")) + object.setDate(((java.util.Date)(arg0.unmarshal((java.lang.Object)value.getValue("date", java.util.Date.class), java.util.Date.class)))); + if(value.isNotNullValue("point")) + object.setPoint(((com.tvd12.ezyfoxserver.binding.testing.Point)(arg0.unmarshal((java.lang.Object)value.getValue("point", com.tvd12.ezyfoxserver.binding.testing.Point.class), com.tvd12.ezyfoxserver.binding.testing.Point.class)))); + if(value.isNotNullValue("clazz")) + object.setClazz(((java.lang.Class)(arg0.unmarshal((java.lang.Object)value.getValue("clazz", java.lang.Class.class), java.lang.Class.class)))); + if(value.isNotNullValue("3")) + object.setZ(((java.lang.Integer)(arg0.unmarshal((java.lang.Object)value.getValue("3", int.class), int.class))).intValue()); + if(value.isNotNullValue("localDate")) + object.setLocalDate(((java.time.LocalDate)(arg0.unmarshal((java.lang.Object)value.getValue("localDate", java.time.LocalDate.class), java.time.LocalDate.class)))); + if(value.isNotNullValue("data1")) + object.setData1(((com.tvd12.ezyfoxserver.binding.testing.EzyTestData1)(arg0.unmarshal(com.tvd12.ezyfoxserver.binding.testing.TestData1ReaderImpl.class, (java.lang.Object)value.getValue("data1", com.tvd12.ezyfoxserver.binding.testing.EzyTestData1.class))))); + return object; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA.java new file mode 100644 index 00000000..15f8ec0c --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding +public class ClassA { + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + private String ignore1; + + @SuppressWarnings("rawtypes") + private Map ignore2; + + private String null1; + + private String a = "1"; + private String b = "2"; + private String c = "3"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String d = "4"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String e = "5"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String f = "6"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA2.java new file mode 100644 index 00000000..5250d549 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA2.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIndex; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding(accessType = EzyAccessType.NONE) +public class ClassA2 { + + @EzyIndex(0) + private String a = "1"; + + @EzyIndex(1) + private String b = "2"; + + @EzyIndex(2) + private String c = "3"; + + private String d = "4"; + + @EzyIndex(5) + private String f = "5"; + + @EzyIndex(6) + private List g = Lists.newArrayList(1, 2, 3, 4, 5); + + @EzyIndex(7) + private List h = Lists.newArrayList(1, 2, 3, 4, 5); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA3.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA3.java new file mode 100644 index 00000000..d65adc04 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA3.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIndex; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding(indexes = {"a", "d", "z1", "f", "g", "h", "z2"}, accessType = EzyAccessType.NONE) +public class ClassA3 { + + @EzyIndex(0) + private String a = "1"; + + @EzyIndex(1) + private String b = "2"; + + @EzyIndex(2) + private String c = "3"; + + private String d = "4"; + + @EzyIndex(5) + private String f = "5"; + + @EzyIndex(6) + private List g = Lists.newArrayList(1, 2, 3, 4, 5); + + @EzyIndex(7) + private List h = Lists.newArrayList(1, 2, 3, 4, 5); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA4.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA4.java new file mode 100644 index 00000000..baf5c3eb --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA4.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIndex; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding(indexes = {"a", "d", "z1", "f", "g", "h", "z2", "i"}, accessType = EzyAccessType.NONE) +public class ClassA4 { + + @EzyIndex(0) + private String a = "1"; + + @EzyIndex(1) + private String b = "2"; + + @EzyIndex(2) + private String c = "3"; + + private String d = "4"; + + @EzyIndex(5) + private String f = "5"; + + @EzyIndex(6) + private List g = Lists.newArrayList(1, 2, 3, 4, 5); + + @EzyIndex(7) + private List h = Lists.newArrayList(1, 2, 3, 4, 5); + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyIndex(8) + public List i = Lists.newArrayList(1, 2, 3); + + @EzyIndex(9) + public void setJ(String a, String b) { + } + + @EzyIndex(9) + public void getJ() { + } + + @EzyIndex(10) + public void setK(String k) { + + } + + @EzyIndex(11) + public String getK() { + return "k"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA5.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA5.java new file mode 100644 index 00000000..d4dcc37f --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA5.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; + +public class ClassA5 { + + public List getA() { + return Lists.newArrayList(1, 2, 3); + } + + public void setA(List a) { + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA6.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA6.java new file mode 100644 index 00000000..d4c4bc18 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA6.java @@ -0,0 +1,81 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIndex; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding(accessType = EzyAccessType.NONE) +public class ClassA6 { + + @EzyIndex(0) + private String a = "1"; + + @EzyIndex(1) + private String b = "2"; + + @EzyIndex(2) + private String c = "3"; + + private String d = "4"; + + @EzyIndex(5) + private String f = "5"; + + @EzyIndex(6) + private List g = Lists.newArrayList(1, 2, 3, 4, 5); + + @EzyIndex(7) + private List h = Lists.newArrayList(1, 2, 3, 4, 5); + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyIndex(8) + public List i = Lists.newArrayList(1, 2, 3); + + @EzyIndex(9) + public void setJ(String a, String b) { + } + + @EzyIndex(9) + public void getJ() { + } + + @EzyIndex(10) + public void setK(String k) { + + } + + @EzyIndex(11) + public String getK() { + return "k"; + } + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyIndex(12) + private String m = "m"; + + @EzyIndex(13) + public void setO(List o) { + + } + + @EzyIndex(13) + public List getO() { + return Lists.newArrayList(1, 2, 3); + } + + @EzyIndex(20) + private List p = Lists.newArrayList(1, 2, 3); +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA7.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA7.java new file mode 100644 index 00000000..a5d47ded --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassA7.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +@EzyArrayBinding(accessType = EzyAccessType.DECLARED_ELEMENTS) +public class ClassA7 extends ClassA6 { + + protected String a61 = "a61"; + protected String a62 = "a62"; + public String a63 = "a63"; + protected List a64 = Lists.newArrayList(1, 2, 3); + + public String getA61() { + return a61; + } + + public void setA61(String a61) { + this.a61 = a61; + } + + public List getA64() { + return a64; + } + + public void setA64(List a64) { + this.a64 = a64; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassB.java new file mode 100644 index 00000000..12eb087e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassB.java @@ -0,0 +1,60 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@EzyArrayBinding(indexes = { + "ignore1", "null1", "a", "b", "c", "d", "e", "f", + "method1", "method2", "map" +}) +@ToString +public class ClassB { + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + private String ignore1; + + private String null1; + + private String a = "1"; + private String b = "2"; + private String c = "3"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String d = "4"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String e = "5"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + public String f = "6"; + + private Map map = newMap(); + + protected String getMethod1() { + return "dung"; + } + + public String getMethod2() { + return "dung"; + } + + protected Map newMap() { + Map map = new HashMap<>(); + map.put("hello", "world"); + return map; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassC.java new file mode 100644 index 00000000..54199ade --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/ClassC.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@EzyArrayBinding(indexes = {"map1", "list1", "map2", "list2", "longs1", "classAs1"}) +@ToString +public class ClassC { + private Map map1 = newMap1(); + private List list1 = Lists.newArrayList("a", "b", "c"); + private Map map2 = newMap2(); + private List list2 = Lists.newArrayList(new ClassA()); + private Long[] longs1 = new Long[] {10L, 11L, 12L}; + private ClassA[] classAs1 = new ClassA[] {new ClassA()}; + + protected Map newMap1() { + Map map = new HashMap<>(); + map.put("hello", "world"); + return map; + } + + protected Map newMap2() { + Map map = new HashMap<>(); + map.put("value", new ClassA()); + return map; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1.java new file mode 100644 index 00000000..da9d98c5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyArrayWriterBuilder.setDebug(true); + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA()); + System.out.println(array); + + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + EzyArrayReaderBuilder.setDebug(true); + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA.class)); + EzyReader reader = readerBuilder.build(); + ClassA classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_1.java new file mode 100644 index 00000000..558f177d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_1.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_1 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyArrayWriterBuilder.setDebug(true); + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA2.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA2()); + System.out.println(array); + + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + EzyArrayReaderBuilder.setDebug(true); + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA2.class)); + EzyReader reader = readerBuilder.build(); + ClassA2 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_2.java new file mode 100644 index 00000000..4c8fb859 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_2.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_2 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA3.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA3()); + System.out.println(array); + + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA3.class)); + EzyReader reader = readerBuilder.build(); + ClassA3 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_3.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_3.java new file mode 100644 index 00000000..1cc239b5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_3.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_3 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA4.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA4()); + System.out.println(array); + + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA4.class)); + EzyReader reader = readerBuilder.build(); + ClassA4 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_4.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_4.java new file mode 100644 index 00000000..c72cf7d6 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_4.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_4 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA5.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA5()); + System.out.println(array); + + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA5.class)); + EzyReader reader = readerBuilder.build(); + ClassA5 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_5.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_5.java new file mode 100644 index 00000000..73732404 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_5.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_5 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA6.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA6()); + System.out.println(array); + + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA6.class)); + EzyReader reader = readerBuilder.build(); + ClassA6 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_6.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_6.java new file mode 100644 index 00000000..725342ab --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample1_6.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample1_6 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyArrayWriterBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyArrayWriterBuilder writerBuilder + = new EzyArrayWriterBuilder(new EzyClass(ClassA7.class)); + EzyWriter writer = writerBuilder.build(); + EzyArray array = writer.write(marshaller, new ClassA7()); + System.out.println(array); + + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassA7.class)); + EzyReader reader = readerBuilder.build(); + ClassA7 classA = reader.read(unmarshaller, array); + System.out.println(classA); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2.java new file mode 100644 index 00000000..f5f0289d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyArrayWriterBuilderExample2 { + + @Test + @SuppressWarnings("unchecked") + public void test() throws Exception { + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyArrayWriterBuilder.setDebug(true); + EzyArrayWriterBuilder builder + = new EzyArrayWriterBuilder(new EzyClass(ClassB.class)); + EzyWriter writer = builder.build(); + EzyArray array = writer.write(marshaller, new ClassB()); + System.out.println(array); + + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + EzyArrayReaderBuilder.setDebug(true); + EzyArrayReaderBuilder readerBuilder + = new EzyArrayReaderBuilder(new EzyClass(ClassB.class)); + EzyReader reader = readerBuilder.build(); + ClassB classB = reader.read(unmarshaller, array); + System.out.println(classB); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2_1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2_1.java new file mode 100644 index 00000000..dfd52e42 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample2_1.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyArrayWriterBuilderExample2_1 { + + @Test + public void test() throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.arraybinding") + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyArrayWriterBuilder.setDebug(true); + EzyArray array = marshaller.marshal(new ClassC()); + System.out.println(array); + + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyArrayReaderBuilder.setDebug(true); + ClassC classC = unmarshaller.unmarshal(array, ClassC.class); + System.out.println(classC); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample3.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample3.java new file mode 100644 index 00000000..89b2602e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/arraybinding/EzyArrayWriterBuilderExample3.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.binding.testing.arraybinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyArrayWriterBuilderExample3 { + + @Test + public void test() throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.arraybinding") + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyArrayWriterBuilder.setDebug(true); + EzyArray array = marshaller.marshal( new ClassB()); + System.out.println(array); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding1.java new file mode 100644 index 00000000..d132c280 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding1.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception1; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; + +public class Exception1Binding1 { + + public static void main(String[] args) throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(Exception1ClassA.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + marshaller.marshal(new Exception1ClassA()); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding2.java new file mode 100644 index 00000000..8a867e64 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1Binding2.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception1; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +public class Exception1Binding2 extends EzyEntityBuilders { + + public static void main(String[] args) throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(Exception1ClassB.class) + .build(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + unmarshaller.unmarshal( + EzyEntityFactory.create(EzyObjectBuilder.class) + .append("value", "abc") + .build(), + Exception1ClassB.class); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassA.java new file mode 100644 index 00000000..97b86a70 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassA.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +@EzyObjectBinding +public class Exception1ClassA { + + public String getValue() { + throw new IllegalArgumentException(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassB.java new file mode 100644 index 00000000..b66d0ec0 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception1/Exception1ClassB.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +@EzyObjectBinding +public class Exception1ClassB { + + public String setValue(String value) { + throw new IllegalArgumentException(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding1.java new file mode 100644 index 00000000..7966ea8a --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding1.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception2; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; + +public class Exception2Binding1 { + + public static void main(String[] args) throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(Exception2ClassA.class) + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + marshaller.marshal(new Exception2ClassA()); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding2.java new file mode 100644 index 00000000..3f8a6f1f --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2Binding2.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception2; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +public class Exception2Binding2 extends EzyEntityBuilders { + + public static void main(String[] args) throws Exception { + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(Exception2ClassB.class) + .build(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + Exception2ClassB answer = unmarshaller.unmarshal( + EzyEntityFactory.create(EzyObjectBuilder.class) + .append("value", "abc") + .build(), + Exception2ClassB.class); + System.out.println(answer); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassA.java new file mode 100644 index 00000000..f153fc1d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassA.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception2; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding +public class Exception2ClassA { + + @SuppressWarnings("rawtypes") + private Map map = new HashMap<>(); + + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassB.java new file mode 100644 index 00000000..5d9aed64 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/exception2/Exception2ClassB.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.binding.testing.exception2; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +@EzyObjectBinding +public class Exception2ClassB { + + @SuppressWarnings("rawtypes") + public Map map = new HashMap<>(); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/BindingTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/BindingTest.java new file mode 100644 index 00000000..0e344908 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/BindingTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.test.base.BaseTest; + +public class BindingTest extends BaseTest { + + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.objectbinding") + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + + EzyObject object = marshaller.marshal(new ClassF()); + System.out.println(object); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassA.java new file mode 100644 index 00000000..1bcb2718 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassA.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding(accessType = EzyAccessType.NONE) +public class ClassA { + + @EzyValue("1") + private String a = "1"; + + @EzyValue("2") + private String b = "2"; + + @EzyValue("3") + private List c = Lists.newArrayList(1, 2, 3); + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyValue("4") + private String d = "4"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyValue("5") + private String e = "5"; + + @Setter(AccessLevel.NONE) + @Getter(AccessLevel.NONE) + @EzyValue("9") + public List i = Lists.newArrayList(1, 2, 3); + + @EzyValue("6") + public void getF() { + } + + @EzyValue("6") + public void setF(String a, String b) { + + } + + @EzyValue("7") + protected String getG() { + return "g"; + } + + @EzyValue("8") + public List getH() { + return Lists.newArrayList(1, 2, 3); + } + + @EzyValue("8") + public void setH(List h) { + + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassB.java new file mode 100644 index 00000000..3a5c01a5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassB.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyIgnore; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +@EzyObjectBinding(accessType = EzyAccessType.ALL) +public class ClassB { + + private List a = Lists.newArrayList(1, 2, 3); + + public List getA() { + return a; + } + + public void setA(List a) { + this.a = a; + } + + public List getB() { + return Lists.newArrayList(1, 2, 3); + } + + public void setB(List b) { + + } + + @EzyIgnore + public void setC(String c) { + + } + + @EzyIgnore + public String getC() { + return "c"; + } + + protected void setD(String d) { + } + + protected String getD() { + return "d"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassC.java new file mode 100644 index 00000000..b53b4cc7 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassC.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding(accessType = EzyAccessType.DECLARED_ELEMENTS) +public class ClassC extends ClassA { + + private String a1 = "1"; + private String b1 = "2"; + private String c1 = "3"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassD.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassD.java new file mode 100644 index 00000000..eb803b08 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassD.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding(accessType = EzyAccessType.DECLARED_FIELDS) +public class ClassD extends ClassA { + + private String a1 = "1"; + private String b1 = "2"; + private String c1 = "3"; + + public void setD1(String d1) { + } + + public String getD1() { + return "d1"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassE.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassE.java new file mode 100644 index 00000000..f550a591 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassE.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding(accessType = EzyAccessType.DECLARED_METHODS) +public class ClassE extends ClassA { + + private String a1 = "1"; + private String b1 = "2"; + private String c1 = "3"; + + public void setD1(String d1) { + } + + public String getD1() { + return "d1"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassF.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassF.java new file mode 100644 index 00000000..c24f4b42 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/ClassF.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.binding.EzyAccessType; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriter; +import com.tvd12.ezyfoxserver.binding.template.EzyMapArrayWriter; +import com.tvd12.ezyfoxserver.binding.template.EzyMapObjectWriter; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding(accessType = EzyAccessType.DECLARED_METHODS) +public class ClassF extends ClassA { + + private String a1 = "1"; + private String b1 = "2"; + private String c1 = "3"; + + @EzyWriter(EzyMapObjectWriter.class) + private Map map = defaultMap(); + + @EzyWriter(EzyMapArrayWriter.class) + private Map map2 = defaultMap(); + + public void setD1(String d1) { + } + + public String getD1() { + return "d1"; + } + + private Map defaultMap() { + Map map = new HashMap<>(); + map.put(new ClassA(), new ClassB()); + map.put("hello", "world"); + map.put("null", null); + return map; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding1Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding1Test.java new file mode 100644 index 00000000..e10fefa7 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding1Test.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyObjectBinding1Test { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyObjectWriterBuilder writerBuilder + = new EzyObjectWriterBuilder(new EzyClass(ClassA.class)); + EzyWriter writer = writerBuilder.build(); + EzyObject object = writer.write(marshaller, new ClassA()); + System.out.println(object); + + EzyObjectReaderBuilder readerBuilder + = new EzyObjectReaderBuilder(new EzyClass(ClassA.class)); + EzyReader reader = readerBuilder.build(); + ClassA classA = reader.read(unmarshaller, object); + System.out.println(classA); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding2Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding2Test.java new file mode 100644 index 00000000..b7d16a6b --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding2Test.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyObjectBinding2Test { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyObjectWriterBuilder writerBuilder + = new EzyObjectWriterBuilder(new EzyClass(ClassB.class)); + EzyWriter writer = writerBuilder.build(); + EzyObject object = writer.write(marshaller, new ClassB()); + System.out.println(object); + + EzyObjectReaderBuilder readerBuilder + = new EzyObjectReaderBuilder(new EzyClass(ClassB.class)); + EzyReader reader = readerBuilder.build(); + ClassB ClassB = reader.read(unmarshaller, object); + System.out.println(ClassB); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding3Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding3Test.java new file mode 100644 index 00000000..c640fe14 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding3Test.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyObjectBinding3Test { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyObjectWriterBuilder writerBuilder + = new EzyObjectWriterBuilder(new EzyClass(ClassC.class)); + EzyWriter writer = writerBuilder.build(); + EzyObject object = writer.write(marshaller, new ClassC()); + System.out.println(object); + + EzyObjectReaderBuilder readerBuilder + = new EzyObjectReaderBuilder(new EzyClass(ClassC.class)); + EzyReader reader = readerBuilder.build(); + ClassC ClassC = reader.read(unmarshaller, object); + System.out.println(ClassC); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding4Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding4Test.java new file mode 100644 index 00000000..897b70a4 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding4Test.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyObjectBinding4Test { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyObjectWriterBuilder writerBuilder + = new EzyObjectWriterBuilder(new EzyClass(ClassD.class)); + EzyWriter writer = writerBuilder.build(); + EzyObject object = writer.write(marshaller, new ClassD()); + System.out.println(object); + + EzyObjectReaderBuilder readerBuilder + = new EzyObjectReaderBuilder(new EzyClass(ClassD.class)); + EzyReader reader = readerBuilder.build(); + ClassD ClassD = reader.read(unmarshaller, object); + System.out.println(ClassD); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding5Test.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding5Test.java new file mode 100644 index 00000000..1c2f7dec --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/objectbinding/EzyObjectBinding5Test.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.objectbinding; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyReader; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyWriter; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleMarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzyObjectBinding5Test { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzyObjectWriterBuilder.setDebug(true); + EzyObjectReaderBuilder.setDebug(true); + + EzyMarshaller marshaller = new EzySimpleMarshaller(); + EzyUnmarshaller unmarshaller = new EzySimpleUnmarshaller(); + + EzyObjectWriterBuilder writerBuilder + = new EzyObjectWriterBuilder(new EzyClass(ClassE.class)); + EzyWriter writer = writerBuilder.build(); + EzyObject object = writer.write(marshaller, new ClassE()); + System.out.println(object); + + EzyObjectReaderBuilder readerBuilder + = new EzyObjectReaderBuilder(new EzyClass(ClassE.class)); + EzyReader reader = readerBuilder.build(); + ClassE ClassE = reader.read(unmarshaller, object); + System.out.println(ClassE); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/BindingTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/BindingTest.java new file mode 100644 index 00000000..bb5c9818 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/BindingTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.testing.scan.pack1.ClassB; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.test.base.BaseTest; + +public class BindingTest extends BaseTest { + + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.scan.pack0") + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + + EzyObject object = marshaller.marshal(new ClassB()); + System.out.println(object); + ClassB classB = unmarshaller.unmarshal(object, ClassB.class); + System.out.println(classB); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/ClassA.java new file mode 100644 index 00000000..cda8d6d5 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/ClassA.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack0; + +public class ClassA { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration0.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration0.java new file mode 100644 index 00000000..70de437a --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration0.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack0; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.binding.annotation.EzyPackagesScan; + +@EzyConfiguration +@EzyPackagesScan({"com.tvd12.ezyfoxserver.binding.testing.scan.pack1"}) +public class Configuration0 { +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration1.java new file mode 100644 index 00000000..1fac2560 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration1.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack0; + +import com.tvd12.ezyfoxserver.binding.EzyBindingConfig; +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyBindingContextAware; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.binding.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.binding.annotation.EzyPackagesScan; +import com.tvd12.ezyfoxserver.binding.testing.objectbinding.ClassD; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +import lombok.Setter; + +@EzyConfiguration +@EzyPackagesScan({"com.tvd12.ezyfoxserver.binding.testing.scan.pack1"}) +public class Configuration1 implements EzyBindingContextAware, EzyBindingConfig { + + @Setter + private EzyBindingContext context; + + @Override + public void config() { + context.bindTemplate(ClassD.class, new EzyUnwrapper() { + @Override + public void unwrap(EzyUnmarshaller unmarshaller, EzyObject input, ClassD output) { + } + }); + } + + + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration2.java new file mode 100644 index 00000000..5c00c8f3 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack0/Configuration2.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack0; + +import com.tvd12.ezyfoxserver.binding.EzyBindingConfig; +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyBindingContextAware; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyTemplate; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyConfiguration; +import com.tvd12.ezyfoxserver.binding.annotation.EzyPackagesScan; +import com.tvd12.ezyfoxserver.binding.testing.scan.pack1.ClassC; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; + +import lombok.Setter; + +@EzyConfiguration +@EzyPackagesScan({"com.tvd12.ezyfoxserver.binding.testing.scan.pack1"}) +public class Configuration2 implements EzyBindingContextAware, EzyBindingConfig { + + @Setter + private EzyBindingContext context; + + @Override + public void config() { + context.addTemplate(new EzyTemplate() { + @Override + public ClassA read(EzyUnmarshaller unmarshaller, EzyArray value) { + return new ClassA(); + } + + @Override + public EzyArray write(EzyMarshaller marshaller, ClassA object) { + return EzyEntityFactory.create(EzyArrayBuilder.class).build(); + } + }); + + context.bindTemplate(ClassA.class, new EzyTemplate() { + @Override + public ClassA read(EzyUnmarshaller unmarshaller, EzyArray value) { + return new ClassA(); + } + + @Override + public EzyArray write(EzyMarshaller marshaller, ClassA object) { + return EzyEntityFactory.create(EzyArrayBuilder.class).build(); + } + }); + + context.addTemplate(new Object()); + context.bindTemplate(ClassC.class, new Object()); + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassB.java new file mode 100644 index 00000000..61b47879 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassB.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +@EzyObjectBinding +public class ClassB { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassC.java new file mode 100644 index 00000000..6b64c511 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassC.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack1; + +public class ClassC { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassD.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassD.java new file mode 100644 index 00000000..e2742201 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan/pack1/ClassD.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan.pack1; + +public class ClassD { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/ClassA.java new file mode 100644 index 00000000..af740231 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/ClassA.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import java.util.List; + +import com.google.common.collect.Lists; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@lombok.ToString +public class ClassA { + + private T t = newT(); + + private List classB = Lists.newArrayList(new ClassB(), new ClassB()); + + @SuppressWarnings("unchecked") + protected T newT() { + return (T)new Integer(10); + } + + @Getter + @Setter + @ToString + public static class ClassB { + private String a = "a"; + private String b = "b"; + private String c = "c"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Data.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Data.java new file mode 100644 index 00000000..c06e026e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Data.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.ToString; + +@ToString +@EzyObjectBinding +@EzyArrayBinding +public class Data { + + public String data1 = "data1"; + public String data2 = "data2"; + public String data3 = "data2"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA.java new file mode 100644 index 00000000..732906b7 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReader; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriter; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString(callSuper = true) +@EzyObjectBinding +public class Scan1ClassA extends Scan1ClassA1 { + private String a = "1"; + private String b = "1"; + private String c = "1"; + private int d = 10; + + private Scan1ClassB classB = new Scan1ClassB(); + + @EzyWriter(Scan1ClassCWriterImpl.class) + @EzyReader(Scan1ClassCReaderImpl.class) + private Scan1ClassC classC = new Scan1ClassC(); + + private Map map = newMap(); + + private List list = Lists.newArrayList("a", "b", "c"); + + private List dataList1 = Lists.newArrayList(new Data(), new Data()); + + private Data[] dataArray1 = new Data[] {new Data(), new Data()}; + + protected Map newMap() { + Map map = new HashMap<>(); + map.put("hello", "world"); + return map; + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA1.java new file mode 100644 index 00000000..a9bb1fd1 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassA1.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class Scan1ClassA1 { + + protected String hung = "dep trai"; + + @EzyValue("hll") + public String getHello() { + return "world"; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassB.java new file mode 100644 index 00000000..c8739cf6 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassB.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +@EzyObjectBinding +public class Scan1ClassB { + + public String one = "a"; + public String two = "b"; + public String three = "c"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassC.java new file mode 100644 index 00000000..da846371 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassC.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +public class Scan1ClassC { + + public String x = "x"; + public String y = "y"; + public String z = "z"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCReaderImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCReaderImpl.java new file mode 100644 index 00000000..7ba74916 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCReaderImpl.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReaderImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractReader; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +@EzyReaderImpl +public class Scan1ClassCReaderImpl + extends EzyAbstractReader { + + @Override + public Scan1ClassC read(EzyUnmarshaller unmarshaller, EzyArray array) { + Scan1ClassC answer = new Scan1ClassC(); + answer.setX(array.get(0, String.class)); + answer.setY(array.get(1, String.class)); + answer.setZ(array.get(2, String.class)); + return answer; + } + + public EzyArray write(EzyMarshaller marshaller, Scan1ClassC object) { + return newArrayBuilder() + .append(object.getX()) + .append(object.getY()) + .append(object.getZ()) + .build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCWriterImpl.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCWriterImpl.java new file mode 100644 index 00000000..a9409089 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1ClassCWriterImpl.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriterImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractWriter; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +@EzyWriterImpl +public class Scan1ClassCWriterImpl + extends EzyAbstractWriter { + + public EzyArray write(EzyMarshaller marshaller, Scan1ClassC object) { + return newArrayBuilder() + .append(object.getX()) + .append(object.getY()) + .append(object.getZ()) + .build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example1.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example1.java new file mode 100644 index 00000000..78d351d0 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example1.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class Scan1Example1 { + + public static void main(String[] args) throws Exception { + new Scan1Example1().test(); + } + + @Test + public void test() { + EzyObjectReaderBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + EzyObjectWriterBuilder.setDebug(true); + EzyArrayWriterBuilder.setDebug(true); + + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.scan1") + .addTemplate(new Scan1ClassCWriterImpl()) + .addTemplate(new Scan1ClassCReaderImpl()) + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + EzyObject outObject = marshaller.marshal(new Scan1ClassA()); + System.out.println(outObject); + outObject.put("hung", "xau trai"); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + Scan1ClassA outEntity = unmarshaller.unmarshal(outObject, Scan1ClassA.class); + System.out.println(outEntity); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example2.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example2.java new file mode 100644 index 00000000..5c47a66a --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan1/Scan1Example2.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan1; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectReaderBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectWriterBuilder; +import com.tvd12.ezyfoxserver.binding.impl.EzySimpleBindingContext; +import com.tvd12.ezyfoxserver.binding.testing.scan1.ClassA.ClassB; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class Scan1Example2 { + + public static void main(String[] args) throws Exception { + new Scan1Example2().test(); + } + + @SuppressWarnings("rawtypes") + public void test() { + + EzyObjectReaderBuilder.setDebug(true); + EzyArrayReaderBuilder.setDebug(true); + EzyObjectWriterBuilder.setDebug(true); + EzyArrayWriterBuilder.setDebug(true); + + EzySimpleBindingContext context = EzySimpleBindingContext.builder() + .addClass(ClassA.class) + .addClass(ClassB.class) + .build(); + + EzyMarshaller marshaller = context.newMarshaller(); + EzyObject outObject = marshaller.marshal(new ClassA()); + System.out.println(outObject); + outObject.put("hung", "xau trai"); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + ClassA outEntity = unmarshaller.unmarshal(outObject, ClassA.class); + System.out.println(outEntity); + } +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2A.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2A.java new file mode 100644 index 00000000..c603a5b1 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2A.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding +public class Scan2A { + + private String a = "1"; + private boolean b = true; + private byte c = 1; + private char d = 'a'; + private double e = 2D; + private float f = 3F; + private long g = 4L; + private short h = 5; + + + public void setObject(Scan2Object object) { + + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2B.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2B.java new file mode 100644 index 00000000..3ca3b0e2 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2B.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyArrayBinding +public class Scan2B { + + private String a = "1"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2C.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2C.java new file mode 100644 index 00000000..d8a8600d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2C.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyIgnore; +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReader; +import com.tvd12.ezyfoxserver.binding.annotation.EzyValue; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriter; + +import lombok.Getter; +import lombok.Setter; + +@EzyObjectBinding +public class Scan2C { + + @EzyIgnore + @Getter + @Setter + private String a; + + @EzyValue("b") + @Setter + private String b; + + @EzyValue("") + @Setter + @Getter + private String c; + + @Getter + @EzyReader(Scan2ObjectReader.class) + private Scan2Object object; + + @EzyIgnore + public String getB() { + return "b"; + } + + @EzyWriter(Scan2ObjectWriter.class) + public void setObject(Scan2Object object) { + this.object = object; + } + + @EzyWriter(Scan2ObjectWriter.class) + public Scan2Object getObject1() { + return new Scan2Object(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2Object.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2Object.java new file mode 100644 index 00000000..d0a6ac32 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2Object.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +public class Scan2Object { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectReader.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectReader.java new file mode 100644 index 00000000..3281b3aa --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectReader.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyReaderImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractReader; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +@EzyReaderImpl +public class Scan2ObjectReader extends EzyAbstractReader { + + @Override + public Scan2Object read(EzyUnmarshaller unmarshaller, EzyObject value) { + Scan2Object object = new Scan2Object(); + return object; + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectWriter.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectWriter.java new file mode 100644 index 00000000..b04bf705 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan2/Scan2ObjectWriter.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan2; + +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.annotation.EzyWriterImpl; +import com.tvd12.ezyfoxserver.binding.impl.EzyAbstractWriter; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +@EzyWriterImpl +public class Scan2ObjectWriter extends EzyAbstractWriter { + + @Override + public EzyObject write(EzyMarshaller marshaller, Scan2Object object) { + EzyObjectBuilder builder = newObjectBuilder(); + return builder.build(); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3A.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3A.java new file mode 100644 index 00000000..1cf1da1d --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3A.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan3; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyObjectBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyObjectBinding +public class Scan3A { + + private String a = "1"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3Array.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3Array.java new file mode 100644 index 00000000..4541f26e --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3Array.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan3; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +@EzyArrayBinding +public class Scan3Array { + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3B.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3B.java new file mode 100644 index 00000000..ef49f2f4 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3B.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan3; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@EzyArrayBinding +public class Scan3B { + + private String a = "1"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3C.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3C.java new file mode 100644 index 00000000..bc0556ca --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/scan3/Scan3C.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.binding.testing.scan3; + +public class Scan3C { + + public String a = "a"; + public String b = "b"; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/BindingTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/BindingTest.java new file mode 100644 index 00000000..725ce9ec --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/BindingTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyMarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.test.base.BaseTest; + +public class BindingTest extends BaseTest { + + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.testing1") + .build(); + EzyMarshaller marshaller = context.newMarshaller(); + EzyArray array = marshaller.marshal(new ClassA()); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + InterfaceA interfaceA = unmarshaller.unmarshal(array, InterfaceA.class); + System.out.println(interfaceA); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassA.java new file mode 100644 index 00000000..88f0db34 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassA.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; + +@EzyArrayBinding(subTypes = true) +public class ClassA implements InterfaceA { + + @Getter + @Setter + private String name; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassB.java new file mode 100644 index 00000000..0036c55c --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassB.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; + +@EzyArrayBinding(subTypes = true, subTypeClasses = {InterfaceB.class}) +public class ClassB implements InterfaceB { + + @Setter + @Getter + private String name; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassC.java new file mode 100644 index 00000000..fef34c4a --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/ClassC.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; + +@EzyArrayBinding +public class ClassC implements InterfaceC { + + @Setter + @Getter + private String name; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceA.java new file mode 100644 index 00000000..ffe1f870 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceA.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +public interface InterfaceA { + + String getName(); + + void setName(String name); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceB.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceB.java new file mode 100644 index 00000000..ff5e4c72 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceB.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +public interface InterfaceB { + + String getName(); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceC.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceC.java new file mode 100644 index 00000000..4c1fbc97 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/testing1/InterfaceC.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.binding.testing.testing1; + +public interface InterfaceC { + + String getName(); + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassA.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassA.java new file mode 100644 index 00000000..dfa4b42c --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassA.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.binding.testing.unwrapper; + +import com.tvd12.ezyfoxserver.binding.annotation.EzyArrayBinding; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@EzyArrayBinding +public class ClassA { + + private String a; + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassAUnwrapper.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassAUnwrapper.java new file mode 100644 index 00000000..3cabee52 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/ClassAUnwrapper.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.binding.testing.unwrapper; + +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +@SuppressWarnings("rawtypes") +public class ClassAUnwrapper implements EzyUnwrapper { + + @Override + public void unwrap(EzyUnmarshaller arg0, Object arg1, Object arg2) { + EzyArray value = (EzyArray)arg1; + ClassA object = (ClassA)arg2; + object.setA(value.get(0)); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyArrayUnwrapperBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyArrayUnwrapperBuilderTest.java new file mode 100644 index 00000000..0a49fef2 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyArrayUnwrapperBuilderTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.binding.testing.unwrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.binding.impl.EzyArrayUnwrapperBuilder; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzyArrayUnwrapperBuilderTest extends BaseTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .build(); + EzyArrayUnwrapperBuilder.setDebug(true); + EzyArrayUnwrapperBuilder builder = + new EzyArrayUnwrapperBuilder(new EzyClass(ClassA.class)); + EzyArray array = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("hehe") + .build(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyUnwrapper unwrapper = builder.build(); + ClassA classA = new ClassA(); + unwrapper.unwrap(unmarshaller, array, classA); + System.out.println(classA); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyObjectUnwrapperBuilderTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyObjectUnwrapperBuilderTest.java new file mode 100644 index 00000000..8bfbbc93 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyObjectUnwrapperBuilderTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.binding.testing.unwrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.EzyUnwrapper; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectUnwrapperBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.test.base.BaseTest; + +public class EzyObjectUnwrapperBuilderTest extends BaseTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .build(); + EzyObjectUnwrapperBuilder.setDebug(true); + EzyObjectUnwrapperBuilder builder = + new EzyObjectUnwrapperBuilder(new EzyClass(ClassA.class)); + EzyObject object = EzyEntityFactory.create(EzyObjectBuilder.class) + .append("a", "hi!") + .build(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + EzyUnwrapper unwrapper = builder.build(); + ClassA classA = new ClassA(); + unwrapper.unwrap(unmarshaller, object, classA); + System.out.println(classA); + } + +} diff --git a/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyUnwrapperTest.java b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyUnwrapperTest.java new file mode 100644 index 00000000..db67bb88 --- /dev/null +++ b/ezyfox-server-binding/src/test/java/com/tvd12/ezyfoxserver/binding/testing/unwrapper/EzyUnwrapperTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.binding.testing.unwrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.binding.EzyBindingContext; +import com.tvd12.ezyfoxserver.binding.EzyUnmarshaller; +import com.tvd12.ezyfoxserver.binding.impl.EzyObjectUnwrapperBuilder; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyUnwrapperTest extends BaseTest { + + @Test + public void test() { + EzyBindingContext context = EzyBindingContext.builder() + .scan("com.tvd12.ezyfoxserver.binding.testing.unwrapper") + .build(); + EzyObjectUnwrapperBuilder.setDebug(true); + EzyArray array = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("hehe") + .build(); + EzyUnmarshaller unmarshaller = context.newUnmarshaller(); + ClassA classA = new ClassA(); + unmarshaller.unwrap(array, classA); + System.out.println(classA); + } + +} diff --git a/ezyfox-server-binding/src/test/resources/AllTests.tng.xml b/ezyfox-server-binding/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..e5a4ae98 --- /dev/null +++ b/ezyfox-server-binding/src/test/resources/AllTests.tng.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-binding/src/test/resources/logback.xml b/ezyfox-server-binding/src/test/resources/logback.xml new file mode 100644 index 00000000..efd85297 --- /dev/null +++ b/ezyfox-server-binding/src/test/resources/logback.xml @@ -0,0 +1,20 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-boot/pom.xml b/ezyfox-server-boot/pom.xml new file mode 100644 index 00000000..b0ce011e --- /dev/null +++ b/ezyfox-server-boot/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-boot + 1.0.0 + + ezyfox-server-boot + http://www.tvd12.com/java/projects/ezyfox-server + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-httpserver + ${ezy.httpserver.version} + + + + \ No newline at end of file diff --git a/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrapBuilder.java b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrapBuilder.java new file mode 100644 index 00000000..89259ccb --- /dev/null +++ b/ezyfox-server-boot/src/main/java/com/tvd12/ezyfoxserver/EzyHttpServerBootstrapBuilder.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.builder.EzyAbtractServerBootstrapBuilder; + +public abstract class EzyHttpServerBootstrapBuilder extends EzyAbtractServerBootstrapBuilder { + + @Override + protected EzyHttpBootstrap newHttpBottstrap() { + EzyComplexHttpBootstrap bootstrap = new EzyComplexHttpBootstrap(); + bootstrap.setServerContext(serverContext); + return bootstrap; + } + +} diff --git a/ezyfox-server-boot/src/test/resources/AllTests.tng.xml b/ezyfox-server-boot/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-boot/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-client/pom.xml b/ezyfox-server-client/pom.xml index e84954b2..7f5007cd 100644 --- a/ezyfox-server-client/pom.xml +++ b/ezyfox-server-client/pom.xml @@ -6,7 +6,7 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-client @@ -14,17 +14,22 @@ 1.0.0 ezyfox-server-client http://maven.apache.org + + + 1.0.0 + 1.0.0 + com.tvd12 ezyfox-server-netty - 1.0.0 + ${ezy.netty.version} com.tvd12 ezyfox-server-nettycodec - 1.0.0 + ${ezy.nettycodec.version} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClient.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClient.java index 32700803..b597ae9c 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClient.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClient.java @@ -1,26 +1,80 @@ package com.tvd12.ezyfoxserver.client; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; +import java.util.Set; -import lombok.Getter; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.controller.EzyClientAppController; +import com.tvd12.ezyfoxserver.client.listener.EzyClientAppResponseListener; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientAppControllers; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientAppResponseListeners; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientControllers; +import com.tvd12.ezyfoxserver.client.wrapper.impl.EzyClientAppControllersImpl; +import com.tvd12.ezyfoxserver.client.wrapper.impl.EzyClientAppResponseListenersImpl; +import com.tvd12.ezyfoxserver.client.wrapper.impl.EzyClientControllersImpl; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; public class EzyClient implements EzyDestroyable { - @Getter - protected EzyControllers controllers; + protected EzyClientControllers controllers = newControllers(); + protected EzyClientAppControllers appControllers = newAppControllers(); + protected EzyClientAppResponseListeners appResponseListeners = newAppResponseListeners(); + protected Set unloggableCommands = defaultUnloggableCommands(); - { - controllers = newControllers(); + @SuppressWarnings({ "unchecked" }) + public T getController(EzyConstant cmd) { + return (T)controllers.getController(cmd); } - protected EzyControllers newControllers() { - return EzyClientControllers.builder().build(); + public void addController(EzyConstant cmd, Object ctrl) { + controllers.addController(cmd, ctrl); + } + + @SuppressWarnings("rawtypes") + public EzyClientAppController getAppController(EzyConstant cmd) { + return appControllers.getController(cmd); + } + + @SuppressWarnings("rawtypes") + public void addAppController(EzyConstant cmd, EzyClientAppController ctrl) { + appControllers.addController(cmd, ctrl); + } + + @SuppressWarnings("rawtypes") + public EzyClientAppResponseListener getAppResponseListener(Object requestId) { + return appResponseListeners.getListener(requestId); + } + + @SuppressWarnings("rawtypes") + public void addClientAppResponseListener( + Object requestId, EzyClientAppResponseListener listener) { + appResponseListeners.addListener(requestId, listener); + } + + public Set getUnloggableCommands() { + return unloggableCommands; } @Override public void destroy() { - + controllers.destroy(); + controllers = null; + } + + protected EzyClientControllers newControllers() { + return EzyClientControllersImpl.builder().build(); + } + + protected EzyClientAppControllers newAppControllers() { + return EzyClientAppControllersImpl.builder().build(); + } + + protected EzyClientAppResponseListeners newAppResponseListeners() { + return EzyClientAppResponseListenersImpl.builder().build(); } + protected Set defaultUnloggableCommands() { + return Sets.newHashSet(EzyClientCommand.PING, EzyClientCommand.PONG); + } } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientBoostrap.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientBoostrap.java index 96ee7d0d..1b9dfbbc 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientBoostrap.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientBoostrap.java @@ -3,17 +3,24 @@ */ package com.tvd12.ezyfoxserver.client; +import java.net.ConnectException; import java.net.InetSocketAddress; +import java.net.NoRouteToHostException; +import java.net.SocketException; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.constants.EzyConnectionError; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.controller.EzyConnectFailureController; import com.tvd12.ezyfoxserver.client.handler.EzyClientHandler; -import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; -import com.tvd12.ezyfoxserver.client.serialize.iml.EzyRequestSerializerImpl; import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; -import com.tvd12.ezyfoxserver.codec.EzyCombinedCodec; import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; -import com.tvd12.ezyfoxserver.entity.EzyStartable; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.netty.codec.EzyCombinedCodec; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; @@ -31,36 +38,81 @@ * @author tavandung12 * */ -@Builder public class EzyClientBoostrap extends EzyLoggable implements EzyStartable, EzyDestroyable { protected int port; protected String host; - protected EzyClient client; protected EzyCodecCreator codecCreator; + protected EzyClientContext clientContext; @Override public void start() throws Exception { EventLoopGroup group = newLoopGroup(); try { + // new client bootstrap Bootstrap b = newBootstrap(group); - getLogger().info("client connecting..."); - ChannelFuture f = b.connect().sync(); - f.channel().closeFuture().addListener((future) -> - getLogger().info("channel future close") - ).sync(); + + getLogger().info("connecting to server ..."); + + // connect to server + ChannelFuture connectionFuture = b.connect(); + + // wait and listen connection + connectionFuture.syncUninterruptibly(); + + // process connection successful + if(connectionFuture.isSuccess()) + processConnectSuccess(connectionFuture); + } + catch(ConnectException e) { + processConnectFailure(EzyConnectionError.CONNECTION_REFUSED); + } + catch(NoRouteToHostException e) { + processConnectFailure(EzyConnectionError.NO_ROUTE_TO_HOST); } + catch(SocketException e) { + processConnectFailure(EzyConnectionError.NETWORK_UNREACHABLE); + } + catch(Exception e) { + throw e; + } + finally { - group.shutdownGracefully().addListener((future) -> - getLogger().info("event loop group shutdown") - ).sync(); + group.shutdownGracefully().addListener((future) -> { + getLogger().info("event loop group shutdown"); + }).sync(); } } - @Override - public void destroy() { + protected void processConnectFailure(EzyConstant error) { + getLogger().info("connect to server failed"); + + // notify to controller + notifyConnectionFailure(error); + + // destroy this boostrap + destroy(); + } + + protected void notifyConnectionFailure(EzyConstant error) { + EzyConnectFailureController ctrl = + getClient().getController(EzyClientCommand.CONNECT_FAILURE); + ctrl.handle(error); + } + + protected void processConnectSuccess(ChannelFuture connectFuture) throws Exception { + getLogger().info("connect to server successfully"); + + // get close future channel + ChannelFuture closeFuture = connectFuture.channel().closeFuture(); + + // wait and listen close future state + closeFuture.addListener((future) -> { + getLogger().info("channel future close"); + }) + .sync(); } protected Bootstrap newBootstrap(EventLoopGroup group) { @@ -72,26 +124,63 @@ protected Bootstrap newBootstrap(EventLoopGroup group) { } protected EventLoopGroup newLoopGroup() { - return new NioEventLoopGroup(39, EzyExecutors.newThreadFactory("clienteventloopgroup")); + return new NioEventLoopGroup(3, EzyExecutors.newThreadFactory("clienteventloopgroup")); } protected ChannelInitializer newChannelInitializer() { return ClientChannelInitializer.builder() .codecCreator(codecCreator) - .context(newContext()) + .context(clientContext) .build(); } - protected EzyClientContext newContext() { - EzySimpleClientContext ctx = new EzySimpleClientContext(); - ctx.setClient(client); - ctx.setProperty(EzyRequestSerializer.class, newRequestSerializer()); - ctx.setWorkerExecutor(EzyExecutors.newFixedThreadPool(39, "client-worker")); - return ctx; + protected EzyClient getClient() { + return clientContext.getClient(); } - protected EzyRequestSerializer newRequestSerializer() { - return EzyRequestSerializerImpl.builder().build(); + @Override + public void destroy() { + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected int port; + protected String host; + protected EzyCodecCreator codecCreator; + protected EzyClientContext clientContext; + + public Builder port(int port) { + this.port = port; + return this; + } + + public Builder host(String host) { + this.host = host; + return this; + } + + public Builder codecCreator(EzyCodecCreator codecCreator) { + this.codecCreator = codecCreator; + return this; + } + + public Builder clientContext(EzyClientContext clientContext) { + this.clientContext = clientContext; + return this; + } + + @Override + public EzyClientBoostrap build() { + EzyClientBoostrap answer = new EzyClientBoostrap(); + answer.host = host; + answer.port = port; + answer.codecCreator = codecCreator; + answer.clientContext = clientContext; + return answer; + } } } @@ -105,11 +194,11 @@ class ClientChannelInitializer extends ChannelInitializer { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); - ChannelOutboundHandler encoder = codecCreator.newEncoder(); - ChannelInboundHandlerAdapter decoder = codecCreator.newDecoder(); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); - pipeline.addLast(newDataHandler()); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); + ChannelOutboundHandler encoder = (ChannelOutboundHandler) codecCreator.newEncoder(); + ChannelInboundHandlerAdapter decoder = (ChannelInboundHandlerAdapter) codecCreator.newDecoder(65536); + pipeline.addLast("codec-1", new EzyCombinedCodec(decoder, encoder)); + pipeline.addLast("handler", newDataHandler()); + pipeline.addLast("codec-2", new EzyCombinedCodec(decoder, encoder)); } protected EzyClientHandler newDataHandler() { diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientContext.java deleted file mode 100644 index 3decfd92..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientContext.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.tvd12.ezyfoxserver.client; - -import com.tvd12.ezyfoxserver.context.EzyContext; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; - -public interface EzyClientContext extends EzyContext, EzyDestroyable { - - EzyClient getClient(); - -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientControllers.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientControllers.java deleted file mode 100644 index 68a00abc..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientControllers.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.tvd12.ezyfoxserver.client; - -import java.util.HashMap; -import java.util.Map; - -import com.tvd12.ezyfoxserver.client.controller.EzyAccessAppController; -import com.tvd12.ezyfoxserver.client.controller.EzyDisconnectController; -import com.tvd12.ezyfoxserver.client.controller.EzyHandShakeController; -import com.tvd12.ezyfoxserver.client.controller.EzyLoginController; -import com.tvd12.ezyfoxserver.constant.EzyCommand; -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.controller.EzyController; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyControllersImpl; - -public class EzyClientControllers extends EzyControllersImpl { - - protected EzyClientControllers(Builder builder) { - super(builder); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyControllersImpl.Builder { - - @SuppressWarnings("rawtypes") - @Override - protected Map newControllers() { - Map answer = new HashMap<>(); - answer.put(EzyCommand.HAND_SHAKE, new EzyHandShakeController()); - answer.put(EzyCommand.LOGIN, new EzyLoginController()); - answer.put(EzyCommand.ACCESS_APP, new EzyAccessAppController()); - answer.put(EzyCommand.DISCONNECT, new EzyDisconnectController()); - return answer; - } - - @Override - public EzyControllers build() { - return new EzyClientControllers(this); - } - } - -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientRunner.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientRunner.java deleted file mode 100644 index e058fbc0..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientRunner.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * - */ -package com.tvd12.ezyfoxserver.client; - -import com.tvd12.ezyfoxserver.codec.MsgPackCodecCreator; - -import lombok.AllArgsConstructor; - -/** - * @author tavandung12 - * - */ -@AllArgsConstructor -public class EzyClientRunner { - - public static void main(String[] args) throws Exception { - if (args.length != 2) - System.err.println(getErrorMessage()); - start(args[0], Integer.parseInt(args[1])); - } - - private static void start(String host, int port) { - try { - tryStart(host, port); - } - catch(Exception e) { - e.printStackTrace(); - } - } - - private static void tryStart(String host, int port) throws Exception { - EzyClientBoostrap.builder() - .client(new EzyClient()) - .codecCreator(new MsgPackCodecCreator()) - .host(host) - .port(port) - .build().start(); - } - - private static String getErrorMessage() { - return "Usage: " + EzyClientRunner.class.getSimpleName() + " "; - } - -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientStarter.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientStarter.java new file mode 100644 index 00000000..1b83c4ac --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzyClientStarter.java @@ -0,0 +1,100 @@ +package com.tvd12.ezyfoxserver.client; + +import java.util.concurrent.ExecutorService; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyClientStarter + extends EzyLoggable + implements EzyStartable { + + protected int port; + protected String host; + protected boolean fromMainThread; + protected EzyCodecCreator codecCreator; + protected EzyClientContext clientContext; + + protected final ExecutorService startService; + + public EzyClientStarter() { + startService = EzyExecutors.newSingleThreadExecutor("client-starter"); + Runtime.getRuntime().addShutdownHook(new Thread(() -> startService.shutdown())); + } + + public void start() throws Exception { + if(fromMainThread) + doStart(); + else + startService.submit(() -> EzyProcessor.processWithException(this::doStart)); + } + + public void doStart() throws Exception { + EzyClientBoostrap.builder() + .host(host) + .port(port) + .codecCreator(codecCreator) + .clientContext(clientContext) + .build() + .start(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected int port; + protected String host; + protected EzyCodecCreator codecCreator; + protected EzyClientContext clientContext; + protected boolean fromMainThread = true; + + public Builder host(String host) { + this.host = host; + return this; + } + + public Builder port(int port) { + this.port = port; + return this; + } + + public Builder fromMainThread(boolean fromMainThread) { + this.fromMainThread = fromMainThread; + return this; + } + + public Builder clientContext(EzyClientContext clientContext) { + this.clientContext = clientContext; + return this; + } + + public Builder codecCreator(EzyCodecCreator codecCreator) { + this.codecCreator = codecCreator; + return this; + } + + @Override + public EzyClientStarter build() { + EzyClientStarter answer = new EzyClientStarter(); + answer.setHost(host); + answer.setPort(port); + answer.setCodecCreator(codecCreator); + answer.setClientContext(clientContext); + return answer; + } + + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzySimpleClientContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzySimpleClientContext.java deleted file mode 100644 index 744dd80b..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/EzySimpleClientContext.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.tvd12.ezyfoxserver.client; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.function.Supplier; - -import com.tvd12.ezyfoxserver.client.cmd.impl.EzyClientShutdownImpl; -import com.tvd12.ezyfoxserver.command.EzyRunWorker; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.command.EzyShutdown; -import com.tvd12.ezyfoxserver.command.impl.EzyRunWorkerImpl; -import com.tvd12.ezyfoxserver.command.impl.EzySendMessageImpl; -import com.tvd12.ezyfoxserver.entity.EzyEntity; - -import io.netty.channel.ChannelHandlerContext; -import lombok.Getter; -import lombok.Setter; - -public class EzySimpleClientContext - extends EzyEntity - implements EzyClientContext { - - @Setter - @Getter - protected EzyClient client; - @Setter - @Getter - protected ExecutorService workerExecutor; - @Setter - protected ChannelHandlerContext channelContext; - @SuppressWarnings("rawtypes") - protected Map commandSuppliers; - - { - commandSuppliers = defaultCommandSuppliers(); - } - - @SuppressWarnings("unchecked") - @Override - public T get(Class clazz) { - if(commandSuppliers.containsKey(clazz)) - return (T) commandSuppliers.get(clazz).get(); - if(containsKey(clazz)) - return getProperty(clazz); - throw new IllegalArgumentException("has no instance of " + clazz); - } - - @SuppressWarnings("rawtypes") - protected Map defaultCommandSuppliers() { - Map answer = new HashMap<>(); - answer.put(EzySendMessage.class, () -> new EzySendMessageImpl()); - answer.put(EzyRunWorker.class, () -> new EzyRunWorkerImpl(getWorkerExecutor())); - answer.put(EzyShutdown.class, () -> new EzyClientShutdownImpl(this)); - return answer; - } - - @Override - public void destroy() { - client.destroy(); - workerExecutor.shutdown(); - } - -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzyPingSchedule.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzyPingSchedule.java new file mode 100644 index 00000000..5c266f26 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzyPingSchedule.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.client.cmd; + +public interface EzyPingSchedule { + + void start(); + + void stop(); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzySendRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzySendRequest.java new file mode 100644 index 00000000..0285d319 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/EzySendRequest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.client.cmd; + +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.command.EzyCommand; +import com.tvd12.ezyfoxserver.entity.EzySender; + +public interface EzySendRequest extends EzyCommand { + + EzySendRequest sender(EzySender sender); + + EzySendRequest request(EzyRequest request); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyClientShutdownImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyClientShutdownImpl.java index 5fb1005c..85740715 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyClientShutdownImpl.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyClientShutdownImpl.java @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.client.cmd.impl; -import com.tvd12.ezyfoxserver.client.EzyClientContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; import com.tvd12.ezyfoxserver.command.EzyShutdown; public class EzyClientShutdownImpl implements EzyShutdown { diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyPingScheduleImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyPingScheduleImpl.java new file mode 100644 index 00000000..1baef89b --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzyPingScheduleImpl.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.client.cmd.impl; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import com.tvd12.ezyfoxserver.client.cmd.EzyPingSchedule; +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.request.EzyPingRequest; +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzyPingScheduleImpl + extends EzyLoggable implements EzyPingSchedule { + + protected long delay = 3000; + protected long period = 3000; + protected EzyClientContext context; + protected ScheduledExecutorService service; + + public EzyPingScheduleImpl(EzyClientContext context) { + this.context = context; + this.service = EzyExecutors.newSingleThreadScheduledExecutor("client-ping-service"); + Runtime.getRuntime().addShutdownHook(new Thread(() -> service.shutdown())); + } + + @Override + public void start() { + getLogger().debug("start ping schedule"); + service.scheduleAtFixedRate(this::execute, delay, period, TimeUnit.MILLISECONDS); + } + + @Override + public void stop() { + service.shutdownNow(); + getLogger().debug("stop ping schedule"); + } + + protected void execute() { + try { + context + .get(EzySendRequest.class) + .sender(context.getMe()) + .request(newPingRequest()) + .execute(); + } + catch(Exception e) { + getLogger().error("send ping to server error", e); + } + } + + protected EzyRequest newPingRequest() { + return EzyPingRequest.builder().build(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzySendRequestImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzySendRequestImpl.java new file mode 100644 index 00000000..f859f5b2 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/cmd/impl/EzySendRequestImpl.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.client.cmd.impl; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; +import com.tvd12.ezyfoxserver.command.impl.EzyAbstractCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySender; + +public class EzySendRequestImpl extends EzyAbstractCommand implements EzySendRequest { + + protected EzySender sender; + protected EzyRequest request; + + protected Set unloggableCommands; + + protected final EzyRequestSerializer requestSerializer; + + public EzySendRequestImpl(EzyClientContext context) { + this.requestSerializer = context.get(EzyRequestSerializer.class); + this.unloggableCommands = context.getClient().getUnloggableCommands(); + } + + @Override + public EzySendRequest sender(EzySender sender) { + this.sender = sender; + return this; + } + + @Override + public EzySendRequest request(EzyRequest request) { + this.request = request; + return this; + } + + @Override + public Boolean execute() { + EzyArray requestParams = serializeToArray(request); + sender.send(requestParams); + return Boolean.TRUE; + } + + protected void debugLogRequest(EzyArray requestParams) { + if(!unloggableCommands.contains(request.getCommand())) + getLogger().debug("send to server commad {} "); + } + + protected EzyArray serializeToArray(EzyRequest request) { + return requestSerializer.serializeToArray(request); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientCommand.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientCommand.java new file mode 100644 index 00000000..d2765692 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientCommand.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.client.constants; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyClientCommand implements EzyConstant { + + ACESS_APP_SUCCESS(0), + CONNECT_SUCCESS(1), + CONNECT_FAILURE(2), + ERROR(10), + HANDSHAKE(11), + PING(12), + PONG(13), + DISCONNECT(14), + PLUGIN_REQUEST(15), + LOGIN(20), + LOGIN_ERROR(21), + LOGOUT(22), + APP_ACCESS(30), + APP_REQUEST(31), + APP_JOINED(32), + APP_EXIT(33); + + @Getter + private final int id; + + private EzyClientCommand(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyClientCommand valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/constants/EzyClientConstant.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientConstant.java similarity index 77% rename from ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/constants/EzyClientConstant.java rename to ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientConstant.java index b65b99b6..ab53787e 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/constants/EzyClientConstant.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyClientConstant.java @@ -1,8 +1,8 @@ -package com.tvd12.ezyfoxserver.constants; +package com.tvd12.ezyfoxserver.client.constants; import com.tvd12.ezyfoxserver.constant.EzyConstant; -public abstract class EzyClientConstant { +public final class EzyClientConstant { public static final EzyConstant ME = EzyConstant.one(); public static final EzyConstant PRIVATE_KEY = EzyConstant.one(); diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyConnectionError.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyConnectionError.java new file mode 100644 index 00000000..bb8fae76 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/constants/EzyConnectionError.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.client.constants; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +import lombok.Getter; + +public enum EzyConnectionError implements EzyConstant { + + UNKNOWN(0), + NETWORK_UNREACHABLE(1), + CONNECTION_REFUSED(2), + NO_ROUTE_TO_HOST(2); + + @Getter + private int id; + + private EzyConnectionError(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientAppContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientAppContext.java new file mode 100644 index 00000000..afbf7f52 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientAppContext.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.client.context; + +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyClientAppContext + extends EzyPluginRequester, EzyContext, EzyDestroyable { + + int getAppId(); + + String getAppName(); + + EzyClientUser getMe(); + + EzyClientContext getParent(); + + T get(Class clazz); + + void sendRequest(Object requestId, EzyData params); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContext.java new file mode 100644 index 00000000..ccd3c696 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContext.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.client.context; + +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyClientContext + extends EzyPluginRequester, EzyContext, EzyDestroyable { + + EzyClient getClient(); + + EzyClientUser getMe(); + + void addAppContext(EzyClientAppContext context); + + EzyClientAppContext getAppContext(int appId); + + EzyClientAppContext getAppContext(String appName); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContextBuilder.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContextBuilder.java new file mode 100644 index 00000000..16880359 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyClientContextBuilder.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.client.context; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; +import com.tvd12.ezyfoxserver.client.serialize.impl.EzyRequestSerializerImpl; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public class EzyClientContextBuilder implements EzyBuilder { + + protected final EzyClient client; + + public EzyClientContextBuilder() { + this.client = newClient(); + } + + public static EzyClientContextBuilder newInstance() { + return new EzyClientContextBuilder(); + } + + protected EzyClient newClient() { + return new EzyClient(); + } + + public EzyClientContextBuilder setupClient(EzyApply applier) { + applier.apply(client); + return this; + } + + @Override + public EzyClientContext build() { + EzySimpleClientContext context = newProduct(); + context.setClient(client); + context.setProperty(EzyRequestSerializer.class, newRequestSerializer()); + context.setWorkerExecutor(EzyExecutors.newFixedThreadPool(16, "client-worker")); + return context; + } + + protected EzySimpleClientContext newProduct() { + return new EzySimpleClientContext(); + } + + protected EzyRequestSerializer newRequestSerializer() { + return EzyRequestSerializerImpl.builder().build(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyPluginRequester.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyPluginRequester.java new file mode 100644 index 00000000..5cfa4fad --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzyPluginRequester.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.client.context; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyPluginRequester { + + void sendPluginRequest(String pluginName, EzyArray data); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientAppContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientAppContext.java new file mode 100644 index 00000000..4df17b5a --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientAppContext.java @@ -0,0 +1,72 @@ +package com.tvd12.ezyfoxserver.client.context; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.client.request.EzyRequestAppRequest; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyEntity; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; + +import lombok.Builder; +import lombok.Getter; + +@Getter +@Builder +public class EzySimpleClientAppContext + extends EzyEntity + implements EzyClientAppContext { + + protected int appId; + protected String appName; + protected EzyClientContext parent; + + @SuppressWarnings("unchecked") + @Override + public T get(Class clazz) { + Object answer = parent.get(clazz); + if(answer == null) + answer = getProperty(clazz); + return (T)answer; + } + + @Override + public EzyClientUser getMe() { + return getParent().getMe(); + } + + @Override + public void sendRequest(Object requestId, EzyData params) { + get(EzySendRequest.class) + .sender(getMe()) + .request(newRequest(requestId, params)) + .execute(); + } + + @Override + public void sendPluginRequest(String pluginName, EzyArray data) { + parent.sendPluginRequest(pluginName, data); + } + + private EzyRequest newRequest(Object requestId, EzyData params) { + return EzyRequestAppRequest.builder() + .appId(appId) + .data(newArrayBuilder() + .append(requestId) + .append(params) + .build()) + .build(); + } + + @Override + public void destroy() { + this.parent = null; + this.properties.clear(); + } + + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientContext.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientContext.java new file mode 100644 index 00000000..339c68d9 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/context/EzySimpleClientContext.java @@ -0,0 +1,113 @@ +package com.tvd12.ezyfoxserver.client.context; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.cmd.EzyPingSchedule; +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.cmd.impl.EzyClientShutdownImpl; +import com.tvd12.ezyfoxserver.client.cmd.impl.EzyPingScheduleImpl; +import com.tvd12.ezyfoxserver.client.cmd.impl.EzySendRequestImpl; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.client.entity.EzySimpleClientUser; +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.client.request.EzyRequestPluginRequest; +import com.tvd12.ezyfoxserver.command.EzyRunWorker; +import com.tvd12.ezyfoxserver.command.EzySendMessage; +import com.tvd12.ezyfoxserver.command.EzyShutdown; +import com.tvd12.ezyfoxserver.command.impl.EzyRunWorkerImpl; +import com.tvd12.ezyfoxserver.command.impl.EzySendMessageImpl; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyEntity; + +import lombok.Getter; +import lombok.Setter; + +public class EzySimpleClientContext + extends EzyEntity + implements EzyClientContext { + + @Setter + @Getter + protected EzyClient client; + + @Getter + protected final EzyClientUser me; + + @Setter + @Getter + protected ExecutorService workerExecutor; + + @SuppressWarnings("rawtypes") + protected Map commandSuppliers = defaultCommandSuppliers(); + + protected Map appContextByIds = new ConcurrentHashMap<>(); + protected Map appContextByNames = new ConcurrentHashMap<>(); + + public EzySimpleClientContext() { + me = new EzySimpleClientUser(); + } + + @SuppressWarnings("unchecked") + @Override + public T get(Class clazz) { + if(commandSuppliers.containsKey(clazz)) + return (T) commandSuppliers.get(clazz).get(); + if(containsKey(clazz)) + return getProperty(clazz); + return null; + } + + @Override + public EzyClientAppContext getAppContext(int appId) { + return appContextByIds.get(appId); + } + + @Override + public EzyClientAppContext getAppContext(String appName) { + return appContextByNames.get(appName); + } + + @Override + public void addAppContext(EzyClientAppContext context) { + appContextByIds.put(context.getAppId(), context); + appContextByNames.put(context.getAppName(), context); + } + + @Override + public void sendPluginRequest(String pluginName, EzyArray data) { + get(EzySendRequest.class) + .sender(getMe()) + .request(newPluginRequest(pluginName, data)) + .execute(); + } + + private EzyRequest newPluginRequest(String pluginName, EzyArray data) { + return EzyRequestPluginRequest.builder() + .pluginName(pluginName).data(data).build(); + } + + @SuppressWarnings("rawtypes") + protected Map defaultCommandSuppliers() { + EzyPingSchedule pingSchedule = new EzyPingScheduleImpl(this); + Map answer = new HashMap<>(); + answer.put(EzyPingSchedule.class, () -> pingSchedule); + answer.put(EzySendMessage.class, () -> new EzySendMessageImpl()); + answer.put(EzySendRequest.class, () -> new EzySendRequestImpl(this)); + answer.put(EzyShutdown.class, () -> new EzyClientShutdownImpl(this)); + answer.put(EzyRunWorker.class, () -> new EzyRunWorkerImpl(getWorkerExecutor())); + return answer; + } + + @Override + public void destroy() { + client.destroy(); + properties.clear(); + workerExecutor.shutdown(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAbstractController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAbstractController.java index d035fd4b..2c408ae9 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAbstractController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAbstractController.java @@ -1,48 +1,6 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; -import com.tvd12.ezyfoxserver.client.request.EzyRequest; -import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; -import com.tvd12.ezyfoxserver.constants.EzyClientConstant; -import com.tvd12.ezyfoxserver.context.EzyContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.entity.EzyUser; -import com.tvd12.ezyfoxserver.factory.EzyFactory; -import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; -public class EzyAbstractController extends EzyLoggable { - - protected EzyRequestSerializer getRequestSerializer(EzyContext ctx) { - return ctx.get(EzyRequestSerializer.class); - } - - protected EzyObject serializeToObject(EzyContext ctx, EzyRequest request) { - return getRequestSerializer(ctx).serializeToObject(request); - } - - protected EzyArray serializeToArray(EzyContext ctx, EzyRequest request) { - return getRequestSerializer(ctx).serializeToArray(request); - } - - protected EzyArrayBuilder newArrayBuilder() { - return EzyFactory.create(EzyArrayBuilder.class); - } - - protected EzyObjectBuilder newObjectBuilder() { - return EzyFactory.create(EzyObjectBuilder.class); - } - - protected EzyUser getMe(EzyContext ctx) { - return getProperty(ctx, EzyClientConstant.ME); - } - - protected T getProperty(EzyContext ctx, Object key) { - return ctx.getProperty(key); - } - - protected void setProperty(EzyContext ctx, Object key, Object value) { - ctx.setProperty(key, value); - } +public class EzyAbstractController extends EzyEntityBuilders { } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAccessAppController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAccessAppController.java index 38bb2487..c8b46cb5 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAccessAppController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyAccessAppController.java @@ -1,39 +1,35 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.client.EzyClientContext; -import com.tvd12.ezyfoxserver.client.request.EzyJoinRoomRequest; -import com.tvd12.ezyfoxserver.client.request.EzyRequest; -import com.tvd12.ezyfoxserver.command.EzySendMessage; +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.context.EzySimpleClientAppContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyUser; public class EzyAccessAppController extends EzyAbstractController - implements EzyClientController { + implements EzyClientController { + @SuppressWarnings({ "rawtypes", "unchecked" }) @Override - public void handle(EzyClientContext ctx, EzyUser user, EzyArray data) { - getLogger().info("access app success, appId = " + data.get(0)); - sendJoinRoomRequest(ctx, user, data.get(0)); - getLogger().info("sended join room request"); + public void handle(EzyClientContext ctx, EzyClientUser user, EzyArray data) { + getLogger().info("access app success, data = " + data); + EzyClientAppContext appCtx = newAppContext(ctx, data); + ctx.addAppContext(appCtx); + EzyClient client = ctx.getClient(); + EzyClientAppController ctrl = client.getAppController(EzyClientCommand.ACESS_APP_SUCCESS); + if(ctrl != null) ctrl.handle(appCtx, user, data.get(2, EzyArray.class)); } - protected void sendJoinRoomRequest(EzyClientContext ctx, EzyUser user, int appId) { - ctx.get(EzySendMessage.class) - .sender(user) - .data(serializeToArray(ctx, newJoinRoomRequest(appId))) - .execute(); - } - - protected EzyRequest newJoinRoomRequest(int appId) { - return EzyJoinRoomRequest.builder() - .appId(appId) - .data(newJoinRoomData()) + protected EzyClientAppContext newAppContext(EzyClientContext ctx, EzyArray data) { + return EzySimpleClientAppContext.builder() + .appId(data.get(0, int.class)) + .appName(data.get(1, String.class)) + .parent(ctx) .build(); } - protected EzyArray newJoinRoomData() { - return newArrayBuilder().append(1).append("lobby").build(); - } - + } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientAppController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientAppController.java new file mode 100644 index 00000000..e9ec7e1d --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientAppController.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.client.entity.EzySimpleClientUser; + +public interface EzyClientAppController + extends EzyClientBaseController { +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientBaseController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientBaseController.java new file mode 100644 index 00000000..e9a7dccf --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientBaseController.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.client.controller; + +public interface EzyClientBaseController { + + public void handle(C ctx, R rev, D data); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientController.java index 2979344f..dcfd8b88 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyClientController.java @@ -1,9 +1,7 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.client.EzyClientContext; -import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; import com.tvd12.ezyfoxserver.entity.EzyArray; -public interface EzyClientController - extends EzyController { +public interface EzyClientController extends EzyClientBaseController { } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectFailureController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectFailureController.java new file mode 100644 index 00000000..f5c631ff --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectFailureController.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyConnectFailureController { + + EzyConnectFailureController EMPTY = (error) -> {}; + + void handle(EzyConstant error); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectSuccessController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectSuccessController.java new file mode 100644 index 00000000..6f3107c7 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyConnectSuccessController.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.client.request.EzyHandShakeRequest; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyConnectSuccessController + extends EzyAbstractController + implements EzyClientController { + + @Override + public void handle(EzyClientContext ctx, EzyClientSession session, EzyArray data) { + sendHandShakeRequest(ctx, session); + } + + protected void sendHandShakeRequest(EzyClientContext ctx, EzyClientSession session) { + ctx.get(EzySendRequest.class) + .sender(session) + .request(newHandShakeRequest()) + .execute(); + } + + protected EzyHandShakeRequest newHandShakeRequest() { + return EzyHandShakeRequest.builder().build(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyDisconnectController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyDisconnectController.java index 45aef9d9..163914d8 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyDisconnectController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyDisconnectController.java @@ -1,28 +1,16 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.client.EzyClientContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.entity.EzyUser; public class EzyDisconnectController extends EzyAbstractController - implements EzyClientController { + implements EzyClientController { @Override - public void handle(EzyClientContext ctx, Object rev, EzyArray data) { - if(rev instanceof EzyUser) - handle(ctx, (EzyUser)rev, data); - else - handle(ctx, (EzySession)rev, data); - } - - protected void handle(EzyClientContext ctx, EzyUser user, EzyArray data) { - handle(ctx, user.getSession(), data); - } - - protected void handle(EzyClientContext ctx, EzySession session, EzyArray data) { + public void handle(EzyClientContext ctx, EzyClientUser rev, EzyArray data) { getLogger().info("user be disconnected by reason {}", EzyDisconnectReason.valueOf(data.get(0, Integer.class))); } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyErrorController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyErrorController.java new file mode 100644 index 00000000..34271ace --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyErrorController.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyErrorController + extends EzyAbstractController + implements EzyClientController { + + @Override + public void handle(EzyClientContext ctx, EzyClientSession rev, EzyArray data) { + getLogger().info("error {}", data); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyHandShakeController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyHandShakeController.java index e47a7001..25f899c7 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyHandShakeController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyHandShakeController.java @@ -1,49 +1,20 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.client.EzyClientContext; -import com.tvd12.ezyfoxserver.client.request.EzyLoginRequest; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzySession; public class EzyHandShakeController extends EzyAbstractController - implements EzyClientController { + implements EzyClientController { @Override - public void handle(EzyClientContext ctx, EzySession session, EzyArray data) { - getLogger().info("begin handle handshake, server key {}, reconnect token {}", - data.get(0), data.get(1)); - sendLoginRequest(ctx, session); - getLogger().info("end handshake sending login request"); + public void handle(EzyClientContext ctx, EzyClientSession session, EzyArray data) { + updateSession(session, data); } - protected void sendLoginRequest(EzyContext ctx, EzySession session) { - ctx.get(EzySendMessage.class) - .data(newLoginData(ctx, "dungtv", "123456")) - .sender(session) - .execute(); + protected void updateSession(EzyClientSession session, EzyArray data) { + session.setReconnectToken(""); } - protected EzyArray newLoginData(EzyContext ctx, String name, String pass) { - return serializeToArray(ctx, newLoginRequest(name, pass)); - } - - protected EzyLoginRequest newLoginRequest(String name, String pass) { - return EzyLoginRequest.builder() - .username(name) - .password(pass) - .data(newLoginInData()) - .build(); - } - - protected EzyData newLoginInData() { - return newObjectBuilder() - .append("v", "1.0.0") - .append("t", "android") - .build(); - } - } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginController.java index d59104d9..4bfcc0de 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginController.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginController.java @@ -1,65 +1,58 @@ package com.tvd12.ezyfoxserver.client.controller; -import com.tvd12.ezyfoxserver.client.EzyClientContext; -import com.tvd12.ezyfoxserver.client.request.EzyAccessAppRequest; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.constants.EzyClientConstant; -import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.context.EzySimpleClientAppContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.client.entity.EzySimpleClientUser; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.entity.EzySimpleUser; -import com.tvd12.ezyfoxserver.entity.EzyUser; public class EzyLoginController extends EzyAbstractController - implements EzyClientController { + implements EzyClientController { @Override - public void handle(EzyClientContext ctx, EzySession session, EzyArray data) { - setMe(ctx, session, data); - sendAccessAppRequest(ctx); + public void handle(EzyClientContext ctx, EzyClientSession session, EzyArray data) { + updateMe(ctx, data); + EzyArray joinedApps = data.get(2, EzyArray.class); + if(joinedApps.isEmpty()) + processNotReconnect(ctx, session, data); + else + processReconnect(ctx, joinedApps); } - protected void sendAccessAppRequest(EzyContext ctx) { - ctx.get(EzySendMessage.class) - .data(newAccessAppData(ctx)) - .sender(getMe(ctx)) - .execute(); + protected void processNotReconnect(EzyClientContext ctx, EzyClientSession session, EzyArray data) { } - protected EzyArray newAccessAppData(EzyContext ctx) { - return serializeToArray(ctx, newAccessAppRequest()); - } - - protected EzyAccessAppRequest newAccessAppRequest() { - return EzyAccessAppRequest.builder() - .appName("ezyfox-chat") - .data(newAccessAppData()) - .build(); - } - - protected EzyObject newAccessAppData() { - return newObjectBuilder().build(); - } - - protected void setMe(EzyContext ctx, EzySession session, EzyArray data) { - setProperty(ctx, EzyClientConstant.ME, createMe(session, data)); - } - - protected EzyUser createMe(EzySession session, EzyArray data) { + protected void updateMe(EzyClientContext ctx, EzyArray data) { long userId = data.get(0, long.class); - String username = data.get(1); - EzySimpleUser me = new EzySimpleUser(); + String username = data.get(1, String.class); + EzySimpleClientUser me = (EzySimpleClientUser) ctx.getMe(); me.setId(userId); - me.setSession(session); me.setName(username); getLogger().info("login success userId = {}, username = {}", userId, username); - return me; } - protected void sendAccessAppRequest() { - + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected void processReconnect(EzyClientContext ctx, EzyArray joinedApps) { + for(int i = 0 ; i < joinedApps.size() ; i++) { + EzyArray data = joinedApps.get(0, EzyArray.class); + EzyClientAppContext appCtx = newAppContext(ctx, data); + ctx.addAppContext(appCtx); + EzyClient client = ctx.getClient(); + EzyClientAppController ctrl = client.getAppController(EzyClientCommand.ACESS_APP_SUCCESS); + if(ctrl != null) ctrl.handle(appCtx, appCtx.getMe(), newArrayBuilder().build()); + } } - + + protected EzyClientAppContext newAppContext(EzyClientContext ctx, EzyArray data) { + return EzySimpleClientAppContext.builder() + .appId(data.get(0, int.class)) + .appName(data.get(1, String.class)) + .parent(ctx) + .build(); + } + } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginErrorController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginErrorController.java new file mode 100644 index 00000000..4e8bfdfa --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyLoginErrorController.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyLoginErrorController + extends EzyAbstractController + implements EzyClientController { + + @Override + public void handle(EzyClientContext ctx, EzyClientSession rev, EzyArray data) { + getLogger().info("login error {}", data); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyPongController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyPongController.java new file mode 100644 index 00000000..16cc168e --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyPongController.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyPongController implements EzyClientController { + + @Override + public void handle(EzyClientContext ctx, EzyClientUser rev, EzyArray data) { + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyRequestAppController.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyRequestAppController.java new file mode 100644 index 00000000..4790d456 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/controller/EzyRequestAppController.java @@ -0,0 +1,50 @@ +package com.tvd12.ezyfoxserver.client.controller; + +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.client.listener.EzyClientAppResponseListener; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; + +public class EzyRequestAppController + extends EzyAbstractController + implements EzyClientController { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void handle(EzyClientContext ctx, EzyClientUser user, EzyArray data) { + int appId = data.get(0, int.class); + EzyData responseData = getResponseData(data); + Object requestId = getRequestId(responseData); + EzyData responseParams = getReponseParams(responseData); + EzyClientAppContext appContext = ctx.getAppContext(appId); + EzyClientAppResponseListener listener = getAppResponseListener(ctx, requestId); + if(listener != null) + listener.execute(appContext, responseParams); + } + + @SuppressWarnings("rawtypes") + protected EzyClientAppResponseListener + getAppResponseListener(EzyClientContext ctx, Object requestId) { + return ctx.getClient().getAppResponseListener(requestId); + } + + protected EzyData getResponseData(EzyArray data) { + return data.get(1, EzyArray.class); + } + + protected Object getRequestId(EzyData data) { + return ((EzyArray)data).get(0, String.class); + } + + protected EzyData getReponseParams(EzyData data) { + return ((EzyArray)data).get(1); + } + + protected void sendChatMessageRequest(EzyClientAppContext appCtx) { + EzyArray params = newArrayBuilder().append("nice to meet you!").build(); + appCtx.sendRequest("1", params); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientSession.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientSession.java new file mode 100644 index 00000000..a1fb2b3b --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientSession.java @@ -0,0 +1,287 @@ +package com.tvd12.ezyfoxserver.client.entity; + +import java.io.Serializable; +import java.net.SocketAddress; +import java.util.concurrent.locks.Lock; + +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzySender; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyProperties; + +public interface EzyClientSession extends EzySender, EzyProperties, EzyDestroyable, Serializable { + + /** + * Get session id + * + * @return the session id + */ + long getId(); + + /** + * Get client key to encrypt data send to client + * + * @return the client key + */ + byte[] getServerKey(); + + /** + * + * Set client key + * + * @param key the client key + */ + void setServerKey(byte[] key); + + + /** + * 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 reconnect token + * + * @return the session reconnect token + */ + String getReconnectToken(); + + /** + * Set reconnect token + * + * @param token the reconnect token + */ + void setReconnectToken(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 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 the lock + */ + Lock getLock(); + + /** + * @param delegate the delegate + */ + void setDelegate(EzySessionDelegate delegate); + + /** + * @return the delegate + */ + EzySessionDelegate getDelegate(); + + /** + * 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 + */ + void disconnect(); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientUser.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientUser.java new file mode 100644 index 00000000..ec9b0c6f --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzyClientUser.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.client.entity; + +import com.tvd12.ezyfoxserver.entity.EzySender; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyProperties; + +public interface EzyClientUser extends EzySender, EzyProperties, EzyDestroyable { + + /** + * Get user id + * + * @return the user id + */ + long getId(); + + /** + * Get user name + * + * @eturn the user name + */ + String getName(); + + /** + * Get current session + * + * @return the current session + */ + EzyClientSession getSession(); + + /** + * Add new session + * + * @param session the session to add + */ + void setSession(EzyClientSession session); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientSession.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientSession.java new file mode 100644 index 00000000..52399ba5 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientSession.java @@ -0,0 +1,90 @@ +package com.tvd12.ezyfoxserver.client.entity; + +import java.net.SocketAddress; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyEntity; + +import io.netty.channel.Channel; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleClientSession extends EzyEntity implements EzyClientSession { + private static final long serialVersionUID = 8916844385176991522L; + + protected long id; + private String clientId; + protected long creationTime; + protected long lastReadTime; + protected long lastWriteTime; + protected long readBytes; + protected long writtenBytes; + protected long lastActivityTime; + + protected byte[] privateKey; + protected byte[] publicKey; + protected byte[] serverKey; + + protected boolean loggedIn; + protected boolean activated; + protected long loggedInTime; + + protected String clientType; + protected String clientVersion; + protected String reconnectToken; + protected String fullReconnectToken; + + protected long maxWaitingTime = 5 * 1000; + protected long maxIdleTime = 3 * 60 * 1000; + + protected transient EzySessionDelegate delegate; + protected transient Lock lock = new ReentrantLock(); + protected transient Channel channel; + + @Override + public void addReadBytes(long bytes) { + this.readBytes += bytes; + } + + @Override + public void addWrittenBytes(long bytes) { + this.writtenBytes += bytes; + } + + @Override + public SocketAddress getClientAddress() { + return channel != null ? channel.remoteAddress() : null; + } + + @Override + public SocketAddress getServerAddress() { + return channel != null ? channel.localAddress() : null; + } + + @Override + public void send(EzyData data, EzyTransportType type) { + channel.writeAndFlush(data); + } + + @Override + public void disconnect() { + channel.disconnect().syncUninterruptibly(); + } + + @Override + public void close() { + channel.close().syncUninterruptibly(); + } + + @Override + public void destroy() { + this.setChannel(null); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientUser.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientUser.java new file mode 100644 index 00000000..67779cfe --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/entity/EzySimpleClientUser.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.client.entity; + +import java.io.Serializable; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyEntity; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzySimpleClientUser extends EzyEntity implements EzyClientUser, Serializable { + private static final long serialVersionUID = -7230916678168758064L; + + protected long id; + protected String name; + protected EzyClientSession session; + + @Override + public void send(EzyData data, EzyTransportType type) { + session.send(data); + } + + @Override + public void destroy() { + session.destroy(); + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyClientHandler.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyClientHandler.java index 61872a4d..ae35b4ff 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyClientHandler.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyClientHandler.java @@ -3,26 +3,30 @@ */ package com.tvd12.ezyfoxserver.client.handler; +import java.util.Set; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; import com.tvd12.ezyfoxserver.client.EzyClient; -import com.tvd12.ezyfoxserver.client.EzyClientContext; +import com.tvd12.ezyfoxserver.client.cmd.EzyPingSchedule; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.constants.EzyClientConstant; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.controller.EzyClientController; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.client.entity.EzySimpleClientSession; import com.tvd12.ezyfoxserver.client.request.EzyHandShakeRequest; -import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; import com.tvd12.ezyfoxserver.command.EzyRunWorker; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.command.EzyShutdown; -import com.tvd12.ezyfoxserver.constant.EzyCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.constants.EzyClientConstant; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.entity.EzySimpleSession; -import com.tvd12.ezyfoxserver.entity.EzyUser; import com.tvd12.ezyfoxserver.exception.EzyResponseHandleException; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.netty.handler.EzyBytesReceived; +import com.tvd12.ezyfoxserver.netty.handler.EzyBytesSent; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; @@ -31,45 +35,88 @@ * @author tavandung12 * */ -public class EzyClientHandler extends SimpleChannelInboundHandler { +public class EzyClientHandler + extends SimpleChannelInboundHandler + implements EzyBytesReceived, EzyBytesSent { - private EzySession session; + private EzyClient client; + private EzyClientSession session; private EzyClientContext context; - private EzyControllers controllers; - private EzyRequestSerializer requestSerializer; + protected Set unloggableCommands; + private Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public void bytesReceived(int count) { + session.addReadBytes(count); + } + + @Override + public void bytesSent(int count) { + session.addWrittenBytes(count); + } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { - getLogger().info("active complete, be going to handshake"); + getLogger().debug("channel active"); createNewSession(ctx); - sendHandShakeRequest(); - getLogger().info("has send handshake"); + updateContextWithNewSession(); + notifyConnectSuccess(ctx); + startPingSchedule(); } + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + getLogger().debug("channel inactive"); + stopPingSchedule(); + } + + @Override + public void channelRegistered(ChannelHandlerContext ctx) throws Exception { + getLogger().debug("channel register"); + } + + @Override + public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { + getLogger().debug("channel unregister"); + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + getLogger().debug("handler added"); + } + @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - getLogger().info("handler removed"); - context.get(EzyShutdown.class).execute(); + getLogger().debug("handler removed"); } @Override protected void channelRead0(ChannelHandlerContext ctx, EzyArray msg) throws Exception { - getLogger().info("Client recived: " + msg); int cmdId = msg.get(0); EzyData data = msg.get(1); - EzyCommand cmd = EzyCommand.valueOf(cmdId); + EzyClientCommand cmd = EzyClientCommand.valueOf(cmdId); + debugLogReceivedData(cmd, data); handleResponse(cmd, data); } - protected void sendHandShakeRequest() { - context.get(EzySendMessage.class) - .data(newHandShakeData()) - .sender(session) - .execute(); + protected void debugLogReceivedData(EzyClientCommand cmd, EzyData data) { + if(!unloggableCommands.contains(cmd)) + getLogger().info("client fire command: {} with data: {}", cmd, data); + } + + protected void startPingSchedule() { + context.get(EzyPingSchedule.class).start(); } - protected EzyArray newHandShakeData() { - return requestSerializer.serializeToArray(newHandShakeRequest()); + protected void stopPingSchedule() { + context.get(EzyPingSchedule.class).stop(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected void notifyConnectSuccess(ChannelHandlerContext ctx) { + EzyClientController ctrl = + client.getController(EzyClientCommand.CONNECT_SUCCESS); + ctrl.handle(context, session, newArrayBuilder().build()); } protected EzyHandShakeRequest newHandShakeRequest() { @@ -80,43 +127,52 @@ protected void createNewSession(ChannelHandlerContext ctx) { this.session = newSession(ctx); } - protected EzySession newSession(ChannelHandlerContext ctx) { - EzySimpleSession session = new EzySimpleSession(); + protected void updateContextWithNewSession() { + this.context.getMe().setSession(session); + } + + protected EzyClientSession newSession(ChannelHandlerContext ctx) { + EzySimpleClientSession session = new EzySimpleClientSession(); session.setChannel(ctx.channel()); return session; } - protected void handleResponse(EzyCommand cmd, EzyData data) { + protected void handleResponse(EzyClientCommand cmd, EzyData data) { context.get(EzyRunWorker.class).run(() -> { tryHandleResponse(cmd, data); }); } - @SuppressWarnings("unchecked") - protected void tryHandleResponse(EzyCommand cmd, EzyData data) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected void tryHandleResponse(EzyClientCommand cmd, EzyData data) { try { - controllers.getController(cmd).handle(context, getReceiver(), data); + EzyClientController ctr = client.getController(cmd); + ctr.handle(context, getReceiver(cmd), (EzyArray) data); } catch(Exception e) { throw new EzyResponseHandleException(newHandleRequestErrorMessage(cmd, data), e); } } - protected Object getReceiver() { - return getMe() == null ? session : getMe(); + protected Object getReceiver(EzyClientCommand cmd) { + return EzyReceiverDeterminer.builder() + .userSupplier(() -> getMe()) + .sessionSupplier(() -> session) + .build() + .determine(cmd); } public void setContext(EzyClientContext ctx) { this.context = ctx; - this.controllers = getClient().getControllers(); - this.requestSerializer = ctx.get(EzyRequestSerializer.class); + this.client = context.getClient(); + this.unloggableCommands = client.getUnloggableCommands(); } protected EzyClient getClient() { return context.getClient(); } - protected EzyUser getMe() { + protected EzyClientUser getMe() { return context.getProperty(EzyClientConstant.ME); } @@ -129,8 +185,12 @@ protected String newHandleRequestErrorMessage(EzyConstant cmd, EzyData data) { return "error when handle request command: " + cmd + ", data: " + data; } + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + protected Logger getLogger() { - return LoggerFactory.getLogger(getClass()); + return logger; } } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyReceiverDeterminer.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyReceiverDeterminer.java new file mode 100644 index 00000000..414b9bee --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/handler/EzyReceiverDeterminer.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.client.handler; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.client.entity.EzyClientUser; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public class EzyReceiverDeterminer { + + protected Map> suppliers; + + public Object determine(EzyConstant cmd) { + return suppliers.get(cmd).get(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected Supplier userSupplier; + protected Supplier sessionSupplier; + + public Builder userSupplier(Supplier userSupplier) { + this.userSupplier = userSupplier; + return this; + } + + public Builder sessionSupplier(Supplier sessionSupplier) { + this.sessionSupplier = sessionSupplier; + return this; + } + + @Override + public EzyReceiverDeterminer build() { + EzyReceiverDeterminer answer = new EzyReceiverDeterminer(); + answer.suppliers = newSuppliers(); + return answer; + } + + protected Map> newSuppliers() { + Map> answer = new ConcurrentHashMap<>(); + answer.put(EzyClientCommand.PONG, () -> userSupplier.get()); + answer.put(EzyClientCommand.CONNECT_SUCCESS, () -> sessionSupplier.get()); + answer.put(EzyClientCommand.ERROR, () -> userSupplier.get()); + answer.put(EzyClientCommand.HANDSHAKE, () -> sessionSupplier.get()); + answer.put(EzyClientCommand.DISCONNECT, () -> userSupplier.get()); + answer.put(EzyClientCommand.LOGIN, () -> sessionSupplier.get()); + answer.put(EzyClientCommand.LOGIN_ERROR, () -> sessionSupplier.get()); + answer.put(EzyClientCommand.LOGOUT, () -> userSupplier.get()); + answer.put(EzyClientCommand.APP_ACCESS, () -> userSupplier.get()); + answer.put(EzyClientCommand.APP_JOINED, () -> userSupplier.get()); + answer.put(EzyClientCommand.APP_REQUEST, () -> userSupplier.get()); + answer.put(EzyClientCommand.APP_EXIT, () -> userSupplier.get()); + return answer; + } + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/listener/EzyClientAppResponseListener.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/listener/EzyClientAppResponseListener.java new file mode 100644 index 00000000..1d4ed211 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/listener/EzyClientAppResponseListener.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.client.listener; + +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.entity.EzyData; + +public interface EzyClientAppResponseListener

{ + + void execute(EzyClientAppContext ctx, P params); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyAccessAppRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyAccessAppRequest.java index bcad2405..13bfbc25 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyAccessAppRequest.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyAccessAppRequest.java @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.client.request; -import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.entity.EzyData; @@ -16,7 +16,7 @@ protected EzyAccessAppRequest(Builder builder) { @Override public EzyConstant getCommand() { - return EzyCommand.ACCESS_APP; + return EzyClientCommand.APP_ACCESS; } @Override diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyBaseRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyBaseRequest.java index 098199d4..7612d454 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyBaseRequest.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyBaseRequest.java @@ -1,17 +1,6 @@ package com.tvd12.ezyfoxserver.client.request; -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; -import com.tvd12.ezyfoxserver.factory.EzyFactory; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; -public class EzyBaseRequest { - - protected EzyArrayBuilder newArrayBuilder() { - return EzyFactory.create(EzyArrayBuilder.class); - } - - protected EzyObjectBuilder newObjectBuilder() { - return EzyFactory.create(EzyObjectBuilder.class); - } - +public class EzyBaseRequest extends EzyEntityBuilders { } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyFixedCmdRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyFixedCmdRequest.java index 32bdf2cf..68855ede 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyFixedCmdRequest.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyFixedCmdRequest.java @@ -2,6 +2,8 @@ import java.util.HashMap; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + import lombok.Getter; import lombok.Setter; @@ -14,10 +16,11 @@ public abstract class EzyFixedCmdRequest protected Object data; protected EzyFixedCmdRequest(Builder builder) { - this.data = builder.data; + this.data = builder.getData(); } - public abstract static class Builder> { + public abstract static class Builder> + implements EzyBuilder { protected Object data; public B data(Object data) { @@ -25,26 +28,14 @@ public B data(Object data) { return getThis(); } - public EzyFixedCmdRequest build() { - this.prepare(); - return newProduct(); - } - @SuppressWarnings("unchecked") protected B getThis() { return (B)this; } - protected Object defaultData() { - return new HashMap<>(); + protected Object getData() { + return data != null ? data : new HashMap<>(); } - - protected void prepare() { - if(data == null) - data = defaultData(); - } - - protected abstract EzyFixedCmdRequest newProduct(); } } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyHandShakeRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyHandShakeRequest.java index be0a273c..1693be18 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyHandShakeRequest.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyHandShakeRequest.java @@ -3,10 +3,10 @@ import java.io.File; import java.security.KeyPair; -import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.io.EzySimpleFileReader; -import com.tvd12.ezyfoxserver.io.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; import com.tvd12.ezyfoxserver.sercurity.EzyBase64; import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; @@ -16,23 +16,29 @@ public class EzyHandShakeRequest extends EzyBaseRequest implements EzyRequest { private KeyPair keyPair; private String publicKey; private String reconnectToken; + private String clientId = ""; + private String clientType = "JAVA"; + private String clientVersion = "1.0.0"; protected EzyHandShakeRequest(Builder builder) { this.reconnectToken = builder.fetchReconnectToken(); this.keyPair = builder.newKeyPair(); - this.publicKey = EzyBase64.encode2utf8(keyPair.getPublic().getEncoded()); + this.publicKey = EzyBase64.encode2utf(keyPair.getPublic().getEncoded()); } @Override public EzyConstant getCommand() { - return EzyCommand.HAND_SHAKE; + return EzyClientCommand.HANDSHAKE; } @Override public Object getData() { return newArrayBuilder() + .append(clientId) .append(publicKey) .append(reconnectToken) + .append(clientType) + .append(clientVersion) .build(); } @@ -52,9 +58,9 @@ protected String fetchReconnectToken() { protected KeyPair newKeyPair() { return EzyFileKeysGenerator.builder() - .keyLength(512) + .keysize(512) .algorithm("RSA") - .fileWriter(new EzySimpleFileWriter()) + .fileWriter(EzySimpleFileWriter.builder().build()) .privateKeyFile(getPrivateKeyFile()) .build() .generate(); @@ -70,10 +76,11 @@ private File getPrivateKeyFile() { class ReconnectTokenFetcher { public String get() { - return decryptToken(); + return ""; +// return decryptToken(); } - private String decryptToken() { + protected String decryptToken() { try { return tryDecryptToken(); } @@ -86,7 +93,7 @@ private String tryDecryptToken() throws Exception { return EzyFileAsyCrypt.builder() .algorithm("RSA") .privateKeyFile(getPrivateKeyFile()) - .fileReader(new EzySimpleFileReader()) + .fileReader(EzySimpleFileReader.builder().build()) .build() .decrypt(getTokenFile(), String.class); } diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyJoinRoomRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyJoinRoomRequest.java deleted file mode 100644 index 0be9bd43..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyJoinRoomRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.tvd12.ezyfoxserver.client.request; - -import com.tvd12.ezyfoxserver.constant.EzyCommand; -import com.tvd12.ezyfoxserver.constant.EzyConstant; - -public class EzyJoinRoomRequest extends EzyFixedCmdAppRequest { - - protected EzyJoinRoomRequest(Builder builder) { - super(builder); - } - - @Override - public EzyConstant getCommand() { - return EzyCommand.REQUEST_APP; - } - - @Override - public Object getData() { - return newArrayBuilder() - .append(getAppId()) - .append(data) - .build(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyFixedCmdAppRequest.Builder { - @Override - protected EzyFixedCmdRequest newProduct() { - return new EzyJoinRoomRequest(this); - } - } - -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyLoginRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyLoginRequest.java index b76aac99..9e7b0c28 100644 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyLoginRequest.java +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyLoginRequest.java @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.client.request; -import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.entity.EzyData; @@ -18,7 +18,7 @@ protected EzyLoginRequest(Builder builder) { @Override public EzyConstant getCommand() { - return EzyCommand.LOGIN; + return EzyClientCommand.LOGIN; } @Override diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyPingRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyPingRequest.java new file mode 100644 index 00000000..d10f7a6d --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyPingRequest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.client.request; + +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +import lombok.Builder; + +@Builder +public class EzyPingRequest extends EzyEntityBuilders implements EzyRequest { + + @Override + public Object getData() { + return newArrayBuilder().build(); + } + + @Override + public EzyConstant getCommand() { + return EzyClientCommand.PING; + } + + + + + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestAppRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestAppRequest.java new file mode 100644 index 00000000..70c6e783 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestAppRequest.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.client.request; + +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public class EzyRequestAppRequest extends EzyFixedCmdAppRequest { + + protected EzyRequestAppRequest(Builder builder) { + super(builder); + } + + @Override + public EzyConstant getCommand() { + return EzyClientCommand.APP_REQUEST; + } + + @Override + public Object getData() { + return newArrayBuilder() + .append(getAppId()) + .append(data) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyFixedCmdAppRequest.Builder { + + @Override + public EzyRequest build() { + return new EzyRequestAppRequest(this); + } + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestPluginRequest.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestPluginRequest.java new file mode 100644 index 00000000..5d2bdf93 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/request/EzyRequestPluginRequest.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.client.request; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyRequestPluginRequest extends EzyBaseRequest implements EzyRequest { + + protected EzyArray data; + protected String pluginName; + + protected EzyRequestPluginRequest(Builder builder) { + this.data = builder.data; + this.pluginName = builder.pluginName; + } + + @Override + public EzyConstant getCommand() { + return EzyClientCommand.PLUGIN_REQUEST; + } + + @Override + public Object getData() { + return newArrayBuilder() + .append(pluginName) + .append(data) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected EzyArray data; + protected String pluginName; + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + public Builder pluginName(String pluginName) { + this.pluginName = pluginName; + return this; + } + + @Override + public EzyRequest build() { + return new EzyRequestPluginRequest(this); + } + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/iml/EzyRequestSerializerImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/iml/EzyRequestSerializerImpl.java deleted file mode 100644 index f7235457..00000000 --- a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/iml/EzyRequestSerializerImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.tvd12.ezyfoxserver.client.serialize.iml; - -import java.util.HashMap; -import java.util.Map; - -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.client.request.EzyRequest; -import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.factory.EzyFactory; - -import lombok.Builder; - -@Builder -public class EzyRequestSerializerImpl implements EzyRequestSerializer { - - @SuppressWarnings("rawtypes") - private static final Map SERIALIZERS; - - static { - SERIALIZERS = defaultSerializers(); - } - - @SuppressWarnings("unchecked") - @Override - public T serialize(EzyRequest request, Class outType) { - return (T) SERIALIZERS.get(outType).serialize(request); - } - - @SuppressWarnings("rawtypes") - private static Map defaultSerializers() { - Map answer = new HashMap<>(); - answer.put(EzyArray.class, new Serializer() { - @Override - public EzyArray serialize(EzyRequest request) { - return EzyFactory.create(EzyArrayBuilder.class) - .append(request.getCommand().getId()) - .append(request.getData()) - .build(); - } - }); - return answer; - } - -} - -interface Serializer { - O serialize(I request); -} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/impl/EzyRequestSerializerImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/impl/EzyRequestSerializerImpl.java new file mode 100644 index 00000000..7bb2993c --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/serialize/impl/EzyRequestSerializerImpl.java @@ -0,0 +1,42 @@ +package com.tvd12.ezyfoxserver.client.serialize.impl; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.client.request.EzyRequest; +import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.function.EzySerializer; + +import lombok.Builder; + +@Builder +public class EzyRequestSerializerImpl implements EzyRequestSerializer { + + @SuppressWarnings("rawtypes") + private static final Map SERIALIZERS = defaultSerializers(); + + @SuppressWarnings("unchecked") + @Override + public T serialize(EzyRequest request, Class outType) { + return (T) SERIALIZERS.get(outType).serialize(request); + } + + @SuppressWarnings("rawtypes") + private static Map defaultSerializers() { + Map answer = new HashMap<>(); + answer.put(EzyArray.class, new EzySerializer() { + @Override + public EzyArray serialize(EzyRequest request) { + return EzyEntityFactory.create(EzyArrayBuilder.class) + .append(request.getCommand().getId()) + .append(request.getData()) + .build(); + } + }); + return answer; + } + +} \ No newline at end of file diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppControllers.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppControllers.java new file mode 100644 index 00000000..454c0c01 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppControllers.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.client.wrapper; + +import com.tvd12.ezyfoxserver.client.controller.EzyClientAppController; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyClientAppControllers extends EzyDestroyable { + + @SuppressWarnings("rawtypes") + EzyClientAppController getController(EzyConstant cmd); + + @SuppressWarnings("rawtypes") + void addController(EzyConstant cmd, EzyClientAppController ctrl); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppResponseListeners.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppResponseListeners.java new file mode 100644 index 00000000..e57301aa --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientAppResponseListeners.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.client.wrapper; + +import com.tvd12.ezyfoxserver.client.listener.EzyClientAppResponseListener; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyClientAppResponseListeners extends EzyDestroyable { + + @SuppressWarnings("rawtypes") + EzyClientAppResponseListener getListener(Object requestId); + + @SuppressWarnings("rawtypes") + void addListener(Object requestId, EzyClientAppResponseListener listener); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientControllers.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientControllers.java new file mode 100644 index 00000000..6a573c8b --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/EzyClientControllers.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.client.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyClientControllers extends EzyDestroyable { + + Object getController(EzyConstant cmd); + + void addController(EzyConstant cmd, Object ctrl); + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppControllersImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppControllersImpl.java new file mode 100644 index 00000000..d4d5db19 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppControllersImpl.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.client.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.controller.EzyClientAppController; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientAppControllers; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public class EzyClientAppControllersImpl implements EzyClientAppControllers { + + @SuppressWarnings("rawtypes") + protected Map controllers = new ConcurrentHashMap<>(); + + @SuppressWarnings("rawtypes") + @Override + public EzyClientAppController getController(EzyConstant cmd) { + return controllers.get(cmd); + } + + @SuppressWarnings("rawtypes") + @Override + public void addController(EzyConstant cmd, EzyClientAppController ctrl) { + controllers.put(cmd, ctrl); + } + + @Override + public void destroy() { + controllers.clear(); + controllers = null; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyClientAppControllers build() { + EzyClientAppControllersImpl answer = new EzyClientAppControllersImpl(); + return answer; + } + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppResponseListenersImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppResponseListenersImpl.java new file mode 100644 index 00000000..193a6871 --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientAppResponseListenersImpl.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.client.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.listener.EzyClientAppResponseListener; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientAppResponseListeners; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzyClientAppResponseListenersImpl + extends EzyLoggable implements EzyClientAppResponseListeners { + + @SuppressWarnings("rawtypes") + protected Map requests = new ConcurrentHashMap<>(); + + @SuppressWarnings("rawtypes") + @Override + public EzyClientAppResponseListener getListener(Object requestId) { + return requests.get(requestId); + } + + @SuppressWarnings("rawtypes") + @Override + public void addListener(Object requestId, EzyClientAppResponseListener listener) { + requests.put(requestId, listener); + } + + @Override + public void destroy() { + requests.clear(); + requests = null; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + @Override + public EzyClientAppResponseListeners build() { + return new EzyClientAppResponseListenersImpl(); + } + } + +} diff --git a/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientControllersImpl.java b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientControllersImpl.java new file mode 100644 index 00000000..79bcdcaf --- /dev/null +++ b/ezyfox-server-client/src/main/java/com/tvd12/ezyfoxserver/client/wrapper/impl/EzyClientControllersImpl.java @@ -0,0 +1,73 @@ +package com.tvd12.ezyfoxserver.client.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.controller.EzyAccessAppController; +import com.tvd12.ezyfoxserver.client.controller.EzyConnectFailureController; +import com.tvd12.ezyfoxserver.client.controller.EzyConnectSuccessController; +import com.tvd12.ezyfoxserver.client.controller.EzyDisconnectController; +import com.tvd12.ezyfoxserver.client.controller.EzyErrorController; +import com.tvd12.ezyfoxserver.client.controller.EzyHandShakeController; +import com.tvd12.ezyfoxserver.client.controller.EzyLoginController; +import com.tvd12.ezyfoxserver.client.controller.EzyLoginErrorController; +import com.tvd12.ezyfoxserver.client.controller.EzyPongController; +import com.tvd12.ezyfoxserver.client.controller.EzyRequestAppController; +import com.tvd12.ezyfoxserver.client.wrapper.EzyClientControllers; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +import lombok.Setter; + +@Setter +public class EzyClientControllersImpl implements EzyClientControllers { + + protected Map controllers; + + @Override + public Object getController(EzyConstant cmd) { + return controllers.get(cmd); + } + + @Override + public void addController(EzyConstant cmd, Object ctrl) { + controllers.put(cmd, ctrl); + } + + @Override + public void destroy() { + controllers.clear(); + controllers = null; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected Map newControllers() { + Map answer = new ConcurrentHashMap<>(); + answer.put(EzyClientCommand.PONG, new EzyPongController()); + answer.put(EzyClientCommand.ERROR, new EzyErrorController()); + answer.put(EzyClientCommand.CONNECT_SUCCESS, new EzyConnectSuccessController()); + answer.put(EzyClientCommand.CONNECT_FAILURE, EzyConnectFailureController.EMPTY); + answer.put(EzyClientCommand.HANDSHAKE, new EzyHandShakeController()); + answer.put(EzyClientCommand.LOGIN, new EzyLoginController()); + answer.put(EzyClientCommand.LOGIN_ERROR, new EzyLoginErrorController()); + answer.put(EzyClientCommand.APP_ACCESS, new EzyAccessAppController()); + answer.put(EzyClientCommand.DISCONNECT, new EzyDisconnectController()); + answer.put(EzyClientCommand.APP_REQUEST, new EzyRequestAppController()); + return answer; + } + + @Override + public EzyClientControllers build() { + EzyClientControllersImpl answer = new EzyClientControllersImpl(); + answer.setControllers(newControllers()); + return answer; + } + } + +} diff --git a/ezyfox-server-client/src/test/java/com/tvd12/ezyfoxserver/client/testing/EzyClientRunner.java b/ezyfox-server-client/src/test/java/com/tvd12/ezyfoxserver/client/testing/EzyClientRunner.java new file mode 100644 index 00000000..59dc8ef4 --- /dev/null +++ b/ezyfox-server-client/src/test/java/com/tvd12/ezyfoxserver/client/testing/EzyClientRunner.java @@ -0,0 +1,169 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.client.testing; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.client.EzyClient; +import com.tvd12.ezyfoxserver.client.EzyClientStarter; +import com.tvd12.ezyfoxserver.client.cmd.EzySendRequest; +import com.tvd12.ezyfoxserver.client.constants.EzyClientCommand; +import com.tvd12.ezyfoxserver.client.context.EzyClientAppContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContext; +import com.tvd12.ezyfoxserver.client.context.EzyClientContextBuilder; +import com.tvd12.ezyfoxserver.client.controller.EzyClientAppController; +import com.tvd12.ezyfoxserver.client.controller.EzyHandShakeController; +import com.tvd12.ezyfoxserver.client.controller.EzyLoginController; +import com.tvd12.ezyfoxserver.client.entity.EzyClientSession; +import com.tvd12.ezyfoxserver.client.entity.EzySimpleClientUser; +import com.tvd12.ezyfoxserver.client.listener.EzyClientAppResponseListener; +import com.tvd12.ezyfoxserver.client.request.EzyAccessAppRequest; +import com.tvd12.ezyfoxserver.client.request.EzyLoginRequest; +import com.tvd12.ezyfoxserver.client.serialize.EzyRequestSerializer; +import com.tvd12.ezyfoxserver.client.serialize.impl.EzyRequestSerializerImpl; +import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator; + +import lombok.AllArgsConstructor; + +/** + * @author tavandung12 + * + */ +@AllArgsConstructor +public class EzyClientRunner { + + public static void main(String[] args) throws Exception { + if (args.length != 2) + System.err.println(getErrorMessage()); + start(args[0], Integer.parseInt(args[1])); + } + + private static void start(String host, int port) throws Exception { + EzyClientStarter.builder() + .host(host) + .port(port) + .clientContext(newClientContext()) + .codecCreator(new MsgPackCodecCreator()) + .build() + .start(); + } + + protected EzyRequestSerializer newRequestSerializer() { + return EzyRequestSerializerImpl.builder().build(); + } + + private static EzyClientContext newClientContext() { + return new EzyClientContextBuilder() + .setupClient(EzyClientRunner::setupClient) + .build(); + } + + private static void setupClient(EzyClient client) { + + client.addController(EzyClientCommand.HANDSHAKE, new EzyHandShakeController() { + @Override + public void handle(EzyClientContext ctx, EzyClientSession session, EzyArray data) { + super.handle(ctx, session, data); + sendLoginRequest(ctx, session); + } + + protected void sendLoginRequest(EzyContext ctx, EzyClientSession session) { + ctx.get(EzySendRequest.class) + .sender(session) + .request(newLoginRequest()) + .execute(); + } + + protected String getUsername() { + return "dungtv"; + } + + protected String getPassword() { + return "123456"; + } + + protected EzyLoginRequest newLoginRequest() { + return EzyLoginRequest.builder() + .username(getUsername()) + .password(getPassword()) + .data(newLoginInData()) + .build(); + } + + protected EzyData newLoginInData() { + return newArrayBuilder() + .append("1.0.0") + .append("android") + .build(); + } + }); + + client.addController(EzyClientCommand.LOGIN, new EzyLoginController() { + + @Override + protected void processNotReconnect( + EzyClientContext ctx, EzyClientSession session, EzyArray data) { + sendAccessAppsRequest(ctx); + } + + protected void sendAccessAppsRequest(EzyClientContext ctx) { + ctx.get(EzySendRequest.class) + .sender(ctx.getMe()) + .request(newAccessAppRequest()) + .execute(); + } + + protected EzyAccessAppRequest newAccessAppRequest() { + return EzyAccessAppRequest.builder() + .appName("ezyfox-chat") + .data(newAccessAppData()) + .build(); + } + + protected EzyObject newAccessAppData() { + return newObjectBuilder().build(); + } + + }); + + client.addAppController(EzyClientCommand.ACESS_APP_SUCCESS, new EzyClientAppController() { + + @Override + public void handle(EzyClientAppContext ctx, EzySimpleClientUser rev, EzyArray data) { + sendChatMessageRequest(ctx); + sendPluginRequest(ctx); + } + + protected void sendChatMessageRequest(EzyClientAppContext appCtx) { + EzyArray params = EzyEntityFactory.create(EzyArrayBuilder.class).append("nice to meet you!").build(); + for(int i = 0 ; i < 1000 ; i++) + appCtx.sendRequest("1", params); + } + + protected void sendPluginRequest(EzyClientAppContext ctx) { + ctx.sendPluginRequest("ezyfox-auth-plugin", newPluginRequestData()); + } + + protected EzyArray newPluginRequestData() { + return EzyEntityFactory.create(EzyArrayBuilder.class).append(1).append("hello world").build(); + } + + }); + + client.addClientAppResponseListener("1", new EzyClientAppResponseListener() { + @Override + public void execute(EzyClientAppContext ctx, EzyArray params) { + System.out.println("\n\nparams = " + params + "\n\n"); + } + }); + } + private static String getErrorMessage() { + return "Usage: " + EzyClientRunner.class.getSimpleName() + " "; + } + +} diff --git a/ezyfox-server-codec/pom.xml b/ezyfox-server-codec/pom.xml index 82bf0a49..e0b6f472 100644 --- a/ezyfox-server-codec/pom.xml +++ b/ezyfox-server-codec/pom.xml @@ -6,10 +6,23 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-codec - 0.0.2 + 1.0.0 ezyfox-server-codec http://maven.apache.org + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractByTypeSerializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractByTypeSerializer.java new file mode 100644 index 00000000..4a2f4503 --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractByTypeSerializer.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.codec; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.function.EzyParser; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +@SuppressWarnings("rawtypes") +public abstract class EzyAbstractByTypeSerializer implements EzyMessageByTypeSerializer { + + protected Map, Map, EzyParser>> parserss = defaultParserss(); + + @Override + public T serialize(Object value, Class outType) { + return value == null + ? parseNil(outType) + : parseNotNull(value, outType); + } + + protected T parseNotNull(Object value, Class outType) { + Map, EzyParser> parsers = getParsers(value.getClass()); + if(parsers == null) + return parseWithNoParsers(value, outType); + EzyParser parser = parsers.get(outType); + if(parser == null) + return parseWithNoParser(value, outType); + return parseWithParser(parser, value); + } + + @SuppressWarnings("unchecked") + protected T parseWithParser(EzyParser parser, Object value) { + return (T)parser.parse(value); + } + + protected T parseWithNoParsers(Object value, Class outType) { + throw new IllegalArgumentException("has no parse for " + value.getClass()); + } + + protected T parseWithNoParser(Object value, Class outType) { + throw new IllegalArgumentException("has no parse for " + value.getClass() + " and outType " + outType); + } + + protected abstract T parseNil(Class outType); + + protected Map, EzyParser> getParsers(Class type) { + return EzyMaps.getValue(parserss, type); + } + + protected Map, Map, EzyParser>> defaultParserss() { + Map, Map, EzyParser>> map = new ConcurrentHashMap<>(); + addParserss(map); + return map; + } + + protected abstract void addParserss(Map, Map, EzyParser>> parserss); + +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractSerializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractSerializer.java index 7893efe3..5f567993 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractSerializer.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyAbstractSerializer.java @@ -1,50 +1,50 @@ -package com.tvd12.ezyfoxserver.codec; - +package com.tvd12.ezyfoxserver.codec; + import java.util.Map; import java.util.concurrent.ConcurrentHashMap; - -import com.tvd12.ezyfoxserver.function.EzyParser; -import com.tvd12.ezyfoxserver.util.EzyMaps; - -public abstract class EzyAbstractSerializer implements EzyMessageSerializer { - + +import com.tvd12.ezyfoxserver.function.EzyParser; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +public abstract class EzyAbstractSerializer implements EzyMessageSerializer { + protected Map, EzyParser> parsers = defaultParsers(); - - @Override + + @Override public byte[] serialize(Object value) { return value == null - ? parseNil() + ? parseNil() : parseNotNull(value); - } - + } + protected byte[] parseNotNull(Object value) { EzyParser parser = getParser(value.getClass()); if(parser != null) return parseWithParser(parser, value); return parseWithNoParser(value); - - } - + + } + protected byte[] parseWithParser(EzyParser parser, Object value) { return parser.parse(value); - } - + } + protected byte[] parseWithNoParser(Object value) { throw new IllegalArgumentException("has no parse for " + value.getClass()); - } - - protected abstract byte[] parseNil(); - + } + + protected abstract byte[] parseNil(); + protected EzyParser getParser(Class type) { return EzyMaps.getValue(parsers, type); - } - + } + protected Map, EzyParser> defaultParsers() { Map, EzyParser> parsers = new ConcurrentHashMap<>(); addParsers(parsers); return parsers; - } - + } + protected abstract void addParsers(Map, EzyParser> parsers); - -} + +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java new file mode 100644 index 00000000..36fd9b28 --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.codec; + +public interface EzyCodecCreator { + + Object newEncoder(); + + Object newDecoder(int maxRequestSize); + +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessage.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessage.java index 77a29091..cb0d3bc5 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessage.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessage.java @@ -29,7 +29,7 @@ public interface EzyMessage { * @return the length of message's size */ default int getSizeLength() { - return getHeader().isBigSize() ? 4 : 2; + return hasBigSize() ? 4 : 2; } default boolean hasBigSize() { diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageBuilder.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageBuilder.java index 2b2a1af5..7284c16f 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageBuilder.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageBuilder.java @@ -1,73 +1,32 @@ package com.tvd12.ezyfoxserver.codec; -public class EzyMessageBuilder { +public final class EzyMessageBuilder { - // prevent new instance - private EzyMessageBuilder() { - } - - public static MessageBuilder messageBuilder() { - return new MessageBuilder(); - } - - public static MessageHeaderBuilder headerBuilder() { - return new MessageHeaderBuilder(); - } - -} - -class MessageHeaderBuilder { - - private boolean bigSize; - private boolean encrypted; - private boolean compressed; - - public MessageHeaderBuilder bigSize(boolean bigSize) { - this.bigSize = bigSize; - return this; - } - public MessageHeaderBuilder encrypted(boolean encrypted) { - this.encrypted = encrypted; - return this; - } - public MessageHeaderBuilder compressed(boolean compressed) { - this.compressed = compressed; - return this; - } - - public EzyMessageHeader build() { - EzySimpleMessageHeader header = new EzySimpleMessageHeader(); - header.setBigSize(bigSize); - header.setEncrypted(encrypted); - header.setCompressed(compressed); - return header; - } -} - -class MessageBuilder { - private int size; private byte[] content; private EzyMessageHeader header; - public MessageBuilder size(int size) { + public static EzyMessageBuilder newInstance() { + return new EzyMessageBuilder(); + } + + public EzyMessageBuilder size(int size) { this.size = size; return this; } - public MessageBuilder content(byte[] content) { + public EzyMessageBuilder content(byte[] content) { this.content = content; return this; } - public MessageBuilder header(EzyMessageHeader header) { + public EzyMessageBuilder header(EzyMessageHeader header) { this.header = header; return this; } - public MessageBuilder header(MessageHeaderBuilder buider) { - this.header = buider.build(); - return this; + public EzyMessageBuilder header(EzyMessageHeaderBuilder buider) { + return header(buider.build()); } public EzyMessage build() { @@ -78,4 +37,4 @@ public EzyMessage build() { return answer; } -} +} \ No newline at end of file diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageByTypeSerializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageByTypeSerializer.java new file mode 100644 index 00000000..48a95c3f --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageByTypeSerializer.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.codec; + +public interface EzyMessageByTypeSerializer + extends EzyMessageSerializer, EzyObjectByTypeSerializer { +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeader.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeader.java index 32a79621..948fecc2 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeader.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeader.java @@ -23,4 +23,11 @@ public interface EzyMessageHeader { */ boolean isCompressed(); // bit 3 + /** + * Check whether message is text or binary type + * + * @return true is text or false is binary + */ + boolean isText(); // bit 4 + } diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeaderBuilder.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeaderBuilder.java new file mode 100644 index 00000000..b5d62318 --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageHeaderBuilder.java @@ -0,0 +1,42 @@ +package com.tvd12.ezyfoxserver.codec; + +public class EzyMessageHeaderBuilder { + + protected boolean bigSize; + protected boolean encrypted; + protected boolean compressed; + protected boolean text; + + public static EzyMessageHeaderBuilder newInstance() { + return new EzyMessageHeaderBuilder(); + } + + public EzyMessageHeaderBuilder bigSize(boolean bigSize) { + this.bigSize = bigSize; + return this; + } + + public EzyMessageHeaderBuilder encrypted(boolean encrypted) { + this.encrypted = encrypted; + return this; + } + + public EzyMessageHeaderBuilder compressed(boolean compressed) { + this.compressed = compressed; + return this; + } + + public EzyMessageHeaderBuilder text(boolean text) { + this.text = text; + return this; + } + + public EzyMessageHeader build() { + EzySimpleMessageHeader header = new EzySimpleMessageHeader(); + header.setBigSize(bigSize); + header.setEncrypted(encrypted); + header.setCompressed(compressed); + header.setText(text); + return header; + } +} \ No newline at end of file diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageToBytes.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageToBytes.java index ab2aff2e..03b812a3 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageToBytes.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageToBytes.java @@ -2,6 +2,6 @@ public interface EzyMessageToBytes { - T convert(final EzyMessage message, final Class type); + T convert(EzyMessage message); } diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectByTypeSerializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectByTypeSerializer.java new file mode 100644 index 00000000..0cb1f648 --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectByTypeSerializer.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.codec; + +public interface EzyObjectByTypeSerializer extends EzyObjectSerializer { + + T serialize(Object value, Class outType); + + @Override + default byte[] serialize(Object value) { + return serialize(value, byte[].class); + } + +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectDeserializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectDeserializer.java index 4764714e..ea843e25 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectDeserializer.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzyObjectDeserializer.java @@ -2,10 +2,18 @@ import java.nio.ByteBuffer; +import com.tvd12.ezyfoxserver.io.EzyStrings; + public interface EzyObjectDeserializer { - T deserialize(byte[] data); - T deserialize(ByteBuffer buffer); + default T deserialize(byte[] data) { + return deserialize(ByteBuffer.wrap(data)); + } + + default T deserialize(String text) { + return deserialize(EzyStrings.getUtfBytes(text)); + } + } diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageHeader.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageHeader.java index 8fb7acf5..c1536d05 100644 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageHeader.java +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageHeader.java @@ -12,5 +12,6 @@ public class EzySimpleMessageHeader implements EzyMessageHeader { protected boolean bigSize; protected boolean encrypted; protected boolean compressed; + protected boolean text; } diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/exception/EzyMaxRequestSizeException.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/exception/EzyMaxRequestSizeException.java new file mode 100644 index 00000000..470a4975 --- /dev/null +++ b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/exception/EzyMaxRequestSizeException.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.exception; + +public class EzyMaxRequestSizeException extends IllegalStateException { + private static final long serialVersionUID = -3982995135416662086L; + + public EzyMaxRequestSizeException(String msg) { + super(msg); + } + + public EzyMaxRequestSizeException(int size, int maxSize) { + this("size = " + size + " when max size = " + maxSize); + } + +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java deleted file mode 100644 index 99f90160..00000000 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.function; - -public interface EzyDeserializer { - - T deserialize(F value); - -} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java deleted file mode 100644 index b84b05f3..00000000 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.function; - -public interface EzySerializer { - - T serialize(F value); - -} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/util/EzyMaps.java b/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/util/EzyMaps.java deleted file mode 100644 index 465e2d47..00000000 --- a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/util/EzyMaps.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -import java.util.Map; - -public abstract class EzyMaps { - - private EzyMaps() { - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static T getValue(Map map, Class type) { - if(type == Object.class) - return null; - Object answer = map.get(type); - if(answer == null && type.getInterfaces() != null) - answer = getValueOfInterfaces(map, type); - if(answer == null && type.getSuperclass() != null) - answer = getValueOfSuper(map, type); - return (T)answer; - } - - @SuppressWarnings("rawtypes") - private static Object getValueOfSuper(Map map, Class type) { - return getValue(map, type.getSuperclass()); - } - - @SuppressWarnings("rawtypes") - private static Object getValueOfInterfaces(Map map, Class type) { - Object answer = null; - for(Class clazz : type.getInterfaces()) - if((answer = getValue(map, clazz)) != null) - return answer; - return answer; - } - -} diff --git a/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractByTypeSerializerTest.java b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractByTypeSerializerTest.java new file mode 100644 index 00000000..272d18fc --- /dev/null +++ b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractByTypeSerializerTest.java @@ -0,0 +1,89 @@ +package com.tvd12.ezyfoxserver.testing.codec; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyAbstractByTypeSerializer; +import com.tvd12.ezyfoxserver.function.EzyParser; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractByTypeSerializerTest extends BaseTest { + + @Test + public void test() { + EzyAbstractByTypeSerializer serializer = new Serializer(); + assert serializer.serialize(null) == null; + assert serializer.serialize(new String("abc")) != null; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyAbstractByTypeSerializer serializer = new Serializer(); + serializer.serialize(new EzyAbstractByTypeSerializerTest()); + } + + @Test + public void test2() { + EzyAbstractByTypeSerializer serializer = new Serializer1(); + serializer.serialize(new EzyAbstractByTypeSerializerTest()); + } + + public static class Serializer extends EzyAbstractByTypeSerializer { + + @Override + protected T parseNil(Class outType) { + return null; + } + + @SuppressWarnings("rawtypes") + @Override + protected void addParserss(Map, Map, EzyParser>> parserss) { + Map, EzyParser> map = new ConcurrentHashMap<>(); + parserss.put(String.class, map); + map.put(byte[].class, new EzyParser() { + @Override + public byte[] parse(Object input) { + return input.toString().getBytes(); + } + }); + } + + } + + public static class Serializer1 extends EzyAbstractByTypeSerializer { + + @Override + protected T parseNil(Class outType) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + protected T parseWithNoParsers(Object value, Class outType) { + return (T) new byte[] {}; + } + + @SuppressWarnings("unchecked") + @Override + protected T parseWithNoParser(Object value, Class outType) { + return (T) new byte[] {}; + } + + @SuppressWarnings("rawtypes") + @Override + protected void addParserss(Map, Map, EzyParser>> parserss) { + Map, EzyParser> map = new ConcurrentHashMap<>(); + parserss.put(String.class, map); + map.put(byte[].class, new EzyParser() { + @Override + public byte[] parse(Object input) { + return input.toString().getBytes(); + } + }); + } + + } + +} diff --git a/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractSerializerTest.java b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractSerializerTest.java new file mode 100644 index 00000000..7adc491d --- /dev/null +++ b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyAbstractSerializerTest.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.testing.codec; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyAbstractSerializer; +import com.tvd12.ezyfoxserver.function.EzyParser; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractSerializerTest extends BaseTest { + + @Test + public void test() { + EzyAbstractSerializer serializer = new Serializer(); + assert serializer.serialize(null) == null; + assert serializer.serialize(new String("abc")) != null; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyAbstractSerializer serializer = new Serializer(); + serializer.serialize(new EzyAbstractSerializerTest()); + } + + @Test + public void test2() { + EzyAbstractSerializer serializer = new Serializer1(); + serializer.serialize(new EzyAbstractSerializerTest()); + } + + public static class Serializer extends EzyAbstractSerializer { + + @Override + protected byte[] parseNil() { + return null; + } + + @Override + protected void addParsers(Map, EzyParser> parsers) { + parsers.put(String.class, new EzyParser() { + @Override + public byte[] parse(Object input) { + return input.toString().getBytes(); + } + }); + } + + } + + public static class Serializer1 extends EzyAbstractSerializer { + + @Override + protected byte[] parseNil() { + return null; + } + + @Override + protected byte[] parseWithNoParser(Object value) { + return new byte[] {}; + } + + @Override + protected void addParsers(Map, EzyParser> parsers) { + parsers.put(String.class, new EzyParser() { + @Override + public byte[] parse(Object input) { + return input.toString().getBytes(); + } + }); + } + + } + +} \ No newline at end of file diff --git a/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeState1Test.java b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeState1Test.java new file mode 100644 index 00000000..1a2c74ea --- /dev/null +++ b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeState1Test.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing.codec; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.test.base.BaseTest; + +public class EzyDecodeState1Test extends BaseTest { + + @Test + public void test() { + EzyIDecodeState state = EzyDecodeState.PREPARE_MESSAGE; + assert state.getId() == 0; + state = EzyDecodeState.PREPARE_MESSAGE; + state = EzyDecodeState.READ_MESSAGE_HEADER; + state = EzyDecodeState.READ_MESSAGE_SIZE; + state = EzyDecodeState.READ_MESSAGE_CONTENT; + } + +} diff --git a/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeStateTest.java b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeStateTest.java new file mode 100644 index 00000000..dceb0624 --- /dev/null +++ b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyDecodeStateTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.codec; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.test.base.BaseTest; + +public class EzyDecodeStateTest extends BaseTest { + + @Test + public void test() { + EzyIDecodeState state = EzyDecodeState.PREPARE_MESSAGE; + assert state.getId() == 0; + EzyDecodeState.values(); + EzyDecodeState.valueOf("PREPARE_MESSAGE"); + } + +} diff --git a/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyMessageBuilderTest.java b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyMessageBuilderTest.java new file mode 100644 index 00000000..a3cc90e8 --- /dev/null +++ b/ezyfox-server-codec/src/test/java/com/tvd12/ezyfoxserver/testing/codec/EzyMessageBuilderTest.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.testing.codec; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeader; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeaderBuilder; +import com.tvd12.test.base.BaseTest; + +public class EzyMessageBuilderTest extends BaseTest { + + @Test + public void test() { + EzyMessageHeaderBuilder headerBuilder = EzyMessageHeaderBuilder.newInstance() + .bigSize(true) + .compressed(true) + .encrypted(true); + EzyMessage message = EzyMessageBuilder.newInstance() + .size(5) + .content(new byte[] {1, 2, 3, 4, 5}) + .header(headerBuilder) + .build(); + EzyMessageHeader header = message.getHeader(); + assert header.isBigSize(); + assert header.isCompressed(); + assert header.isEncrypted(); + assert message.hasBigSize(); + assert message.getSize() == 5; + assert message.getSizeLength() == 4; + assert message.getContent().length == 5; + } + + @Test + public void test2() { + EzyMessageHeaderBuilder headerBuilder = EzyMessageHeaderBuilder.newInstance() + .bigSize(false) + .compressed(true) + .encrypted(true); + EzyMessage message = EzyMessageBuilder.newInstance() + .size(5) + .content(new byte[] {1, 2, 3, 4, 5}) + .header(headerBuilder) + .build(); + EzyMessageHeader header = message.getHeader(); + assert !header.isBigSize(); + assert header.isCompressed(); + assert header.isEncrypted(); + assert !message.hasBigSize(); + assert message.getSize() == 5; + assert message.getSizeLength() == 2; + assert message.getContent().length == 5; + + message.toString(); + header.toString(); + } + +} diff --git a/ezyfox-server-codec/src/test/resources/AllTests.tng.xml b/ezyfox-server-codec/src/test/resources/AllTests.tng.xml index 1de16472..4a602642 100644 --- a/ezyfox-server-codec/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-codec/src/test/resources/AllTests.tng.xml @@ -1,9 +1,9 @@ - + - + \ No newline at end of file diff --git a/ezyfox-server-common/.gitignore b/ezyfox-server-common/.gitignore new file mode 100644 index 00000000..0d69f59f --- /dev/null +++ b/ezyfox-server-common/.gitignore @@ -0,0 +1 @@ +/util-directories-test/ diff --git a/ezyfox-server-common/pom.xml b/ezyfox-server-common/pom.xml index 8424a53a..971eff30 100644 --- a/ezyfox-server-common/pom.xml +++ b/ezyfox-server-common/pom.xml @@ -6,30 +6,31 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-common - 0.0.2 + 1.0.0 ezyfox-server-common http://maven.apache.org - 0.0.2 - 0.0.1 + 1.0.0 + 1.0.0 - + com.tvd12 - ezyfox-server-codec - ${codec.version} + ezyfox-server-security + ${ezy.security.version} com.tvd12 - ezyfox-server-security - ${security.version} + ezyfox-server-concurrent + ${ezy.concurrent.version} + diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java deleted file mode 100644 index f959941c..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.tvd12.ezyfoxserver; - -public class EzySystem { - - private static EzyEnvironment env; - - static { - env = new EzyEnvironment(); - } - - private EzySystem() { - } - - public static EzyEnvironment getEnv() { - return env; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyArrayBuilder.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyArrayBuilder.java index 0b553a55..7972dcde 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyArrayBuilder.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyArrayBuilder.java @@ -1,11 +1,18 @@ package com.tvd12.ezyfoxserver.builder; -import java.util.Collection; - import com.tvd12.ezyfoxserver.entity.EzyArray; public interface EzyArrayBuilder extends EzyBuilder { + /** + * append item to product + * + * @param the value type + * @param item the item to add + * @return this pointer + */ + EzyArrayBuilder append(T item); + /** * append items to product * @@ -14,7 +21,7 @@ public interface EzyArrayBuilder extends EzyBuilder { * @return this pointer */ @SuppressWarnings("unchecked") - EzyArrayBuilder append(final T... items); + EzyArrayBuilder append(T... items); /** * append items to product @@ -22,7 +29,8 @@ public interface EzyArrayBuilder extends EzyBuilder { * @param items the items to add * @return this pointer */ - EzyArrayBuilder append(final Collection items); + @SuppressWarnings("rawtypes") + EzyArrayBuilder append(Iterable items); /** * build and add constructed item to product @@ -31,7 +39,7 @@ public interface EzyArrayBuilder extends EzyBuilder { * @return this pointer */ @SuppressWarnings("rawtypes") - default EzyArrayBuilder append(final EzyBuilder builder) { + default EzyArrayBuilder append(EzyBuilder builder) { return this.append(builder.build()); } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyObjectBuilder.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyObjectBuilder.java index 48372f62..19a79c37 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyObjectBuilder.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyObjectBuilder.java @@ -13,7 +13,7 @@ public interface EzyObjectBuilder extends EzyBuilder { * @param value the value * @return this pointer */ - EzyObjectBuilder append(final Object key, final Object value); + EzyObjectBuilder append(Object key, Object value); /** * append a map of key value entries to project @@ -22,7 +22,7 @@ public interface EzyObjectBuilder extends EzyBuilder { * @return this pointer */ @SuppressWarnings("rawtypes") - EzyObjectBuilder append(final Map map); + EzyObjectBuilder append(Map map); /** * build a value mapped to the key and add to product @@ -31,7 +31,8 @@ public interface EzyObjectBuilder extends EzyBuilder { * @param builder the builder to build value * @return this pointer */ - default EzyObjectBuilder append(final Object key, final EzyBuilder builder) { + @SuppressWarnings("rawtypes") + default EzyObjectBuilder append(Object key, EzyBuilder builder) { return this.append(key, builder.build()); } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyArrayBuilderImpl.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyArrayBuilderImpl.java index ecb50551..70646797 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyArrayBuilderImpl.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyArrayBuilderImpl.java @@ -1,10 +1,9 @@ package com.tvd12.ezyfoxserver.builder.impl; -import java.util.Collection; - import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.impl.EzyArrayList; +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; import com.tvd12.ezyfoxserver.io.EzyInputTransformer; import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; @@ -13,11 +12,14 @@ public class EzyArrayBuilderImpl implements EzyArrayBuilder { protected EzyArray product; + protected EzyCollectionConverter collectionConverter; public EzyArrayBuilderImpl( EzyInputTransformer inputTransformer, - EzyOutputTransformer outputTransformer) { + EzyOutputTransformer outputTransformer, + EzyCollectionConverter collectionConverter) { super(inputTransformer, outputTransformer); + this.collectionConverter = collectionConverter; this.product = newProduct(); } @@ -25,9 +27,16 @@ protected EzyArray newProduct() { EzyArrayList answer = new EzyArrayList(); answer.setInputTransformer(inputTransformer); answer.setOutputTransformer(outputTransformer); + answer.setCollectionConverter(collectionConverter); return answer; } + @Override + public EzyArrayBuilder append(T item) { + this.product.add(item); + return this; + } + /* * (non-Javadoc) * @see com.tvd12.ezyfoxserver.builder.EzyArrayBuilder#append(java.lang.Object[]) @@ -43,8 +52,9 @@ public EzyArrayBuilder append(T... items) { * (non-Javadoc) * @see com.tvd12.ezyfoxserver.builder.EzyArrayBuilder#append(java.util.Collection) */ + @SuppressWarnings("rawtypes") @Override - public EzyArrayBuilder append(Collection items) { + public EzyArrayBuilder append(Iterable items) { this.product.add(items); return this; } @@ -58,10 +68,19 @@ public EzyArray build() { return product; } - public static class Creator extends AbstractCreator { + public static class Creator extends AbstractCreator { + + protected EzyCollectionConverter collectionConverter; + + public Creator collectionConverter(EzyCollectionConverter converter) { + this.collectionConverter = converter; + return this; + } + @Override public EzyArrayBuilderImpl create() { - return new EzyArrayBuilderImpl(inputTransformer, outputTransformer); + return new EzyArrayBuilderImpl( + inputTransformer, outputTransformer, collectionConverter); } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyInOutTransformerNeeder.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyInOutTransformerNeeder.java index 2f20832c..55dca8b9 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyInOutTransformerNeeder.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyInOutTransformerNeeder.java @@ -16,22 +16,30 @@ public EzyInOutTransformerNeeder( this.outputTransformer = outputTransformer; } - public static abstract class AbstractCreator

+ public static abstract class AbstractCreator< + P extends EzyInOutTransformerNeeder, + C extends AbstractCreator + > implements EzyCreation

{ protected EzyInputTransformer inputTransformer; protected EzyOutputTransformer outputTransformer; - public AbstractCreator

inputTransformer(EzyInputTransformer inputTransformer) { + public C inputTransformer(EzyInputTransformer inputTransformer) { this.inputTransformer = inputTransformer; - return this; + return getThis(); } - public AbstractCreator

outputTransformer(EzyOutputTransformer outputTransformer) { + public C outputTransformer(EzyOutputTransformer outputTransformer) { this.outputTransformer = outputTransformer; - return this; + return getThis(); } @Override public abstract P create(); + + @SuppressWarnings("unchecked") + protected C getThis() { + return (C)this; + } } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyObjectBuilderImpl.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyObjectBuilderImpl.java index c83f23c8..471688c2 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyObjectBuilderImpl.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyObjectBuilderImpl.java @@ -58,7 +58,7 @@ public EzyObject build() { return this.product; } - public static class Creator extends AbstractCreator { + public static class Creator extends AbstractCreator { @Override public EzyObjectBuilderImpl create() { return new EzyObjectBuilderImpl(inputTransformer, outputTransformer); diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java deleted file mode 100644 index 333a6e2d..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.tvd12.ezyfoxserver.concurrent; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; - -public abstract class EzyExecutors { - - private EzyExecutors() { - } - - public static ScheduledExecutorService newScheduledThreadPool( - final int corePoolSize, final String threadName) { - return Executors.newScheduledThreadPool(corePoolSize, newThreadFactory(threadName)); - } - - public static ExecutorService newFixedThreadPool( - final int nThreads, final String threadName) { - return Executors.newFixedThreadPool(nThreads, newThreadFactory(threadName)); - } - - public static ExecutorService newSingleThreadExecutor( - final String threadName) { - return Executors.newSingleThreadExecutor(newThreadFactory(threadName)); - } - - public static ScheduledExecutorService newSingleThreadScheduledExecutor( - final String threadName) { - return Executors.newSingleThreadScheduledExecutor(newThreadFactory(threadName)); - } - - public static EzyThreadFactory newThreadFactory(final String poolName) { - return newThreadFactory(poolName, false, Thread.NORM_PRIORITY); - } - - public static EzyThreadFactory newThreadFactory( - final String poolName, final int priority) { - return newThreadFactory(poolName, false, priority); - } - - public static EzyThreadFactory newThreadFactory( - final String poolName, final boolean daemon) { - return newThreadFactory(poolName, daemon, Thread.NORM_PRIORITY); - } - - public static EzyThreadFactory newThreadFactory( - final String poolName, final boolean daemon, final int priority) { - return EzyThreadFactory.builder() - .daemon(daemon) - .priority(priority) - .poolName(poolName) - .build(); - } -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java deleted file mode 100644 index 04a486ef..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.tvd12.ezyfoxserver.constant; - -import java.util.concurrent.atomic.AtomicInteger; - -public interface EzyConstant { - - // the counter utility - AtomicInteger COUNTER = new AtomicInteger(0); - - /** - * Get constant id - * - * @return the constant id - */ - int getId(); - - /** - * Get constant name - * - * @return the constant name - */ - default String getName() { - return getClass().getSimpleName() + "-" + getId(); - } - - /** - * Create new constant - * - * @return a constant - */ - static EzyConstant one() { - return one(COUNTER.incrementAndGet()); - } - - /** - * Create new constant with id - * - * @param id the constant id - * @return a constant - */ - static EzyConstant one(int id) { - return new EzyConstant() { - @Override - public int getId() { - return id; - } - }; - }; - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionAdapter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionAdapter.java deleted file mode 100644 index 9e80bae6..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionAdapter.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.delegate; - -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.util.EzyLoggable; - -public class EzySessionAdapter extends EzyLoggable implements EzySessionDelegate { - - @Override - public void onSessionReturned(EzyConstant reason) { - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java deleted file mode 100644 index 0c1e8822..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.tvd12.ezyfoxserver.delegate; - -public interface EzySessionDelegate extends EzySessionRemoveDelegate { - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyArray.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyArray.java index 82fee22f..6a24a2ee 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyArray.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyArray.java @@ -7,7 +7,15 @@ public interface EzyArray extends EzyRoArray { /** - * Add values to array + * Add item to array + * + * @param the value type + * @param item the item to add + */ + void add(T item); + + /** + * Add items to array * * @param the value type * @param items the items to add @@ -16,7 +24,7 @@ public interface EzyArray extends EzyRoArray { void add(T... items); /** - * Add values to array + * Add items to array * * @param items the items to add */ diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyCloseable.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyCloseable.java deleted file mode 100644 index f5399689..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyCloseable.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzyCloseable { - - void close(); - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDestroyable.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDestroyable.java deleted file mode 100644 index b2622e8d..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyDestroyable.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzyDestroyable { - - void destroy(); - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyEntity.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyEntity.java index 639350df..868ca4ec 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyEntity.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyEntity.java @@ -4,6 +4,8 @@ import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; +import com.tvd12.ezyfoxserver.util.EzyProperties; + /** * Each model in application should have properties, and we think key/value is good idea * diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyInitable.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyInitable.java deleted file mode 100644 index fdf8b270..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyInitable.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzyInitable { - - void init(); - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyLifecycle.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyLifecycle.java deleted file mode 100644 index bd698439..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyLifecycle.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzyLifecycle extends EzyInitable, EzyDestroyable { - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoArray.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoArray.java index e0fc5fa8..9b58a359 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoArray.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoArray.java @@ -14,7 +14,7 @@ public interface EzyRoArray extends EzyData { T get(int index); /** - * Get value by index + * Get and cast value by index * * @param the value * @param index the index @@ -23,6 +23,25 @@ public interface EzyRoArray extends EzyData { */ T get(int index, Class type); + /** + * Get value by index but not cast + * + * @param the value + * @param index the index + * @param type the value type + * @return the object value + */ + @SuppressWarnings("rawtypes") + Object getValue(int index, Class type); + + /** + * Check if value in the index is not null + * + * @param index the index + * @return true or false + */ + boolean isNotNullValue(int index); + /** * Get new array * @@ -37,6 +56,13 @@ public interface EzyRoArray extends EzyData { */ int size(); + /** + * @return is empty or not + */ + default boolean isEmpty() { + return size() == 0; + } + /** * @param type of value * @return covert this array to list @@ -52,9 +78,10 @@ public interface EzyRoArray extends EzyData { /** * @param the array type + * @param the return type * @param type type array type * @return the array value */ - T toArray(Class type); + A toArray(Class type); } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoObject.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoObject.java index f58ce52b..5a069faf 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoObject.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoObject.java @@ -25,7 +25,9 @@ public interface EzyRoObject extends EzyData { * * @return true or false */ - boolean isEmpty(); + default boolean isEmpty() { + return size() == 0; + } /** * @see java.util.Map#containsKey(java.lang.Object) @@ -35,6 +37,14 @@ public interface EzyRoObject extends EzyData { */ boolean containsKey(Object key); + /** + * check contains key and not null value mapped to the key + * + * @param key the key + * @return true or false + */ + boolean isNotNullValue(Object key); + /** * @see java.util.Map#get(java.lang.Object) * @@ -52,10 +62,20 @@ public interface EzyRoObject extends EzyData { * * @param the type * @param key key - * @param clazz type of value + * @param type type of value * @return a value */ - V get(Object key, Class clazz); + V get(Object key, Class type); + + /** + * get but not cast + * + * @param key the key + * @param type the value type + * @return object value + */ + @SuppressWarnings("rawtypes") + Object getValue(Object key, Class type); /** * @see java.util.Map#keySet() diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java deleted file mode 100644 index 33fcaccb..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzySender { - - void send(EzyData data); - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyStartable.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyStartable.java deleted file mode 100644 index 4654c255..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyStartable.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -public interface EzyStartable { - - void start() throws Exception; - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyArrayList.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyArrayList.java index 32ee8999..19a213b5 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyArrayList.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyArrayList.java @@ -8,9 +8,9 @@ import java.util.function.Consumer; import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; import com.tvd12.ezyfoxserver.io.EzyInputTransformer; import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; -import com.tvd12.ezyfoxserver.util.EzyLiteCollectionConverter; import lombok.Setter; @@ -18,16 +18,14 @@ public class EzyArrayList implements EzyArray { private static final long serialVersionUID = 5952111146742741007L; - protected ArrayList list; + protected ArrayList list = new ArrayList<>(); @Setter protected transient EzyInputTransformer inputTransformer; @Setter protected transient EzyOutputTransformer outputTransformer; - - { - list = new ArrayList<>(); - } + @Setter + protected transient EzyCollectionConverter collectionConverter; public EzyArrayList() { } @@ -48,7 +46,26 @@ public T get(int index) { */ @Override public T get(int index, Class type) { - return (T) transformOutput(list.get(index), type); + return (T) getValue(index, type); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.entity.EzyRoArray#getValue(int, java.lang.Class) + */ + @SuppressWarnings("rawtypes") + @Override + public Object getValue(int index, Class type) { + return transformOutput(list.get(index), type); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.entity.EzyRoArray#isNotNullIndex(int) + */ + @Override + public boolean isNotNullValue(int index) { + return index < size() ? list.get(index) != null : false; } /* @@ -66,7 +83,7 @@ public EzyArray sub(int fromIndex, int toIndex) { */ @Override public void add(T... items) { - this.add(Arrays.asList(items)); + add(Arrays.asList(items)); } /* @@ -75,7 +92,7 @@ public void add(T... items) { */ @Override public void add(Collection items) { - list.addAll(items); + items.forEach(this::add); } /* @@ -87,6 +104,15 @@ public int size() { return list.size(); } + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.entity.EzyRoArray#isEmpty() + */ + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + /* * (non-Javadoc) * @see com.tvd12.ezyfoxserver.entity.EzyArray#set(int, java.lang.Object) @@ -130,7 +156,7 @@ public Iterator iterator() { @SuppressWarnings("rawtypes") @Override public List toList() { - return list; + return new ArrayList<>(list); } /* @@ -147,10 +173,8 @@ public List toList(Class type) { * @see com.tvd12.ezyfoxserver.entity.EzyRoArray#toArray(java.lang.Class) */ @Override - public T toArray(Class type) { - if(!type.isArray()) - throw new IllegalArgumentException(type + " is not array type"); - return EzyLiteCollectionConverter.toArray(list, type); + public A toArray(Class type) { + return getCollectionConverter().toArray(list, type); } /* @@ -160,7 +184,12 @@ public T toArray(Class type) { @SuppressWarnings("rawtypes") @Override public Object clone() throws CloneNotSupportedException { - return new EzyArrayList((Collection) list.clone()); + super.clone(); + EzyArrayList clone = new EzyArrayList((Collection) list.clone()); + clone.setInputTransformer(inputTransformer); + clone.setOutputTransformer(outputTransformer); + clone.setCollectionConverter(getCollectionConverter()); + return clone; } /* @@ -182,10 +211,9 @@ public EzyArray duplicate() { * @param item the item * @return add successful or not */ - protected boolean add(Object item) { - if(item == null) - return list.add(item); - return list.add(transformInput(item)); + @Override + public void add(Object item) { + list.add(transformInput(item)); } /** @@ -218,5 +246,9 @@ private Object transformOutput(Object output, Class type) { public String toString() { return list.toString(); } + + protected EzyCollectionConverter getCollectionConverter() { + return collectionConverter; + } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyHashMap.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyHashMap.java index 10113920..d007a772 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyHashMap.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/impl/EzyHashMap.java @@ -16,15 +16,19 @@ public class EzyHashMap implements EzyObject { private static final long serialVersionUID = 2273868568933801751L; - protected HashMap map; + protected HashMap map = new HashMap<>(); @Setter protected transient EzyInputTransformer inputTransformer; @Setter protected transient EzyOutputTransformer outputTransformer; - { - map = new HashMap<>(); + public EzyHashMap() { + } + + @SuppressWarnings("rawtypes") + public EzyHashMap(Map map) { + this.map.putAll(map); } /* @@ -33,8 +37,6 @@ public class EzyHashMap implements EzyObject { */ @Override public V put(Object key, Object value) { - if(key == null) - throw new IllegalArgumentException("key can't be null"); return (V) map.put(key, transformInput(value)); } @@ -54,8 +56,18 @@ public void putAll(Map m) { * @see com.tvd12.ezyfoxserver.entity.EzyRoObject#get(java.lang.Object, java.lang.Class) */ @Override - public V get(Object key, Class clazz) { - return (V) transformOutput(map.get(key), clazz); + public V get(Object key, Class type) { + return (V) getValue(key, type); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.entity.EzyRoObject#getValue(java.lang.Object, java.lang.Class) + */ + @SuppressWarnings("rawtypes") + @Override + public Object getValue(Object key, Class type) { + return transformOutput(map.get(key), type); } /* @@ -102,6 +114,15 @@ public boolean isEmpty() { public boolean containsKey(Object key) { return map.containsKey(key); } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.entity.EzyRoObject#isNotNullKey(java.lang.Object) + */ + @Override + public boolean isNotNullValue(Object key) { + return map.get(key) != null; + } /* * (non-Javadoc) @@ -146,7 +167,7 @@ public void clear() { @SuppressWarnings("rawtypes") @Override public Map toMap() { - return map; + return new HashMap<>(map); } /* @@ -155,10 +176,10 @@ public Map toMap() { */ @Override public Object clone() throws CloneNotSupportedException { - EzyHashMap clone = new EzyHashMap(); + super.clone(); + EzyHashMap clone = new EzyHashMap(map); clone.setInputTransformer(inputTransformer); clone.setOutputTransformer(outputTransformer); - clone.map.putAll(map); return clone; } @@ -175,12 +196,12 @@ public EzyObject duplicate() { } } - private Object transformInput(final Object input) { + private Object transformInput(Object input) { return inputTransformer.transform(input); } @SuppressWarnings("rawtypes") - private Object transformOutput(final Object output, final Class type) { + private Object transformOutput(Object output, Class type) { return outputTransformer.transform(output, type); } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyBuilderFactory.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyBuilderFactory.java deleted file mode 100644 index 060d283e..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyBuilderFactory.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.tvd12.ezyfoxserver.factory; - -public interface EzyBuilderFactory extends EzyCreator { - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyCreator.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyCreator.java deleted file mode 100644 index da4cfbf8..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyCreator.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.tvd12.ezyfoxserver.factory; - -public interface EzyCreator { - - /** - * create a product - * - * @param the clazz type - * @param productType the product type - * @return the created product - */ - T create(Class productType); - - /** - * check whether this creator able to create the product with type - * - * @param the clazz type - * @param productType the product type - * @return true of false - */ - boolean creatable(Class productType); - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityBuilderCreator.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityBuilderCreator.java new file mode 100644 index 00000000..a45abf0a --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityBuilderCreator.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.factory; + +public interface EzyEntityBuilderCreator { + + /** + * create a product + * + * @param the clazz type + * @param productType the product type + * @return the created product + */ + T create(Class productType); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityFactory.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityFactory.java index 50279b14..58fe8def 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityFactory.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyEntityFactory.java @@ -1,39 +1,16 @@ package com.tvd12.ezyfoxserver.factory; -import com.tvd12.ezyfoxserver.factory.impl.EzyBuilderFactoryImpl; -import com.tvd12.ezyfoxserver.io.EzyLiteOutputTransformer; -import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; +public final class EzyEntityFactory { -public abstract class EzyEntityFactory { - - private static final BuilderFactory BUILDER_FACTORY; - - static { - BUILDER_FACTORY = new BuilderFactory(); - } + private static final EzyEntityBuilderCreator CREATOR + = new EzySimpleEntityBuilderCreator(); private EzyEntityFactory() { + // do nothing } public static T create(Class productType) { - if(BUILDER_FACTORY.creatable(productType)) - return BUILDER_FACTORY.create(productType); - throw new IllegalArgumentException("has no creator for " + productType); - } - -} - -class BuilderFactory extends EzyBuilderFactoryImpl { - - private static final EzyOutputTransformer OUTPUT_TRANSFORMER; - - static { - OUTPUT_TRANSFORMER = new EzyLiteOutputTransformer(); - } - - @Override - protected EzyOutputTransformer getOutputTransformer() { - return OUTPUT_TRANSFORMER; + return CREATOR.create(productType); } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyFactory.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyFactory.java deleted file mode 100644 index 024b9a69..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.tvd12.ezyfoxserver.factory; - -import java.util.ArrayList; -import java.util.List; - -import com.tvd12.ezyfoxserver.factory.impl.EzyBuilderFactoryImpl; - -public abstract class EzyFactory { - - private static final List CREATORS; - - static { - CREATORS = newCreators(); - } - - private EzyFactory() { - // do nothing - } - - public static T create(Class productType) { - for(EzyCreator creator : CREATORS) - if(creator.creatable(productType)) - return creator.create(productType); - throw new IllegalArgumentException("has no creator for " + productType); - } - - private static final List newCreators() { - List answer = new ArrayList<>(); - answer.add(new EzyBuilderFactoryImpl()); - return answer; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyLiteEntityFactory.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyLiteEntityFactory.java new file mode 100644 index 00000000..96cf00aa --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzyLiteEntityFactory.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.factory; + +public final class EzyLiteEntityFactory { + + private static final EzyEntityBuilderCreator CREATOR + = new EzySimpleLiteEntityBuilderCreator(); + + private EzyLiteEntityFactory() { + } + + public static T create(Class productType) { + return CREATOR.create(productType); + } + +} \ No newline at end of file diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleEntityBuilderCreator.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleEntityBuilderCreator.java new file mode 100644 index 00000000..4489daee --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleEntityBuilderCreator.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.factory; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.builder.impl.EzyArrayBuilderImpl; +import com.tvd12.ezyfoxserver.builder.impl.EzyObjectBuilderImpl; +import com.tvd12.ezyfoxserver.concurrent.EzyLazyInitializer; +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzyInputTransformer; +import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzySimpleCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzySimpleInputTransformer; +import com.tvd12.ezyfoxserver.io.EzySimpleOutputTransformer; + +public class EzySimpleEntityBuilderCreator implements EzyEntityBuilderCreator { + + private static final EzyInputTransformer INPUT_TRANSFORMER + = new EzySimpleInputTransformer(); + private static final EzyOutputTransformer OUTPUT_TRANSFORMER + = new EzySimpleOutputTransformer(); + private static final EzyCollectionConverter COLLECTION_CONVERTER + = new EzySimpleCollectionConverter(); + + @SuppressWarnings("rawtypes") + private EzyLazyInitializer> suppliers + = new EzyLazyInitializer<>(this::defaultSuppliers); + + @SuppressWarnings("unchecked") + @Override + public T create(Class productType) { + return (T) getSuppliers().get(productType).get(); + } + + @SuppressWarnings("rawtypes") + protected Map getSuppliers() { + return suppliers.get(); + } + + protected EzyInputTransformer getInputTransformer() { + return INPUT_TRANSFORMER; + } + + protected EzyOutputTransformer getOutputTransformer() { + return OUTPUT_TRANSFORMER; + } + + protected EzyCollectionConverter getCollectionConverter() { + return COLLECTION_CONVERTER; + } + + @SuppressWarnings("rawtypes") + private final Map defaultSuppliers() { + Map answer = new ConcurrentHashMap<>(); + answer.put(EzyObjectBuilder.class, () -> { + return new EzyObjectBuilderImpl.Creator() + .inputTransformer(getInputTransformer()) + .outputTransformer(getOutputTransformer()) + .create(); + }); + answer.put(EzyArrayBuilder.class, () -> { + return new EzyArrayBuilderImpl.Creator() + .inputTransformer(getInputTransformer()) + .outputTransformer(getOutputTransformer()) + .collectionConverter(getCollectionConverter()) + .create(); + }); + return answer; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleLiteEntityBuilderCreator.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleLiteEntityBuilderCreator.java new file mode 100644 index 00000000..4219994e --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/EzySimpleLiteEntityBuilderCreator.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.factory; + +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzyLiteCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzyLiteOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; + +public class EzySimpleLiteEntityBuilderCreator extends EzySimpleEntityBuilderCreator { + + private static final EzyOutputTransformer OUTPUT_TRANSFORMER + = new EzyLiteOutputTransformer(); + private static final EzyCollectionConverter COLLECTION_CONVERTER + = new EzyLiteCollectionConverter(OUTPUT_TRANSFORMER); + + @Override + protected EzyOutputTransformer getOutputTransformer() { + return OUTPUT_TRANSFORMER; + } + + @Override + protected EzyCollectionConverter getCollectionConverter() { + return COLLECTION_CONVERTER; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/impl/EzyBuilderFactoryImpl.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/impl/EzyBuilderFactoryImpl.java deleted file mode 100644 index c9cecd54..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/factory/impl/EzyBuilderFactoryImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.tvd12.ezyfoxserver.factory.impl; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; -import com.tvd12.ezyfoxserver.builder.impl.EzyArrayBuilderImpl; -import com.tvd12.ezyfoxserver.builder.impl.EzyObjectBuilderImpl; -import com.tvd12.ezyfoxserver.concurrent.EzyLazyInitializer; -import com.tvd12.ezyfoxserver.factory.EzyBuilderFactory; -import com.tvd12.ezyfoxserver.io.EzyInputTransformer; -import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; -import com.tvd12.ezyfoxserver.io.EzySimpleInputTransformer; -import com.tvd12.ezyfoxserver.io.EzySimpleOutputTransformer; - -public class EzyBuilderFactoryImpl implements EzyBuilderFactory { - - @SuppressWarnings("rawtypes") - private EzyLazyInitializer> suppliers; - - private static final EzyInputTransformer INPUT_TRANSFORMER; - private static final EzyOutputTransformer OUTPUT_TRANSFORMER; - - { - suppliers = new EzyLazyInitializer<>(this::defaultSuppliers); - } - - static { - INPUT_TRANSFORMER = new EzySimpleInputTransformer(); - OUTPUT_TRANSFORMER = new EzySimpleOutputTransformer(); - } - - @SuppressWarnings("unchecked") - @Override - public T create(Class productType) { - return (T) getSuppliers().get(productType).get(); - } - - @Override - public boolean creatable(Class productType) { - return getSuppliers().containsKey(productType); - } - - @SuppressWarnings("rawtypes") - protected Map getSuppliers() { - return suppliers.get(); - } - - protected EzyInputTransformer getInputTransformer() { - return INPUT_TRANSFORMER; - } - - protected EzyOutputTransformer getOutputTransformer() { - return OUTPUT_TRANSFORMER; - } - - @SuppressWarnings("rawtypes") - private final Map defaultSuppliers() { - Map answer = new ConcurrentHashMap<>(); - answer.put(EzyObjectBuilder.class, () -> { - return new EzyObjectBuilderImpl.Creator() - .inputTransformer(getInputTransformer()) - .outputTransformer(getOutputTransformer()) - .create(); - }); - answer.put(EzyArrayBuilder.class, () -> { - return new EzyArrayBuilderImpl.Creator() - .inputTransformer(getInputTransformer()) - .outputTransformer(getOutputTransformer()) - .create(); - }); - return answer; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java deleted file mode 100644 index e56860b2..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.tvd12.ezyfoxserver.function; - -import java.util.function.Function; - -public interface EzyNumber extends Function { -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java deleted file mode 100644 index ea600023..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.tvd12.ezyfoxserver.helper; - -import com.tvd12.ezyfoxserver.function.EzyInitialize; - -public class EzyLazyInitHelper { - - private EzyLazyInitHelper() { - } - - public static T init(Object context, EzyInitialize initer) { - return init(context, null, initer); - } - - public static T init(Object context, T currentValue, EzyInitialize initer) { - if(currentValue == null) { - synchronized (context) { - if(currentValue == null) { - return initer.init(); - } - } - } - return currentValue; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java deleted file mode 100644 index b8569d3a..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -public abstract class EzyArrays { - - private EzyArrays() { - } - - public static void copy(byte[] from, byte[] to, int toPos) { - for(int i = 0 ; i < from.length ; i++) - to[toPos + i] = from[i]; - } - - public static byte[] merge(byte first, byte[] other) { - byte[] bytes = new byte[other.length + 1]; - bytes[0] = first; - for(int i = 0 ; i < other.length ; i++) - bytes[i + 1] = other[i]; - return bytes; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollectionConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollectionConverter.java new file mode 100644 index 00000000..b0808c74 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollectionConverter.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Collection; + +@SuppressWarnings({"rawtypes"}) +public interface EzyCollectionConverter { + + T toArray(Collection coll, Class type); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java deleted file mode 100644 index 0caab064..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.nio.ByteBuffer; - -public abstract class EzyInts { - - private EzyInts() { - } - - public static int bin2int(int length) { - return EzyMath.bin2int(length); - } - - public static int bin2int(byte[] bytes) { - return EzyMath.bin2int(bytes); - } - - public static int bin2uint(byte[] bytes) { - return EzyMath.bin2uint(bytes); - } - - public static int bin2int(ByteBuffer buffer, int size) { - return bin2int(EzyBytes.copy(buffer, size)); - } - - public static int bin2uint(ByteBuffer buffer, int size) { - return bin2uint(EzyBytes.copy(buffer, size)); - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteCollectionConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteCollectionConverter.java new file mode 100644 index 00000000..e5da7526 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteCollectionConverter.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Collection; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +@SuppressWarnings({"rawtypes"}) +public class EzyLiteCollectionConverter extends EzySimpleCollectionConverter { + + private final EzyOutputTransformer outputTransformer; + + @SuppressWarnings("unchecked") + @Override + protected T toArray(Object array, Class type) { + if(array instanceof EzyArray) + return toArray(((EzyArray)array).toList(), type.getComponentType()); + if(array instanceof Collection) + return toArray((Collection)array, type.getComponentType()); + return (T) outputTransformer.transform(array, type); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteOutputTransformer.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteOutputTransformer.java index 4a92eaf9..30e801f1 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteOutputTransformer.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLiteOutputTransformer.java @@ -1,109 +1,55 @@ package com.tvd12.ezyfoxserver.io; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.byteArrayToCharArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.toByteWrapperArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.toCharWrapperArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.byteArrayToCharArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.toByteWrapperArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.toCharWrapperArray; -import java.io.Serializable; -import java.text.ParseException; -import java.util.Date; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.lang3.time.FastDateFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.EzyEnvironment; -import com.tvd12.ezyfoxserver.EzySystem; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyObject; import com.tvd12.ezyfoxserver.function.EzyToObject; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; -public class EzyLiteOutputTransformer implements EzyOutputTransformer, Serializable { - private static final long serialVersionUID = 8067491929651725682L; - - @SuppressWarnings("rawtypes") - private static final Map TRANSFORMER; - - static { - TRANSFORMER = defaultTransformers(); - } +public class EzyLiteOutputTransformer extends EzySimpleOutputTransformer { + private static final long serialVersionUID = -3934914866478350107L; - @SuppressWarnings("rawtypes") @Override - public Object transform(Object value, Class type) { - return value == null - ? transformNullValue(value) - : transformNonNullValue(value, type); - } - - protected Object transformNullValue(Object value) { - return value; - } - - @SuppressWarnings("rawtypes") - protected Object transformNonNullValue(Object value, Class type) { - return transformNonNullValue(value, type, getTransformers()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - protected Object transformNonNullValue( - Object value, Class type, Map transformers) { - if(transformers.containsKey(type)) - return transformers.get(type).transform(value); - return value; - } - @SuppressWarnings("rawtypes") - protected Map getTransformers() { - return TRANSFORMER; - } - - private static String getDateFormatPattern() { - return EzySystem.getEnv().getProperty(EzyEnvironment.DATE_FORMAT_PATTERN); - } - - @SuppressWarnings("rawtypes") - private static Map - defaultTransformers() { - Map answer = new ConcurrentHashMap<>(); - - //primitive type + protected void addPrimitiveTransformers(Map answer) { answer.put(boolean.class, new EzyToObject() { @Override public Object transform(Boolean value) { return value; } }); - answer.put(byte.class, new EzyToObject() { + answer.put(byte.class, new EzyToObject() { @Override - public Object transform(Integer value) { + public Object transform(Number value) { return value.byteValue(); } }); - answer.put(char.class, new EzyToObject() { + answer.put(char.class, new EzyToObject() { @Override - public Object transform(Integer value) { - return (char)value.intValue(); + public Object transform(Object value) { + return EzyNumbersConverter.objectToChar(value); } }); - answer.put(double.class, new EzyToObject() { + answer.put(double.class, new EzyToObject() { @Override - public Object transform(Double value) { - return value; + public Object transform(Number value) { + return value.doubleValue(); } }); - answer.put(float.class, new EzyToObject() { + answer.put(float.class, new EzyToObject() { @Override - public Object transform(Float value) { - return value; + public Object transform(Number value) { + return value.floatValue(); } }); - answer.put(int.class, new EzyToObject() { + answer.put(int.class, new EzyToObject() { @Override - public Object transform(Integer value) { - return value; + public Object transform(Number value) { + return value.intValue(); } }); answer.put(long.class, new EzyToObject() { @@ -112,48 +58,51 @@ public Object transform(Number value) { return value.longValue(); } }); - answer.put(short.class, new EzyToObject() { + answer.put(short.class, new EzyToObject() { @Override - public Object transform(Integer value) { + public Object transform(Number value) { return value.shortValue(); } }); - - //primitive type + } + + @Override + @SuppressWarnings("rawtypes") + protected void addWrapperTransformers(Map answer) { answer.put(Boolean.class, new EzyToObject() { @Override public Object transform(Boolean value) { return value; } }); - answer.put(Byte.class, new EzyToObject() { + answer.put(Byte.class, new EzyToObject() { @Override - public Object transform(Integer value) { + public Object transform(Number value) { return value.byteValue(); } }); - answer.put(Character.class, new EzyToObject() { + answer.put(Character.class, new EzyToObject() { @Override - public Object transform(Integer value) { - return (char)value.intValue(); + public Object transform(Object value) { + return EzyNumbersConverter.objectToChar(value); } }); - answer.put(Double.class, new EzyToObject() { + answer.put(Double.class, new EzyToObject() { @Override - public Object transform(Double value) { - return value; + public Object transform(Number value) { + return value.doubleValue(); } }); - answer.put(Float.class, new EzyToObject() { + answer.put(Float.class, new EzyToObject() { @Override - public Object transform(Float value) { - return value; + public Object transform(Number value) { + return value.floatValue(); } }); - answer.put(Integer.class, new EzyToObject() { + answer.put(Integer.class, new EzyToObject() { @Override - public Object transform(Integer value) { - return value; + public Object transform(Number value) { + return value.intValue(); } }); answer.put(Long.class, new EzyToObject() { @@ -162,9 +111,9 @@ public Object transform(Number value) { return value.longValue(); } }); - answer.put(Short.class, new EzyToObject() { + answer.put(Short.class, new EzyToObject() { @Override - public Object transform(Integer value) { + public Object transform(Number value) { return value.shortValue(); } }); @@ -174,142 +123,130 @@ public Object transform(String value) { return value; } }); - - //primitive array + } + + @SuppressWarnings("rawtypes") + @Override + protected void addPrimitiveArrayTransformers(Map answer) { answer.put(boolean[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(boolean[].class); + return value.toArray(boolean.class); } }); - answer.put(byte[].class, new EzyToObject() { + answer.put(byte[].class, new EzyToObject() { @Override - public Object transform(byte[] value) { - return value; + public Object transform(Object value) { + if(value instanceof byte[]) + return value; + if(value instanceof String) + return EzyBase64.decode((String)value); + return ((EzyArray)value).toArray(byte.class); } }); - answer.put(char[].class, new EzyToObject() { + answer.put(char[].class, new EzyToObject() { @Override - public Object transform(byte[] value) { - return byteArrayToCharArray(value); + public Object transform(Object value) { + if(value instanceof byte[]) + return byteArrayToCharArray((byte[])value); + if(value instanceof String) + return ((String)value).toCharArray(); + return ((EzyArray)value).toArray(char.class); } }); answer.put(double[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(double[].class); + return value.toArray(double.class); } }); answer.put(float[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(float[].class); + return value.toArray(float.class); } }); answer.put(int[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(int[].class); + return value.toArray(int.class); } }); answer.put(long[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(long[].class); + return value.toArray(long.class); } }); answer.put(short[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(short[].class); + return value.toArray(short.class); } }); answer.put(String[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(String[].class); + return value.toArray(String.class); } }); - - //wrapper array + } + + @SuppressWarnings("rawtypes") + @Override + protected void addWrapperArrayTransformers(Map answer) { answer.put(Boolean[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Boolean[].class); + return value.toArray(Boolean.class); } }); - answer.put(Byte[].class, new EzyToObject() { + answer.put(Byte[].class, new EzyToObject() { @Override - public Object transform(byte[] value) { - return toByteWrapperArray(value); + public Object transform(Object value) { + if(value instanceof byte[]) + return toByteWrapperArray((byte[])value); + return ((EzyArray)value).toArray(Byte.class); } }); - answer.put(Character[].class, new EzyToObject() { + answer.put(Character[].class, new EzyToObject() { @Override - public Object transform(byte[] value) { - return toCharWrapperArray(value); + public Object transform(Object value) { + if(value instanceof byte[]) + return toCharWrapperArray((byte[])value); + return ((EzyArray)value).toArray(Character.class); } }); answer.put(Double[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Double[].class); + return value.toArray(Double.class); } }); answer.put(Float[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Float[].class); + return value.toArray(Float.class); } }); answer.put(Integer[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Integer[].class); + return value.toArray(Integer.class); } }); answer.put(Long[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Long[].class); + return value.toArray(Long.class); } }); answer.put(Short[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - return value.toArray(Short[].class); - } - }); - - //other - answer.put(Date.class, new EzyToObject() { - @Override - public Object transform(String value) { - try { - return FastDateFormat.getInstance(getDateFormatPattern()).parse(value); - } catch (ParseException e) { - getLogger().info("value = " + value + " is invalid", e); - } - return null; - } - }); - - //me - answer.put(EzyObject[].class, new EzyToObject() { - @Override - public Object transform(EzyArray value) { - EzyObject[] answer = new EzyObject[value.size()]; - for(int i = 0 ; i < value.size() ; i++) - answer[i] = value.get(i, EzyObject.class); - return answer; + return value.toArray(Short.class); } }); - - return answer; - } - - private static Logger getLogger() { - return LoggerFactory.getLogger(EzyLiteOutputTransformer.class); } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java deleted file mode 100644 index 305cae89..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.nio.ByteBuffer; - -public abstract class EzyLongs { - - private EzyLongs() { - } - - public static long bin2long(int length) { - return EzyMath.bin2long(length); - } - - public static long bin2long(byte[] bytes) { - return EzyMath.bin2long(bytes); - } - - public static long bin2ulong(byte[] bytes) { - return EzyMath.bin2ulong(bytes); - } - - public static long bin2long(ByteBuffer buffer, int size) { - return bin2long(EzyBytes.copy(buffer, size)); - } - - public static long bin2ulong(ByteBuffer buffer, int size) { - return bin2ulong(EzyBytes.copy(buffer, size)); - } -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java deleted file mode 100644 index f2219135..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -public abstract class EzyPrints { - - private EzyPrints() { - } - - public static String printBits(byte[] bytes) { - StringBuilder builder = new StringBuilder(); - for(int i = 0 ; i < bytes.length ; i++) - builder.append(printBits(bytes[i])); - return builder.toString(); - } - - public static String printBits(byte value) { - String str = insertBegin(Integer.toBinaryString(value & 0xff), "0", 8); - return str.substring(str.length() - 8); - } - - public static String insertBegin(String str, String ch, int maxlen) { - String answer = str; - while(answer.length() < maxlen) - answer = ch + answer; - return answer; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleCollectionConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleCollectionConverter.java new file mode 100644 index 00000000..a3848775 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleCollectionConverter.java @@ -0,0 +1,333 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.function.EzyToObject; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; + +@SuppressWarnings({"rawtypes", "unchecked"}) +public class EzySimpleCollectionConverter implements EzyCollectionConverter { + + private final Map converters = defaultConverters(); + + @Override + public T toArray(Collection coll, Class type) { + return convert(coll, type); + } + + protected T convert(Object value, Class type) { + if(converters.containsKey(type)) + return (T) converters.get(type).transform(value); + throw new IllegalArgumentException("can not convert " + type); + } + + protected T toArray(Object array, Class type) { + return toArray((Collection)array, type.getComponentType()); + } + + private T[] toArray(Iterable iterable, T[] array) { + int count = 0; + Class arrayType = array.getClass().getComponentType(); + for(Object obj : iterable) + array[count ++] = toArray(obj, arrayType); + return array; + } + + private char[] toPrimitiveCharArray(Object value) { + if(value instanceof byte[]) + return EzyDataConverter.byteArrayToCharArray((byte[])value); + else if(value instanceof EzyArray) + return ((EzyArray)value).toArray(char.class); + else + return EzyNumbersConverter.numbersToPrimitiveChars((Collection)value); + } + + private Character[] toWrapperCharArray(Object value) { + if(value instanceof byte[]) + return EzyDataConverter.toCharWrapperArray((byte[])value); + else if(value instanceof EzyArray) + return ((EzyArray)value).toArray(Character.class); + else + return EzyNumbersConverter.numbersToWrapperChars((Collection)value); + } + + private byte[] toPrimitiveByteArray(Object value) { + if(value instanceof byte[]) + return (byte[])value; + else if(value instanceof EzyArray) + return ((EzyArray)value).toArray(byte.class); + else if(value instanceof String) + return EzyBase64.decode((String)value); + return EzyDataConverter.collectionToPrimitiveByteArray((Collection)value); + } + + private Byte[] toWrapperByteArray(Object value) { + if(value instanceof byte[]) + return EzyDataConverter.toByteWrapperArray((byte[])value); + else if(value instanceof EzyArray) + return ((EzyArray)value).toArray(Byte.class); + else if(value instanceof String) + return EzyDataConverter.toByteWrapperArray(EzyBase64.decode((String)value)); + return EzyDataConverter.collectionToWrapperByteArray((Collection)value); + } + + private Map defaultConverters() { + Map converters= new ConcurrentHashMap<>(); + addDefaultConverters(converters); + addCustomConverters(converters); + return converters; + } + + private void addDefaultConverters(Map converters) { + converters.put(boolean.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyDataConverter.collectionToPrimitiveBoolArray(input); + } + }); + + converters.put(byte.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveBytes(input); + } + }); + converters.put(char.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveChars(input); + } + }); + converters.put(double.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveDoubles(input); + } + }); + converters.put(float.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveFloats(input); + } + }); + converters.put(int.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveInts(input); + } + }); + converters.put(long.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveLongs(input); + } + }); + converters.put(short.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToPrimitiveShorts(input); + } + }); + + converters.put(String.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyDataConverter.collectionToStringArray(input); + } + }); + + // wrapper + converters.put(Boolean.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyDataConverter.collectionToWrapperBoolArray(input); + } + }); + + converters.put(Byte.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperBytes(input); + } + }); + converters.put(Character.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperChars(input); + } + }); + converters.put(Double.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperDoubles(input); + } + }); + converters.put(Float.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperFloats(input); + } + }); + converters.put(Integer.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperInts(input); + } + }); + converters.put(Long.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperLongs(input); + } + }); + converters.put(Short.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyNumbersConverter.numbersToWrapperShorts(input); + } + }); + + //entity + converters.put(EzyObject.class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return EzyCollections.toArray(input, size -> new EzyObject[size]); + } + }); + } + + //============= + //============= + + private void addCustomConverters(Map converters) { + converters.put(boolean[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new boolean[input.size()][]); + } + }); + + converters.put(byte[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + int count = 0; + byte[][] answer = new byte[input.size()][]; + for(Object item : input) + answer[count ++] = toPrimitiveByteArray(item); + return answer; + } + }); + converters.put(char[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + int count = 0; + char[][] answer = new char[input.size()][]; + for(Object item : input) + answer[count ++] = toPrimitiveCharArray(item); + return answer; + } + }); + converters.put(double[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new double[input.size()][]); + } + }); + converters.put(float[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new float[input.size()][]); + } + }); + converters.put(int[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new int[input.size()][]); + } + }); + converters.put(long[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new long[input.size()][]); + } + }); + converters.put(short[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new short[input.size()][]); + } + }); + + converters.put(String[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new String[input.size()][]); + } + }); + + // wrapper + converters.put(Boolean[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Boolean[input.size()][]); + } + }); + + converters.put(Byte[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + int count = 0; + Byte[][] answer = new Byte[input.size()][]; + for(Object item : input) + answer[count ++] = toWrapperByteArray(item); + return answer; + } + }); + converters.put(Character[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + int count = 0; + Character[][] answer = new Character[input.size()][]; + for(Object item : input) + answer[count ++] = toWrapperCharArray(item); + return answer; + } + }); + converters.put(Double[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Double[input.size()][]); + } + }); + converters.put(Float[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Float[input.size()][]); + } + }); + converters.put(Integer[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Integer[input.size()][]); + } + }); + converters.put(Long[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Long[input.size()][]); + } + }); + converters.put(Short[].class, new EzyToObject() { + @Override + public Object transform(Collection input) { + return toArray(input, new Short[input.size()][]); + } + }); + + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleInputTransformer.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleInputTransformer.java index 897238bb..8c8fe2e0 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleInputTransformer.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleInputTransformer.java @@ -1,33 +1,29 @@ package com.tvd12.ezyfoxserver.io; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.arrayToList; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.charArrayToByteArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.charWrapperArrayToPrimitiveByteArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.toPrimitiveByteArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.arrayToList; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.charArrayToByteArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.charWrapperArrayToPrimitiveByteArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.toPrimitiveByteArray; import java.io.Serializable; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.lang3.time.FastDateFormat; - -import com.tvd12.ezyfoxserver.EzyEnvironment; -import com.tvd12.ezyfoxserver.EzySystem; -import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.entity.impl.EzyArrayList; import com.tvd12.ezyfoxserver.function.EzyToObject; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; -public class EzySimpleInputTransformer implements EzyInputTransformer, Serializable { +public class EzySimpleInputTransformer + extends EzyEntityBuilders + implements EzyInputTransformer, Serializable { private static final long serialVersionUID = 5436415615070699119L; @SuppressWarnings("rawtypes") - private static final Map TRANSFORMER; - - static { - TRANSFORMER = defaultTransformers(); - } + private final Map transformers = defaultTransformers(); @Override public Object transform(Object value) { @@ -44,29 +40,58 @@ protected Object transformNonNullValue(Object value) { return transformNonNullValue(value, getTransformers()); } + @SuppressWarnings("rawtypes") + protected Object transformNonNullValue( + Object value, Map transformers) { + return transformNonNullValue(value, value.getClass(), transformers); + } + @SuppressWarnings({ "unchecked", "rawtypes" }) - protected Object transformNonNullValue(Object value, - final Map transformers) { - if(transformers.containsKey(value.getClass())) - return transformers.get(value.getClass()).transform(value); + protected Object transformNonNullValue( + Object value, Class type, Map transformers) { + EzyToObject trans = transformers.get(type); + if(trans != null) + return trans.transform(value); + else if(type.isEnum()) + return value.toString(); + else if(value instanceof Map) + return transformMap(value); + else if(value instanceof EzyBuilder) + return transformBuilder(value, transformers); return value; } @SuppressWarnings("rawtypes") - protected Map getTransformers() { - return TRANSFORMER; + protected Object transformMap(Object value) { + return newObjectBuilder().append((Map)value).build(); } - private static String getDateFormatPattern() { - return EzySystem.getEnv().getProperty(EzyEnvironment.DATE_FORMAT_PATTERN); + @SuppressWarnings("rawtypes") + protected Object transformBuilder( + Object value, Map transformers) { + return transformNonNullValue(((EzyBuilder)value).build()); } @SuppressWarnings("rawtypes") - private static Map - defaultTransformers() { + protected Map getTransformers() { + return transformers; + } + + @SuppressWarnings("rawtypes") + private Map defaultTransformers() { Map answer = new ConcurrentHashMap<>(); - - //primitive type + addOtherTransformers(answer); + addEntityTransformers(answer); + addWrapperTransformers(answer); + addWrapperArrayTransformers(answer); + addPrimitiveArrayTransformers(answer); + addTwoDimensionsWrapperArrayTransformers(answer); + addTwoDimensionsPrimitiveArrayTransformers(answer); + return answer; + } + + @SuppressWarnings("rawtypes") + protected void addWrapperTransformers(Map answer) { answer.put(Boolean.class, new EzyToObject() { @Override public Object transform(Boolean value) { @@ -121,8 +146,10 @@ public Object transform(String value) { return value; } }); - - //primitive array + } + + @SuppressWarnings("rawtypes") + protected void addPrimitiveArrayTransformers(Map answer) { answer.put(boolean[].class, new EzyToObject() { @Override public Object transform(boolean[] value) { @@ -177,8 +204,10 @@ public Object transform(String[] value) { return arrayToList(value); } }); - - //wrapper array + } + + @SuppressWarnings("rawtypes") + protected void addWrapperArrayTransformers(Map answer) { answer.put(Boolean[].class, new EzyToObject() { @Override public Object transform(Boolean[] value) { @@ -228,25 +257,168 @@ public Object transform(Short[] value) { } }); - //other + } + + //primitive two dimensions array + @SuppressWarnings("rawtypes") + protected void addTwoDimensionsPrimitiveArrayTransformers(Map answer) { + answer.put(boolean[][].class, new EzyToObject() { + @Override + public Object transform(boolean[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(byte[][].class, new EzyToObject() { + @Override + public Object transform(byte[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(char[][].class, new EzyToObject() { + @Override + public Object transform(char[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(double[][].class, new EzyToObject() { + @Override + public Object transform(double[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(float[][].class, new EzyToObject() { + @Override + public Object transform(float[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(int[][].class, new EzyToObject() { + @Override + public Object transform(int[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(long[][].class, new EzyToObject() { + @Override + public Object transform(long[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(short[][].class, new EzyToObject() { + @Override + public Object transform(short[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + } + + //wrapper two dimensions array + @SuppressWarnings("rawtypes") + protected void addTwoDimensionsWrapperArrayTransformers(Map answer) { + answer.put(Boolean[][].class, new EzyToObject() { + @Override + public Object transform(Boolean[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Byte[][].class, new EzyToObject() { + @Override + public Object transform(Byte[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Character[][].class, new EzyToObject() { + @Override + public Object transform(Character[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Double[][].class, new EzyToObject() { + @Override + public Object transform(Double[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Float[][].class, new EzyToObject() { + @Override + public Object transform(Float[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Integer[][].class, new EzyToObject() { + @Override + public Object transform(Integer[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Long[][].class, new EzyToObject() { + @Override + public Object transform(Long[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(Short[][].class, new EzyToObject() { + @Override + public Object transform(Short[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(String[][].class, new EzyToObject() { + @Override + public Object transform(String[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + } + + //entity + @SuppressWarnings("rawtypes") + protected void addEntityTransformers(Map answer) { + answer.put(EzyObject[].class, new EzyToObject() { + @Override + public Object transform(EzyObject[] value) { + return newArrayBuilder().append(value).build(); + } + }); + answer.put(EzyObject[][].class, new EzyToObject() { + @Override + public Object transform(EzyObject[][] value) { + return newArrayBuilder().append(value).build(); + } + }); + } + + //other + @SuppressWarnings("rawtypes") + protected void addOtherTransformers(Map answer) { answer.put(Date.class, new EzyToObject() { @Override public Object transform(Date value) { - return FastDateFormat.getInstance(getDateFormatPattern()).format(value); + return EzyDates.format(value); } }); - //me - answer.put(EzyObject[].class, new EzyToObject() { + answer.put(LocalDate.class, new EzyToObject() { @Override - public Object transform(EzyObject[] value) { - EzyArray answer = new EzyArrayList(); - answer.add(value); - return answer; + public Object transform(LocalDate value) { + return EzyDates.format(value, "yyyy-MM-dd"); + } + }); + + answer.put(LocalDateTime.class, new EzyToObject() { + @Override + public Object transform(LocalDateTime value) { + return EzyDates.format(value); + } + }); + + answer.put(Class.class, new EzyToObject() { + @Override + public Object transform(Class value) { + return value.getName(); } }); - return answer; } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleOutputTransformer.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleOutputTransformer.java index 154dd0f8..618d07f0 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleOutputTransformer.java +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleOutputTransformer.java @@ -1,37 +1,33 @@ package com.tvd12.ezyfoxserver.io; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.byteArrayToCharArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveBoolArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveDoubleArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveFloatArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveIntArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveLongArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToPrimitiveShortArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToStringArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperBoolArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperDoubleArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperFloatArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperIntArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperLongArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.collectionToWrapperShortArray; -import static com.tvd12.ezyfoxserver.util.EzyDataConverter.toCharWrapperArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.byteArrayToCharArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveIntArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveLongArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveShortArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToStringArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperIntArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperLongArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperShortArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.toCharWrapperArray; import java.io.Serializable; -import java.text.ParseException; +import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.apache.commons.lang3.time.FastDateFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.EzyEnvironment; -import com.tvd12.ezyfoxserver.EzySystem; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; import com.tvd12.ezyfoxserver.function.EzyToObject; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; import com.tvd12.ezyfoxserver.util.EzyLoggable; public class EzySimpleOutputTransformer @@ -39,14 +35,8 @@ public class EzySimpleOutputTransformer implements EzyOutputTransformer, Serializable { private static final long serialVersionUID = 8067491929651725682L; - private static final Logger LOGGER; @SuppressWarnings("rawtypes") - private static final Map TRANSFORMER; - - static { - TRANSFORMER = defaultTransformers(); - LOGGER = LoggerFactory.getLogger(EzySimpleOutputTransformer.class); - } + private final Map transformers = defaultTransformers(); @SuppressWarnings("rawtypes") @Override @@ -68,26 +58,44 @@ protected Object transformNonNullValue(Object value, Class type) { @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object transformNonNullValue( Object value, Class type, Map transformers) { - if(transformers.containsKey(type)) + EzyToObject trans = transformers.get(type); + if(trans != null) return transformers.get(type).transform(value); + if(type.isEnum()) + return Enum.valueOf(type, value.toString()); return value; } @SuppressWarnings("rawtypes") protected Map getTransformers() { - return TRANSFORMER; - } - - private static String getDateFormatPattern() { - return EzySystem.getEnv().getProperty(EzyEnvironment.DATE_FORMAT_PATTERN); + return transformers; } + //tank @SuppressWarnings("rawtypes") - private static Map + private Map defaultTransformers() { Map answer = new ConcurrentHashMap<>(); - - //primitive type + addOtherTransformers(answer); + addEntityTransformers(answer); + addWrapperTransformers(answer); + addPrimitiveTransformers(answer); + addWrapperArrayTransformers(answer); + addPrimitiveArrayTransformers(answer); + addTwoDimensionsWrapperArrayTransformers(answer); + addTwoDimensionsPrimitiveArrayTransformers(answer); + return answer; + } + + protected EzyObject[] toObjectArray(EzyArray value) { + EzyObject[] answer = new EzyObject[value.size()]; + for(int i = 0 ; i < value.size() ; i++) + answer[i] = value.get(i, EzyObject.class); + return answer; + } + + @SuppressWarnings("rawtypes") + protected void addPrimitiveTransformers(Map answer) { answer.put(boolean.class, new EzyToObject() { @Override public Object transform(Boolean value) { @@ -136,8 +144,10 @@ public Object transform(Short value) { return value; } }); - - //primitive type + } + + @SuppressWarnings("rawtypes") + protected void addWrapperTransformers(Map answer) { answer.put(Boolean.class, new EzyToObject() { @Override public Object transform(Boolean value) { @@ -192,8 +202,10 @@ public Object transform(String value) { return value; } }); - - //primitive array + } + + @SuppressWarnings("rawtypes") + protected void addPrimitiveArrayTransformers(Map answer) { answer.put(boolean[].class, new EzyToObject>() { @Override public Object transform(Collection value) { @@ -248,8 +260,10 @@ public Object transform(Collection value) { return collectionToStringArray(value); } }); - - //wrapper array + } + + @SuppressWarnings("rawtypes") + protected void addWrapperArrayTransformers(Map answer) { answer.put(Boolean[].class, new EzyToObject>() { @Override public Object transform(Collection value) { @@ -292,32 +306,188 @@ public Object transform(Collection value) { return collectionToWrapperShortArray(value); } }); - - //other + } + + @SuppressWarnings("rawtypes") + protected void addOtherTransformers(Map answer) { answer.put(Date.class, new EzyToObject() { @Override public Object transform(String value) { try { - return FastDateFormat.getInstance(getDateFormatPattern()).parse(value); - } catch (ParseException e) { - LOGGER.info("value = " + value + " is invalid", e); + return EzyDates.parse(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); } return null; } }); - //me + answer.put(LocalDate.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyDates.parseDate(value, "yyyy-MM-dd"); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + + answer.put(LocalDateTime.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyDates.parseDateTime(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + + //other + answer.put(Class.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyClasses.getClass(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + } + + @SuppressWarnings("rawtypes") + protected void addEntityTransformers(Map answer) { answer.put(EzyObject[].class, new EzyToObject() { @Override public Object transform(EzyArray value) { - EzyObject[] answer = new EzyObject[value.size()]; - for(int i = 0 ; i < value.size() ; i++) - answer[i] = value.get(i, EzyObject.class); - return answer; + return toObjectArray(value); } }); - return answer; + answer.put(EzyObject[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + EzyObject[][] answer = new EzyObject[value.size()][]; + for(int i = 0 ; i < value.size() ; i++) + answer[i] = toObjectArray(value.get(i, EzyArray.class)); + return answer; + } + }); + } + + @SuppressWarnings("rawtypes") + protected void addTwoDimensionsPrimitiveArrayTransformers(Map answer) { + answer.put(boolean[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(boolean[].class); + } + }); + answer.put(byte[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(byte[].class); + } + }); + answer.put(char[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(char[].class); + } + }); + answer.put(double[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(double[].class); + } + }); + answer.put(float[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(float[].class); + } + }); + answer.put(int[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(int[].class); + } + }); + answer.put(long[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(long[].class); + } + }); + answer.put(short[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(short[].class); + } + }); + } + + @SuppressWarnings("rawtypes") + protected void addTwoDimensionsWrapperArrayTransformers(Map answer) { + answer.put(Boolean[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Boolean[].class); + } + }); + answer.put(Byte[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Byte[].class); + } + }); + answer.put(Character[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Character[].class); + } + }); + answer.put(Double[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Double[].class); + } + }); + answer.put(Float[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Float[].class); + } + }); + answer.put(Integer[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Integer[].class); + } + }); + answer.put(Long[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Long[].class); + } + }); + answer.put(Short[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(Short[].class); + } + }); + answer.put(String[][].class, new EzyToObject() { + @Override + public Object transform(EzyArray value) { + return value.toArray(String[].class); + } + }); } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java deleted file mode 100644 index 572cd66c..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; - -public abstract class EzyStrings { - - private EzyStrings() { - } - - public static String newUTF(byte[] bytes) { - return newString(bytes, "UTF-8"); - } - - public static String newUTF(ByteBuffer buffer, int size) { - return newString(buffer, size, "UTF-8"); - } - - public static byte[] getUTFBytes(String str) { - return getBytes(str, "UTF-8"); - } - - public static String newString(byte[] bytes, String charset) { - try { - return new String(bytes, charset); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } - } - - public static byte[] getBytes(String str, String charset) { - try { - return str.getBytes(charset); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } - } - - public static String newString(ByteBuffer buffer, int size, String charset) { - byte[] bytes = new byte[size]; - buffer.get(bytes); - return newString(bytes, charset); - } -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectFactory.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectFactory.java similarity index 100% rename from ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectFactory.java rename to ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectFactory.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java new file mode 100644 index 00000000..f4a2f874 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java @@ -0,0 +1,285 @@ +package com.tvd12.ezyfoxserver.pattern; + +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.function.EzyVoid; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.util.EzyReturner; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +public abstract class EzyObjectPool + extends EzyLoggable + implements EzyStartable, EzyDestroyable { + + protected final Queue pool; + protected final int minObjects; + protected final int maxObjects; + protected final long validationInterval; + protected final List borrowedObjects; + protected final EzyObjectFactory objectFactory; + protected final ScheduledExecutorService validationService; + + protected final Lock lock = new ReentrantLock(); + + @SuppressWarnings({ "rawtypes", "unchecked"}) + protected EzyObjectPool(Builder builder) { + this.pool = builder.getPool(); + this.minObjects = builder.minObjects; + this.maxObjects = builder.maxObjects; + this.objectFactory = builder.getObjectFactory(); + this.borrowedObjects = builder.newBorrowedObjects(); + this.validationInterval = builder.validationInterval; + this.validationService = builder.getValidationService(); + } + + protected final void initializeObjects() { + for(int i = 0 ; i < minObjects ; i++) + pool.add(createObject()); + } + + protected T createObject() { + return objectFactory.newProduct(); + } + + protected void removeObject(T object) { + } + + protected List getBorrowedObjects() { + return new ArrayList<>(borrowedObjects); + } + + protected List getRemainObjects() { + return new ArrayList<>(pool); + } + + @Override + public void start() throws Exception { + startValidationService(); + } + + protected void startValidationService() { + validationService.scheduleWithFixedDelay(newValidationTask(), + validationInterval, validationInterval, TimeUnit.MILLISECONDS); + } + + protected Runnable newValidationTask() { + return new Runnable() { + + @Override + public void run() { + try { + addOrRemoveObjects(pool.size()); + removeStaleObjects(); + } + catch(Exception e) { + getLogger().error("object poll validation error", e); + } + } + + private void addOrRemoveObjects(int poolSize) { + if(poolSize < minObjects) + addObjects(poolSize); + else if(poolSize > maxObjects) + removeObjects(poolSize); + } + + private void addObjects(int poolSize) { + addNewObjects(minObjects - poolSize); + } + + private void addNewObjects(int size) { + runWithLock(() -> tryAddNewObjects(size)); + } + + private void tryAddNewObjects(int size) { + for(int i = 0 ; i < size ; i++) + pool.add(createObject()); + } + + private void removeObjects(int poolSize) { + removeUnusedObjects(poolSize - maxObjects); + } + + private void removeUnusedObjects(int size) { + runWithLock(() -> tryRemoveUnusedObjects(size)); + } + + private void tryRemoveUnusedObjects(int size) { + for(int i = 0 ; i < size ; i++) + removeObject(pool.poll()); + } + }; + } + + protected void removeStaleObjects() { + tryRemoveStaleObjects(); + } + + protected void tryRemoveStaleObjects() { + removeStaleObjects(getCanBeStaleObjects()); + } + + protected void removeStaleObjects(List objects) { + for(T object : objects) + if(isStaleObject(object)) + removeStaleObject(object); + } + + protected void removeStaleObject(T object) { + } + + protected boolean isStaleObject(T object) { + return false; + } + + protected List getCanBeStaleObjects() { + return getBorrowedObjects(); + } + + protected final T borrowObject() { + return returnWithLock(() -> tryBorrowObject()); + } + + private final T tryBorrowObject() { + T obj = borrowOrNewObject(); + borrowedObjects.add(obj); + return obj; + } + + protected final boolean returnObject(T object) { + return returnWithLock(() -> tryReturnObject(object)); + } + + private final boolean tryReturnObject(T object) { + return object != null ? doReturnObject(object) : false; + } + + protected void runWithLock(EzyVoid applier) { + EzyProcessor.processWithLock(applier, lock); + } + + protected R returnWithLock(Supplier supplier) { + return EzyReturner.returnWithLock(supplier, lock); + } + + private T borrowOrNewObject() { + return EzyReturner.returnNotNull(pool.poll(), createObject()); + } + + private boolean doReturnObject(T object) { + borrowedObjects.remove(object); + return pool.offer(object); + } + + @Override + public void destroy() { + try { + tryShutdown(); + } + catch(Exception e) { + getLogger().error(getClass().getSimpleName() + " error", e); + } + } + + protected void tryShutdown() { + validationService.shutdown(); + } + + @SuppressWarnings("rawtypes") + public static abstract class Builder + implements EzyBuilder> { + + private Queue pool; + private int minObjects = 300; + private int maxObjects = 5000; + private long validationInterval = 3 * 1000; + protected EzyObjectFactory objectFactory; + private ScheduledExecutorService validationService; + + @SuppressWarnings("unchecked") + public B pool(Queue pool) { + this.pool = pool; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B minObjects(int minObjects) { + this.minObjects = minObjects; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B maxObjects(int maxObjects) { + this.maxObjects = maxObjects; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B objectFactory(EzyObjectFactory objectFactory) { + this.objectFactory = objectFactory; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B validationInterval(long validationInterval) { + this.validationInterval = validationInterval; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B validationService(ScheduledExecutorService validationService) { + this.validationService = validationService; + return (B)this; + } + + protected abstract String getProductName(); + + protected Queue getPool() { + return pool != null ? pool : newPool(); + } + + protected Queue newPool() { + return new ConcurrentLinkedQueue<>(); + } + + protected EzyObjectFactory getObjectFactory() { + return objectFactory != null ? objectFactory : newObjectFactory(); + } + + protected abstract EzyObjectFactory newObjectFactory(); + + protected ScheduledExecutorService getValidationService() { + return validationService != null ? validationService : newValidationService(); + } + + protected ScheduledExecutorService newValidationService() { + ScheduledExecutorService service = EzyExecutors.newScheduledThreadPool(3, newThreadFactory()); + Runtime.getRuntime().addShutdownHook(new Thread(() -> service.shutdown())); + return service; + } + + protected ThreadFactory newThreadFactory() { + return EzyExecutors.newThreadFactory(getProductName()); + } + + protected List newBorrowedObjects() { + return new CopyOnWriteArrayList<>(); + } + + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClassUtil.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClassUtil.java deleted file mode 100644 index d739570f..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClassUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.tvd12.ezyfoxserver.reflect; - -public abstract class EzyClassUtil { - - private EzyClassUtil() { - } - - @SuppressWarnings("unchecked") - public static T newInstance(final String className) { - try { - return (T) getClass(className).newInstance(); - } - catch(Exception e) { - throw new IllegalArgumentException(e); - } - } - - @SuppressWarnings("rawtypes") - public static Class getClass(final String className) { - try { - return Class.forName(className); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException(e); - } - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionConverter.java deleted file mode 100644 index d531763a..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionConverter.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import com.tvd12.ezyfoxserver.function.EzyToObject; - -@SuppressWarnings({ "rawtypes", "unchecked" }) -public abstract class EzyCollectionConverter { - - private static final Map CONVERTERS; - - static { - CONVERTERS = defaultConverters(); - } - - private EzyCollectionConverter() { - } - - public static T toArray(Collection coll, Class type) { - if(CONVERTERS.containsKey(type)) - return (T) CONVERTERS.get(type).transform(coll); - throw new IllegalStateException("can not convert " + type); - } - - private static Map defaultConverters() { - Map answer = new HashMap<>(); - - // primitive - answer.put(boolean[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveBoolArray(input); - } - }); - answer.put(byte[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveByteArray(input); - } - }); - answer.put(char[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveCharArray(input); - } - }); - answer.put(double[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveDoubleArray(input); - } - }); - answer.put(float[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveFloatArray(input); - } - }); - answer.put(int[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveIntArray(input); - } - }); - answer.put(long[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveLongArray(input); - } - }); - answer.put(short[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveShortArray(input); - } - }); - answer.put(String[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToStringArray(input); - } - }); - - // wrapper - answer.put(Boolean[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperBoolArray(input); - } - }); - answer.put(Byte[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperByteArray(input); - } - }); - answer.put(Character[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperCharArray(input); - } - }); - answer.put(Double[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperDoubleArray(input); - } - }); - answer.put(Float[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperFloatArray(input); - } - }); - answer.put(Integer[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperIntArray(input); - } - }); - answer.put(Long[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperLongArray(input); - } - }); - answer.put(Short[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperShortArray(input); - } - }); - - return answer; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntityBuilders.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntityBuilders.java new file mode 100644 index 00000000..73453ec3 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntityBuilders.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.util; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; + +public class EzyEntityBuilders extends EzyLoggable { + + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + + protected EzyObjectBuilder newObjectBuilder() { + return EzyEntityFactory.create(EzyObjectBuilder.class); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntryFiles.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntryFiles.java deleted file mode 100644 index 8eb2c1e2..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntryFiles.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - */ -package com.tvd12.ezyfoxserver.util; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.Collection; - -import org.apache.commons.io.FileUtils; - -/** - * @author tavandung12 - * - */ -public class EzyEntryFiles { - - private File directory; - - public URL[] getURLs() throws IOException { - return getURLs(getFiles()); - } - - private Collection getFiles() { - return FileUtils.listFiles(directory, null, true); - } - - private URL[] getURLs(Collection files) throws IOException { - return FileUtils.toURLs(files.toArray(new File[files.size()])); - } - - public EzyEntryFiles directory(File directory) { - this.directory = directory; - return this; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteCollectionConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteCollectionConverter.java deleted file mode 100644 index e52f86fb..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteCollectionConverter.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import com.tvd12.ezyfoxserver.function.EzyToObject; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public abstract class EzyLiteCollectionConverter { - - private EzyLiteCollectionConverter() { - } - - private static final Map CONVERTERS; - - static { - CONVERTERS = defaultConverters(); - } - - public static T toArray(Collection coll, Class type) { - if(CONVERTERS.containsKey(type)) - return (T) CONVERTERS.get(type).transform(coll); - throw new IllegalStateException("can not convert " + type); - } - - private static Map defaultConverters() { - Map answer = new HashMap<>(); - - answer.put(boolean[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToPrimitiveBoolArray(input); - } - }); - - answer.put(byte[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveBytes(input); - } - }); - answer.put(char[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveChars(input); - } - }); - answer.put(double[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveDoubles(input); - } - }); - answer.put(float[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveFloats(input); - } - }); - answer.put(int[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveInts(input); - } - }); - answer.put(long[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveLongs(input); - } - }); - answer.put(short[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToPrimitiveShorts(input); - } - }); - - answer.put(String[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToStringArray(input); - } - }); - - // wrapper - answer.put(Boolean[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyDataConverter.collectionToWrapperBoolArray(input); - } - }); - - answer.put(Byte[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperBytes(input); - } - }); - answer.put(Character[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperChars(input); - } - }); - answer.put(Double[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperDoubles(input); - } - }); - answer.put(Float[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperFloats(input); - } - }); - answer.put(Integer[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperInts(input); - } - }); - answer.put(Long[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperLongs(input); - } - }); - answer.put(Short[].class, new EzyToObject() { - @Override - public Object transform(Collection input) { - return EzyNumbersConverter.numbersToWrapperShorts(input); - } - }); - - return answer; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteEntityBuilders.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteEntityBuilders.java new file mode 100644 index 00000000..378be5a6 --- /dev/null +++ b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLiteEntityBuilders.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.util; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; + +public class EzyLiteEntityBuilders extends EzyLoggable { + + protected EzyArrayBuilder newArrayBuilder() { + return EzyLiteEntityFactory.create(EzyArrayBuilder.class); + } + + protected EzyObjectBuilder newObjectBuilder() { + return EzyLiteEntityFactory.create(EzyObjectBuilder.class); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java deleted file mode 100644 index c25b4171..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class EzyLoggable { - - protected Logger logger; - - { - logger = LoggerFactory.getLogger(getClass()); - } - - protected Logger getLogger() { - return logger; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyNumbersConverter.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyNumbersConverter.java deleted file mode 100644 index 9e3e661f..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyNumbersConverter.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -import java.util.Collection; - -import com.tvd12.ezyfoxserver.function.EzyNewArray; -import com.tvd12.ezyfoxserver.function.EzyNumber; - -@SuppressWarnings({"rawtypes"}) -public abstract class EzyNumbersConverter { - - private EzyNumbersConverter() { - } - - // primitive - public static byte[] numbersToPrimitiveBytes(Collection coll) { - int index = 0; - byte[] answer = new byte[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).byteValue(); - return answer; - } - - public static char[] numbersToPrimitiveChars(Collection coll) { - int index = 0; - char[] answer = new char[coll.size()]; - for(Object obj : coll) - answer[index ++] = (char)((Number)obj).byteValue(); - return answer; - } - - public static double[] numbersToPrimitiveDoubles(Collection coll) { - int index = 0; - double[] answer = new double[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).doubleValue(); - return answer; - } - - public static float[] numbersToPrimitiveFloats(Collection coll) { - int index = 0; - float[] answer = new float[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).floatValue(); - return answer; - } - - public static int[] numbersToPrimitiveInts(Collection coll) { - int index = 0; - int[] answer = new int[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).intValue(); - return answer; - } - - public static long[] numbersToPrimitiveLongs(Collection coll) { - int index = 0; - long[] answer = new long[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).longValue(); - return answer; - } - - public static short[] numbersToPrimitiveShorts(Collection coll) { - int index = 0; - short[] answer = new short[coll.size()]; - for(Object obj : coll) - answer[index ++] = ((Number)obj).shortValue(); - return answer; - } - - // wrapper - public static T[] numbersToWrapperNumbers( - Collection coll, EzyNewArray newer, EzyNumber converter) { - return coll.stream() - .map((num)->convertNumber(num, converter)) - .toArray((size) -> newer.apply(size)); - } - - public static Byte[] numbersToWrapperBytes(Collection coll) { - return numbersToWrapperNumbers(coll, Byte[]::new, (num) -> numberToByte(num)); - } - - public static Character[] numbersToWrapperChars(Collection coll) { - return numbersToWrapperNumbers(coll, Character[]::new, (num) -> numberToChar(num)); - } - - public static Double[] numbersToWrapperDoubles(Collection coll) { - return numbersToWrapperNumbers(coll, Double[]::new, (num) -> numberToDouble(num)); - } - - public static Float[] numbersToWrapperFloats(Collection coll) { - return numbersToWrapperNumbers(coll, Float[]::new, (num) -> numberToFloat(num)); - } - - public static Integer[] numbersToWrapperInts(Collection coll) { - return numbersToWrapperNumbers(coll, Integer[]::new, (num) -> numberToInt(num)); - } - - public static Long[] numbersToWrapperLongs(Collection coll) { - return numbersToWrapperNumbers(coll, Long[]::new, (num) -> numberToLong(num)); - } - - public static Short[] numbersToWrapperShorts(Collection coll) { - return numbersToWrapperNumbers(coll, Short[]::new, (num) -> numberToShort(num)); - } - - public static Byte numberToByte(Number number) { - return convertNumber(number, (num) -> num.byteValue()); - } - - public static Character numberToChar(Number number) { - return convertNumber(number, (num) -> (char)num.byteValue()); - } - - public static Double numberToDouble(Number number) { - return convertNumber(number, (num) -> num.doubleValue()); - } - - public static Float numberToFloat(Number number) { - return convertNumber(number, (num) -> num.floatValue()); - } - - public static Integer numberToInt(Number number) { - return convertNumber(number, (num) -> num.intValue()); - } - - public static Long numberToLong(Number number) { - return convertNumber(number, (num) -> num.longValue()); - } - - public static Short numberToShort(Number number) { - return convertNumber(number, (num) -> num.shortValue()); - } - - public static T convertNumber(Object number, EzyNumber converter) { - return converter.apply((Number)number); - } - - public static T convertNumber(Number number, EzyNumber converter) { - return converter.apply(number); - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java deleted file mode 100644 index dfdf3863..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -public abstract class EzyReturner { - - private EzyReturner() { - } - - public static T returnNotNull(T rvalue, T svalue) { - return rvalue != null ? rvalue : svalue; - } - -} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java b/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java deleted file mode 100644 index e477cf64..00000000 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.tvd12.ezyfoxserver.util; - -public class EzyStringsIterator extends EzyArrayIterator { - - private String[] array; - - public EzyStringsIterator(String[] array) { - this.array = array; - } - - public static EzyStringsIterator wrap(String[] array) { - return new EzyStringsIterator(array); - } - - @Override - protected int getLength() { - return array.length; - } - - @Override - protected String getItem(int index) { - return array[index]; - } - - - -} diff --git a/ezyfox-server-common/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index b/ezyfox-server-common/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index deleted file mode 100644 index ea6854d6..00000000 --- a/ezyfox-server-common/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index +++ /dev/null @@ -1 +0,0 @@ -config.EzySettings \ No newline at end of file diff --git a/ezyfox-server-common/src/main/resources/ezy-settings-1.0.0.xsd b/ezyfox-server-common/src/main/resources/ezy-settings-1.0.0.xsd deleted file mode 100644 index b6ff826d..00000000 --- a/ezyfox-server-common/src/main/resources/ezy-settings-1.0.0.xsd +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ezyfox-server-common/src/main/resources/ezy-settings.xml b/ezyfox-server-common/src/main/resources/ezy-settings.xml deleted file mode 100644 index 3c369fdc..00000000 --- a/ezyfox-server-common/src/main/resources/ezy-settings.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - com.tvd12 - - - - - videopoker - com.tvd12.example.extension.VideoPokerAppEntryLoader - - - - - - auth - com.tvd12.example.extension.VideoPokerPluginEntryLoader - - - - - \ No newline at end of file diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/CommonBaseTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/CommonBaseTest.java new file mode 100644 index 00000000..8801956b --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/CommonBaseTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class CommonBaseTest extends BaseTest { + + protected EzyObjectBuilder newObjectBuilder() { + return EzyEntityFactory.create(EzyObjectBuilder.class); + } + + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + + protected EzyArrayBuilder newLiteArrayBuilder() { + return EzyLiteEntityFactory.create(EzyArrayBuilder.class); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/EnumTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/EnumTest.java new file mode 100644 index 00000000..d0ae7eef --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/EnumTest.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +import com.tvd12.test.base.BaseTest; +import com.tvd12.test.performance.Performance; + +public class EnumTest extends BaseTest { + + @SuppressWarnings("unused") + @Test + public void test() { + long time = Performance.create() + .loop(1000000) + .test(() -> { + One.ABC.getClass().isEnum(); + One one = Enum.valueOf(One.class, "ABC"); + }) + .getTime(); + System.err.println("loop time is: " + time); + } + + public static enum One { + ABC,DEF + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/JacksonTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/JacksonTest.java index d3bf8a99..c33df278 100644 --- a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/JacksonTest.java +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/JacksonTest.java @@ -12,7 +12,7 @@ import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; import com.tvd12.test.base.BaseTest; public class JacksonTest extends BaseTest { @@ -52,11 +52,11 @@ public EzyObject parseObject(JsonNode node) { } private EzyArrayBuilder newArrayBuilder() { - return EzyEntityFactory.create(EzyArrayBuilder.class); + return EzyLiteEntityFactory.create(EzyArrayBuilder.class); } private EzyObjectBuilder newObjectBuilder() { - return EzyEntityFactory.create(EzyObjectBuilder.class); + return EzyLiteEntityFactory.create(EzyObjectBuilder.class); } private InputStream getJsonInputStream() { diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray1Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray1Test.java new file mode 100644 index 00000000..7083a647 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray1Test.java @@ -0,0 +1,149 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.util.Collection; +import java.util.Date; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.impl.EzyArrayList; +import com.tvd12.ezyfoxserver.io.EzyDates; + +public class EzyArray1Test extends EzyEntityTest { + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void test() { + EzyArrayBuilder builder = newArrayBuilder() + .append(new Boolean(true)) + .append(new Byte((byte)1)) + .append(new Character('a')) + .append(new Double(2D)) + .append(new Float(3F)) + .append(new Integer(4)) + .append(new Long(5L)) + .append(new Short((short)6)) + .append(new String("str")); + + builder + .append(Lists.newArrayList(true, false, true)) + .append(new byte[] {((byte)1)}) + .append(new char[] {'a', 'b', 'c'}) + .append(Lists.newArrayList(1D,2D,3D)) + .append(Lists.newArrayList(4F,5F,6F)) + .append(Lists.newArrayList(6,7,8)) + .append(Lists.newArrayList(9L,10L,11L)) + .append(Lists.newArrayList((short)12)) + .append(Lists.newArrayList("1", "2", "3")); + + builder + .append(EzyDates.parse("2017-05-30T00:00:00:000")); + + EzyArray array = builder.build(); + + assertEquals(array.get(0), Boolean.TRUE); + assertEquals(array.get(1), new Byte((byte)1)); + assertEquals(array.get(2), new Byte((byte)'a')); + assertEquals(array.get(3), new Double(2D)); + assertEquals(array.get(4), new Float(3F)); + assertEquals(array.get(5), new Integer(4)); + assertEquals(array.get(6), new Long(5L)); + assertEquals(array.get(7), new Short((short)6)); + assertEquals(array.get(8), new String("str")); + + assertEquals(array.get(0, boolean.class), Boolean.TRUE); + assertEquals(array.get(1, byte.class), new Byte((byte)1)); + assertEquals(array.get(2, char.class), new Character('a')); + assertEquals(array.get(3, double.class), new Double(2D)); + assertEquals(array.get(4, float.class), new Float(3F)); + assertEquals(array.get(5, int.class), new Integer(4)); + assertEquals(array.get(6, long.class), new Long(5L)); + assertEquals(array.get(7, short.class), new Short((short)6)); + assertEquals(array.get(8, String.class), new String("str")); + + assertEquals(array.get(0, Boolean.class), Boolean.TRUE); + assertEquals(array.get(1, Byte.class), new Byte((byte)1)); + assertEquals(array.get(2, Character.class), new Character('a')); + assertEquals(array.get(3, Double.class), new Double(2D)); + assertEquals(array.get(4, Float.class), new Float(3F)); + assertEquals(array.get(5, Integer.class), new Integer(4)); + assertEquals(array.get(6, Long.class), new Long(5L)); + assertEquals(array.get(7, Short.class), new Short((short)6)); + assertEquals(array.get(8, String.class), new String("str")); + + assertEquals(array.get(9, boolean[].class), new boolean[] {true, false, true}); + assertEquals(array.get(10, byte[].class), new byte[] {1}); + assertEquals(array.get(11, char[].class), new char[] {'a', 'b', 'c'}); + assertEquals(array.get(12, double[].class), new double[] {1D, 2D, 3D}); + assertEquals(array.get(13, float[].class), new float[] {4F,5F,6F}); + assertEquals(array.get(14, int[].class), new int[] {6,7,8}); + assertEquals(array.get(15, long[].class), new long[] {9L,10L,11L}); + assertEquals(array.get(16, short[].class), new short[] {12}); + assertEquals(array.get(17, String[].class), new String[] {"1", "2", "3"}); + + assertEquals(array.get(9, Boolean[].class), new Boolean[] {true, false, true}); + assertEquals(array.get(10, byte[].class), new byte[] {1}); + assertEquals(array.get(11, Character[].class), new Character[] {'a', 'b', 'c'}); + assertEquals(array.get(12, Double[].class), new Double[] {1D, 2D, 3D}); + assertEquals(array.get(13, Float[].class), new Float[] {4F,5F,6F}); + assertEquals(array.get(14, Integer[].class), new Integer[] {6,7,8}); + assertEquals(array.get(15, Long[].class), new Long[] {9L,10L,11L}); + assertEquals(array.get(16, Short[].class), new Short[] {12}); + assertEquals(array.get(17, String[].class), new String[] {"1", "2", "3"}); + + assertEquals(array.get(18, Date.class), EzyDates.parse("2017-05-30T00:00:00:000")); + + assertTrue(((Collection)array.get(9)).containsAll(Lists.newArrayList(true, false, true))); + } + + @Test + public void test1() { + EzyArrayBuilder builder = newArrayBuilder() + .append("a", "b", "c"); + EzyArray array = builder.build(); + assertEquals(array.size(), 3); + assertEquals(array.get(1), "b"); + array.set(1, "d"); + assertEquals(array.get(1), "d"); + array.remove(1); + assertEquals(array.size(), 2); + assertEquals(array.get(1), "c"); + array.forEach(i -> i.toString()); + assertTrue(array.iterator().hasNext()); + assertEquals(array.toList().size(), 2); + assertEquals(array.toList(String.class).size(), 2); + assertEquals(array.toArray(String.class), new String[] {"a", "c"}); + EzyArray dup = array.duplicate(); + assertTrue(array != dup); + assertTrue(dup.toList().containsAll(Sets.newHashSet("a", "c"))); + EzyArray sub = array.sub(0, 1); + assertEquals(sub.size(), 1); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test2() { + EzyArray array = new EzyArrayList() { + private static final long serialVersionUID = 8714822620207886718L; + + @Override + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } + }; + array.duplicate(); + } + + public static class ClassA implements Cloneable { + + @Override + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray2Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray2Test.java new file mode 100644 index 00000000..9d16330e --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray2Test.java @@ -0,0 +1,130 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.function.Consumer; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +import lombok.Setter; + +public class EzyArray2Test extends CommonBaseTest { + + @Test + public void test() { + EzyArray array = newArrayBuilder() + .append((Object)null) + .append("abc") + .build(); + assert !array.isEmpty(); + System.out.println(array); + + XArray xArray = new XArray(); + assert xArray.isEmpty(); + xArray.setSize(100); + assert !xArray.isEmpty(); + assert !xArray.isNotNullValue(10); + } + + private static class XArray implements EzyArray { + private static final long serialVersionUID = -5111743233496608397L; + + @Setter + private int size; + + @Override + public T get(int index) { + return null; + } + + @Override + public T get(int index, Class type) { + return null; + } + + @SuppressWarnings("rawtypes") + @Override + public Object getValue(int index, Class type) { + return null; + } + + @Override + public boolean isNotNullValue(int index) { + return false; + } + + @Override + public EzyArray sub(int fromIndex, int toIndex) { + return null; + } + + @Override + public int size() { + return size; + } + + @Override + public List toList() { + return null; + } + + @Override + public List toList(Class type) { + return null; + } + + @Override + public A toArray(Class type) { + return null; + } + + @Override + public void add(T item) { + } + + @SuppressWarnings("unchecked") + @Override + public void add(T... items) { + } + + @Override + public void add(Collection items) { + } + + @Override + public T set(int index, Object item) { + return null; + } + + @Override + public T remove(int index) { + return null; + } + + @Override + public void forEach(Consumer action) { + } + + @Override + public Iterator iterator() { + return null; + } + + @Override + public EzyArray duplicate() { + return null; + } + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + } + + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray3Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray3Test.java new file mode 100644 index 00000000..929715fe --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray3Test.java @@ -0,0 +1,83 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; +import static org.testng.Assert.*; + +public class EzyArray3Test extends CommonBaseTest { + + @Test + public void test1() { + EzyArray array = newArrayBuilder() + .append(new boolean[][] {{true, false}, {false, true}}) + .build(); + assertEquals(array.toArray(boolean[].class), new boolean[][] {{true, false}, {false, true}}); + } + + public void test2() { + EzyArray array = newArrayBuilder() + .append(new byte[][] {{1,2},{3,4}}) + .build(); + assertEquals(array.toArray(byte[].class), new byte[][] {{1,2},{3,4}}); + } + + @Test + public void test3() { + EzyArray array = newArrayBuilder() + .append(new char[][] {{'a', 'b'}, {'c', 'd'}}) + .build(); + assertEquals(array.toArray(char[].class), new char[][] {{'a', 'b'}, {'c', 'd'}}); + } + + @Test + public void test4() { + EzyArray array = newArrayBuilder() + .append(new double[][] {{1,2},{3,4}}) + .build(); + assertEquals(array.toArray(double[].class), new double[][] {{1,2},{3,4}}); + } + + @Test + public void test5() { + EzyArray array = newArrayBuilder() + .append(new float[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(float[].class), new float[][] {{1,2}, {3,4}}); + } + + @Test + public void test6() { + EzyArray array = newArrayBuilder() + .append(new int[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(int[].class), new int[][] {{1,2}, {3,4}}); + } + + @Test + public void test7() { + EzyArray array = newArrayBuilder() + .append(new long[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(long[].class), new long[][] {{1,2}, {3,4}}); + } + + @Test + public void test8() { + EzyArray array = newArrayBuilder() + .append(new short[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(short[].class), new short[][] {{1,2}, {3,4}}); + } + + @Test + public void test9() { + EzyArray array = newArrayBuilder() + .append(new String[][] {{"1","2"}, {"3","4"}}) + .build(); + assertEquals(array.toArray(String[].class), new String[][] {{"1","2"}, {"3","4"}}); + } + + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray4Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray4Test.java new file mode 100644 index 00000000..16bc246a --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArray4Test.java @@ -0,0 +1,83 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; +import static org.testng.Assert.*; + +public class EzyArray4Test extends CommonBaseTest { + + @Test + public void test1() { + EzyArray array = newArrayBuilder() + .append(new Boolean[][] {{true, false}, {false, true}}) + .build(); + assertEquals(array.toArray(Boolean[].class), new Boolean[][] {{true, false}, {false, true}}); + } + + public void test2() { + EzyArray array = newArrayBuilder() + .append(new Byte[][] {{1,2},{3,4}}) + .build(); + assertEquals(array.toArray(Byte[].class), new Byte[][] {{1,2},{3,4}}); + } + + @Test + public void test3() { + EzyArray array = newArrayBuilder() + .append(new Character[][] {{'a', 'b'}, {'c', 'd'}}) + .build(); + assertEquals(array.toArray(Character[].class), new Character[][] {{'a', 'b'}, {'c', 'd'}}); + } + + @Test + public void test4() { + EzyArray array = newArrayBuilder() + .append(new Double[][] {{1D,2D},{3D,4D}}) + .build(); + assertEquals(array.toArray(Double[].class), new Double[][] {{1D,2D},{3D,4D}}); + } + + @Test + public void test5() { + EzyArray array = newArrayBuilder() + .append(new Float[][] {{1F,2F}, {3F,4F}}) + .build(); + assertEquals(array.toArray(Float[].class), new Float[][] {{1F,2F}, {3F,4F}}); + } + + @Test + public void test6() { + EzyArray array = newArrayBuilder() + .append(new Integer[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(Integer[].class), new Integer[][] {{1,2}, {3,4}}); + } + + @Test + public void test7() { + EzyArray array = newArrayBuilder() + .append(new Long[][] {{1L,2L}, {3L,4L}}) + .build(); + assertEquals(array.toArray(Long[].class), new Long[][] {{1L,2L}, {3L,4L}}); + } + + @Test + public void test8() { + EzyArray array = newArrayBuilder() + .append(new Short[][] {{1,2}, {3,4}}) + .build(); + assertEquals(array.toArray(Short[].class), new Short[][] {{1,2}, {3,4}}); + } + + @Test + public void test9() { + EzyArray array = newArrayBuilder() + .append(new String[][] {{"1","2"}, {"3","4"}}) + .build(); + assertEquals(array.toArray(String[].class), new String[][] {{"1","2"}, {"3","4"}}); + } + + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArrayListTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArrayListTest.java new file mode 100644 index 00000000..de4cbaf3 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyArrayListTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.impl.EzyArrayList; +import com.tvd12.test.base.BaseTest; + +public class EzyArrayListTest extends BaseTest { + + @Test + public void test() { + EzyArrayList arr = new EzyEzyArrayList(); + arr.add((Object)null); + arr.add("a"); + assert arr.isNotNullValue(1); + assert !arr.isNotNullValue(0); + assert !arr.isNotNullValue(100); + } + + public static class EzyEzyArrayList extends EzyArrayList { + private static final long serialVersionUID = 1L; + + @Override + public void add(Object item) { + list.add(item); + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyConstantTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyConstantTest.java new file mode 100644 index 00000000..ec5e6450 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyConstantTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.test.base.BaseTest; + +public class EzyConstantTest extends BaseTest { + + @Test + public void test() { + EzyConstant ct = EzyConstant.one(); + assert ct.getId() >= 0; + assert ct.getName().length() >= 0; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntity1Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntity1Test.java new file mode 100644 index 00000000..0d42836e --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntity1Test.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import java.util.HashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyEntity; +import com.tvd12.test.base.BaseTest; + +public class EzyEntity1Test extends BaseTest { + + @Test + public void test() { + EzyEntity entity = new EzyEntity() { + }; + Map strs = new HashMap<>(); + strs.put("1", "a"); + entity.setProperties(strs); + assert entity.getProperty("1").equals("a"); + assert entity.getProperty("1", String.class).equals("a"); + assert entity.containsKey("1"); + assert entity.getProperties().containsKey("1"); + entity.removeProperty("1"); + assert entity.getProperty("1") == null; + entity.setProperty(EzyEntity1Test.class, this); + assert entity.getProperty(EzyEntity1Test.class) == this; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntityTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntityTest.java new file mode 100644 index 00000000..26f8d84f --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyEntityTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyEntityTest extends BaseTest { + + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + + protected EzyObjectBuilder newObjectBuilder() { + return EzyEntityFactory.create(EzyObjectBuilder.class); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyHashMapTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyHashMapTest.java new file mode 100644 index 00000000..153b78c2 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyHashMapTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.impl.EzyHashMap; +import com.tvd12.test.base.BaseTest; + +public class EzyHashMapTest extends BaseTest { + + @Test + public void test() { + EzyHashMap map = new ExEzyHashMap(); + map.put("1", "2"); + assert map.isNotNullValue("1"); + assert !map.isNotNullValue("2"); + } + + + public static class ExEzyHashMap extends EzyHashMap { + private static final long serialVersionUID = -5733872612446105669L; + + @SuppressWarnings("unchecked") + @Override + public V put(Object key, Object value) { + return (V) map.put(key, value); + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject1Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject1Test.java new file mode 100644 index 00000000..d28fe656 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject1Test.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import java.util.HashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.entity.impl.EzyHashMap; + +import static org.testng.Assert.*; + +public class EzyObject1Test extends EzyEntityTest { + + @Test + public void test() { + } + + @Test + public void test1() { + Map map = new HashMap<>(); + EzyObjectBuilder firstBuilder + = newObjectBuilder().append("1'", "a'"); + map.put("1", "a"); + EzyObject object = newObjectBuilder() + .append(map) + .append("2", firstBuilder) + .append("3", "c") + .append("4", "d") + .append("5", "e") + .build(); + assertEquals(object.get("1"), "a"); + assertEquals(object.get("1", "b"), "a"); + assertEquals(object.get("3", String.class), "c"); + assertEquals(object.remove("4"), "d"); + assertEquals(object.compute("6", (k,v) -> v != null ? v : "f"), "f"); + assertEquals(object.size(), 5); + assertEquals(object.isEmpty(), false); + assertEquals(object.containsKey("6"), true); + assertEquals(object.keySet().containsAll(Sets.newHashSet("1", "2", "3", "5", "6")), true); + object.entrySet(); + object.toMap(); + object.toString(); + EzyObject clone = object.duplicate(); + assertNotEquals(object, clone); + assertTrue(clone.keySet().containsAll(Sets.newHashSet("1", "2", "3", "5", "6"))); + object.clear(); + assertEquals(object.get("1", "b"), "b"); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void test2() { + EzyObject object = new EzyHashMap() { + private static final long serialVersionUID = -4366815253239566713L; + + @Override + public Object clone() throws CloneNotSupportedException { + throw new CloneNotSupportedException(); + } + }; + object.duplicate(); + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject2Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject2Test.java new file mode 100644 index 00000000..bdd82239 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject2Test.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzyObject2Test extends CommonBaseTest { + + @Test + public void test1() { + EzyObject object = newObjectBuilder() + .append("1", new boolean[][] {{true, false}, {false, true}}) + .append("2", new byte[][] {{1,2},{3,4}}) + .append("3", new char[][] {{'a', 'b'}, {'c', 'd'}}) + .append("4", new double[][] {{1,2},{3,4}}) + .append("5", new float[][] {{1,2}, {3,4}}) + .append("6", new int[][] {{1,2}, {3,4}}) + .append("7", new long[][] {{1,2}, {3,4}}) + .append("8", new short[][] {{1,2}, {3,4}}) + .append("9", new String[][] {{"1","2"}, {"3","4"}}) + .build(); + assertEquals(object.get("1", boolean[][].class), new boolean[][] {{true, false}, {false, true}}); + assertEquals(object.get("2", byte[][].class), new byte[][] {{1,2},{3,4}}); + assertEquals(object.get("3", char[][].class), new char[][] {{'a', 'b'}, {'c', 'd'}}); + assertEquals(object.get("4", double[][].class), new double[][] {{1,2},{3,4}}); + assertEquals(object.get("5", float[][].class), new float[][] {{1,2}, {3,4}}); + assertEquals(object.get("6", int[][].class), new int[][] {{1,2}, {3,4}}); + assertEquals(object.get("7", long[][].class), new long[][] {{1,2}, {3,4}}); + assertEquals(object.get("8", short[][].class), new short[][] {{1,2}, {3,4}}); + assertEquals(object.get("9", String[][].class), new String[][] {{"1","2"}, {"3","4"}}); + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject3Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject3Test.java new file mode 100644 index 00000000..058c6a19 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject3Test.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzyObject3Test extends CommonBaseTest { + + @Test + public void test1() { + EzyObject object = newObjectBuilder() + .append("1", new Boolean[][] {{true, false}, {false, true}}) + .append("2", new Byte[][] {{1,2},{3,4}}) + .append("3", new Character[][] {{'a', 'b'}, {'c', 'd'}}) + .append("4", new Double[][] {{1D,2D},{3D,4D}}) + .append("5", new Float[][] {{1F,2F}, {3F,4F}}) + .append("6", new Integer[][] {{1,2}, {3,4}}) + .append("7", new Long[][] {{1L,2L}, {3L,4L}}) + .append("8", new Short[][] {{1,2}, {3,4}}) + .append("9", new String[][] {{"1","2"}, {"3","4"}}) + .build(); + assertEquals(object.get("1", Boolean[][].class), new Boolean[][] {{true, false}, {false, true}}); + assertEquals(object.get("2", Byte[][].class), new Byte[][] {{1,2},{3,4}}); + assertEquals(object.get("3", Character[][].class), new Character[][] {{'a', 'b'}, {'c', 'd'}}); + assertEquals(object.get("4", Double[][].class), new Double[][] {{1D,2D},{3D,4D}}); + assertEquals(object.get("5", Float[][].class), new Float[][] {{1F,2F}, {3F,4F}}); + assertEquals(object.get("6", Integer[][].class), new Integer[][] {{1,2}, {3,4}}); + assertEquals(object.get("7", Long[][].class), new Long[][] {{1L,2L}, {3L,4L}}); + assertEquals(object.get("8", Short[][].class), new Short[][] {{1,2}, {3,4}}); + assertEquals(object.get("9", String[][].class), new String[][] {{"1","2"}, {"3","4"}}); + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject4Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject4Test.java new file mode 100644 index 00000000..f2bbdd31 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject4Test.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzyObject4Test extends CommonBaseTest { + + @Test + public void test1() { + EzyObject object1 = newObjectBuilder().append("1", "a").build(); + EzyObject object2 = newObjectBuilder().append("2", "b").build(); + EzyObject object = newObjectBuilder() + .append("1", new EzyObject[][] {{object1}, {object2}}) + .build(); + EzyObject[][] itemss = object.get("1", EzyObject[][].class); + assertEquals(itemss[0][0].get("1", String.class), "a"); + assertEquals(itemss[1][0].get("2", String.class), "b"); + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject5Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject5Test.java new file mode 100644 index 00000000..b0ca928b --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject5Test.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzyObject5Test extends CommonBaseTest { + + @Test + public void test1() { + EzyObject object = newObjectBuilder() + .append("1", ABC.A) + .build(); + assertEquals(object.get("1", ABC.class), ABC.A); + } + + public static enum ABC { + A,B,C + } +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject6Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject6Test.java new file mode 100644 index 00000000..dfce7d0c --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyObject6Test.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyRoObject; +import com.tvd12.test.base.BaseTest; + +import lombok.Setter; + +public class EzyObject6Test extends BaseTest { + + @Test + public void test() { + XObject x = new XObject(); + assert x.isEmpty(); + x.setSize(100); + assert !x.isEmpty(); + assert !x.isNotNullValue(""); + } + + @SuppressWarnings("serial") + public static class XObject implements EzyRoObject { + + @Setter + private int size; + + @Override + public Object clone() throws CloneNotSupportedException { + return super.clone(); + } + + @Override + public EzyData duplicate() { + return null; + } + + @Override + public int size() { + return size; + } + + @Override + public boolean containsKey(Object key) { + return false; + } + + @Override + public boolean isNotNullValue(Object key) { + return false; + } + + @Override + public V get(Object key) { + return null; + } + + @Override + public V get(Object key, Class clazz) { + return null; + } + + @SuppressWarnings("rawtypes") + @Override + public Object getValue(Object key, Class type) { + return null; + } + + @Override + public Set keySet() { + return null; + } + + @Override + public Set> entrySet() { + return null; + } + + @SuppressWarnings("rawtypes") + @Override + public Map toMap() { + return null; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyReferenceTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyReferenceTest.java new file mode 100644 index 00000000..1f44c06c --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyReferenceTest.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyReference; +import com.tvd12.test.base.BaseTest; + +public class EzyReferenceTest extends BaseTest { + + @Test + public void test() { + assert (new EzyReference() { + + @Override + public void retain() { + } + + @Override + public void release() { + } + + @Override + public int getReferenceCount() { + return 0; + } + }.releasable()); + + assert (new EzyReference() { + + @Override + public void retain() { + } + + @Override + public void release() { + } + + @Override + public int getReferenceCount() { + return 1; + } + }.releasable()) == false; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyEntityFactoryTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyEntityFactoryTest.java new file mode 100644 index 00000000..0ddeafde --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyEntityFactoryTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.factory; + +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyEntityFactoryTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyLiteEntityFactory.class; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyFactoryTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyFactoryTest.java new file mode 100644 index 00000000..a5f936b2 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyFactoryTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.factory; + +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyFactoryTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyEntityFactory.class; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteCollectionConverterTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteCollectionConverterTest.java new file mode 100644 index 00000000..c029c6a6 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteCollectionConverterTest.java @@ -0,0 +1,256 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzyLiteCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzyLiteOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzySimpleCollectionConverter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzyLiteCollectionConverterTest extends CommonBaseTest { + + private EzyCollectionConverter collectionConverter; + + public EzyLiteCollectionConverterTest() { + super(); + this.collectionConverter = new EzyLiteCollectionConverter(new EzyLiteOutputTransformer()); + } + +// @Test + public void test() { + Collection booleans = Lists.newArrayList(true, false, true); + assertEquals(collectionConverter.toArray(booleans, Boolean.class), + new Boolean[] {true, false, true}); + + Collection bytes = Lists.newArrayList((byte)1, (byte)2, (byte)3); + assertEquals(collectionConverter.toArray(bytes, Byte.class), + new Byte[] {(byte)1, (byte)2, (byte)3}); + + Collection characters = Lists.newArrayList('a', 'b', 'c'); + assertEquals(collectionConverter.toArray(characters, Character.class), + new Character[] {'a', 'b', 'c'}); + + Collection doubles = Lists.newArrayList(1D, 2D, 3D); + assertEquals(collectionConverter.toArray(doubles, Double.class), + new Double[] {1D, 2D, 3D}); + + Collection floats = Lists.newArrayList(1F, 2F, 3F); + assertEquals(collectionConverter.toArray(floats, Float.class), + new Float[] {1F, 2F, 3F}); + + Collection integers = Lists.newArrayList(1, 2, 3); + assertEquals(collectionConverter.toArray(integers, Integer.class), + new Integer[] {1, 2, 3}); + + Collection longs = Lists.newArrayList(1L, 2L, 3L); + assertEquals(collectionConverter.toArray(longs, Long.class), + new Long[] {1L, 2L, 3L}); + + Collection shorts = Lists.newArrayList((short)1, (short)2, (short)3); + assertEquals(collectionConverter.toArray(shorts, Short.class), + new Short[] {(short)1, (short)2, (short)3}); + + Collection strings = Lists.newArrayList("a", "b", "c"); + assertEquals(collectionConverter.toArray(strings, String.class), + new String[] {"a", "b", "c"}); + } + +// @Test + public void test1() { + Collection booleans = Lists.newArrayList(true, false, true); + assertEquals(collectionConverter.toArray(booleans, boolean.class), + new boolean[] {true, false, true}); + + Collection bytes = Lists.newArrayList((byte)1, (byte)2, (byte)3); + assertEquals(collectionConverter.toArray(bytes, byte.class), + new byte[] {(byte)1, (byte)2, (byte)3}); + + Collection characters = Lists.newArrayList('a', 'b', 'c'); + assertEquals(collectionConverter.toArray(characters, char.class), + new char[] {'a', 'b', 'c'}); + + Collection doubles = Lists.newArrayList(1D, 2D, 3D); + assertEquals(collectionConverter.toArray(doubles, double.class), + new double[] {1D, 2D, 3D}); + + Collection floats = Lists.newArrayList(1F, 2F, 3F); + assertEquals(collectionConverter.toArray(floats, float.class), + new float[] {1F, 2F, 3F}); + + Collection integers = Lists.newArrayList(1, 2, 3); + assertEquals(collectionConverter.toArray(integers, int.class), + new int[] {1, 2, 3}); + + Collection longs = Lists.newArrayList(1L, 2L, 3L); + assertEquals(collectionConverter.toArray(longs, long.class), + new long[] {1L, 2L, 3L}); + + Collection shorts = Lists.newArrayList((short)1, (short)2, (short)3); + assertEquals(collectionConverter.toArray(shorts, short.class), + new short[] {(short)1, (short)2, (short)3}); + + Collection strings = Lists.newArrayList("a", "b", "c"); + assertEquals(collectionConverter.toArray(strings, String.class), + new String[] {"a", "b", "c"}); + } + + @Test + public void test2() { + Collection booleanss = new ArrayList<>(); + booleanss.add(newArrayBuilder().append(true, false, true).build()); + booleanss.add(newArrayBuilder().append(false, true, false).build()); + assertEquals(collectionConverter.toArray(booleanss, boolean[].class), + new boolean[][] {{true, false, true}, {false, true, false}}); + + Collection bytess = new ArrayList<>(); + bytess.add(newArrayBuilder().append((byte)1, (byte)2, (byte)3).build()); + bytess.add(newArrayBuilder().append((byte)4, (byte)5, (byte)6).build()); + assertEquals(collectionConverter.toArray(bytess, byte[].class), + new byte[][] {{(byte)1, (byte)2, (byte)3}, {(byte)4, (byte)5, (byte)6}}); + + Collection characterss = new ArrayList<>(); + characterss.add(newArrayBuilder().append('a', 'b', 'c').build()); + characterss.add(newArrayBuilder().append('d', 'e', 'f').build()); + assertEquals(collectionConverter.toArray(characterss, char[].class), + new char[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}}); + + Collection doubless = new ArrayList<>(); + doubless.add(newArrayBuilder().append(1D, 2D, 3D).build()); + doubless.add(newArrayBuilder().append(4D, 5D, 6D).build()); + assertEquals(collectionConverter.toArray(doubless, double[].class), + new double[][] {{1D, 2D, 3D}, {4D, 5D, 6D}}); + + Collection floatss = new ArrayList<>(); + floatss.add(newArrayBuilder().append(1F, 2F, 3F).build()); + floatss.add(newArrayBuilder().append(4F, 5F, 6F).build()); + assertEquals(collectionConverter.toArray(floatss, float[].class), + new float[][] {{1F, 2F, 3F}, {4F, 5F, 6F}}); + + Collection integerss = new ArrayList<>(); + integerss.add(newArrayBuilder().append(1, 2, 3).build()); + integerss.add(newArrayBuilder().append(4, 5, 6).build()); + assertEquals(collectionConverter.toArray(integerss, int[].class), + new int[][] {{1, 2, 3}, {4, 5, 6}}); + + Collection longss = new ArrayList<>(); + longss.add(newArrayBuilder().append(1L, 2L, 3L).build()); + longss.add(newArrayBuilder().append(4L, 5L, 6L).build()); + assertEquals(collectionConverter.toArray(longss, long[].class), + new long[][] {{1L, 2L, 3L}, {4L, 5L, 6L}}); + + Collection shortss = new ArrayList<>(); + shortss.add(newArrayBuilder().append((short)1, (short)2, (short)3).build()); + shortss.add(newArrayBuilder().append((short)4, (short)5, (short)6).build()); + assertEquals(collectionConverter.toArray(shortss, short[].class), + new short[][] {{(short)1, (short)2, (short)3}, {(short)4, (short)5, (short)6}}); + + Collection stringss = new ArrayList<>(); + stringss.add(newArrayBuilder().append("a", "b", "c").build()); + stringss.add(newArrayBuilder().append("d", "e", "f").build()); + assertEquals(collectionConverter.toArray(stringss, String[].class), + new String[][] {{"a", "b", "c"}, {"d", "e", "f"}}); + } + + + @Test + public void test3() { + Collection booleanss = new ArrayList<>(); + booleanss.add(newArrayBuilder().append(true, false, true).build()); + booleanss.add(newArrayBuilder().append(false, true, false).build()); + assertEquals(collectionConverter.toArray(booleanss, Boolean[].class), + new Boolean[][] {{true, false, true}, {false, true, false}}); + + Collection bytess = new ArrayList<>(); + bytess.add(newArrayBuilder().append((byte)1, (byte)2, (byte)3).build()); + bytess.add(newArrayBuilder().append((byte)4, (byte)5, (byte)6).build()); + assertEquals(collectionConverter.toArray(bytess, Byte[].class), + new Byte[][] {{(byte)1, (byte)2, (byte)3}, {(byte)4, (byte)5, (byte)6}}); + + Collection characterss = new ArrayList<>(); + characterss.add(newArrayBuilder().append('a', 'b', 'c').build()); + characterss.add(newArrayBuilder().append('d', 'e', 'f').build()); + assertEquals(collectionConverter.toArray(characterss, Character[].class), + new Character[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}}); + + Collection doubless = new ArrayList<>(); + doubless.add(newArrayBuilder().append(1D, 2D, 3D).build()); + doubless.add(newArrayBuilder().append(4D, 5D, 6D).build()); + assertEquals(collectionConverter.toArray(doubless, Double[].class), + new Double[][] {{1D, 2D, 3D}, {4D, 5D, 6D}}); + + Collection floatss = new ArrayList<>(); + floatss.add(newArrayBuilder().append(1F, 2F, 3F).build()); + floatss.add(newArrayBuilder().append(4F, 5F, 6F).build()); + assertEquals(collectionConverter.toArray(floatss, Float[].class), + new Float[][] {{1F, 2F, 3F}, {4F, 5F, 6F}}); + + Collection integerss = new ArrayList<>(); + integerss.add(newArrayBuilder().append(1, 2, 3).build()); + integerss.add(newArrayBuilder().append(4, 5, 6).build()); + assertEquals(collectionConverter.toArray(integerss, Integer[].class), + new Integer[][] {{1, 2, 3}, {4, 5, 6}}); + + Collection longss = new ArrayList<>(); + longss.add(newArrayBuilder().append(1L, 2L, 3L).build()); + longss.add(newArrayBuilder().append(4L, 5L, 6L).build()); + assertEquals(collectionConverter.toArray(longss, Long[].class), + new Long[][] {{1L, 2L, 3L}, {4L, 5L, 6L}}); + + Collection shortss = new ArrayList<>(); + shortss.add(newArrayBuilder().append((short)1, (short)2, (short)3).build()); + shortss.add(newArrayBuilder().append((short)4, (short)5, (short)6).build()); + assertEquals(collectionConverter.toArray(shortss, Short[].class), + new Short[][] {{(short)1, (short)2, (short)3}, {(short)4, (short)5, (short)6}}); + + Collection stringss = new ArrayList<>(); + stringss.add(newArrayBuilder().append("a", "b", "c").build()); + stringss.add(newArrayBuilder().append("d", "e", "f").build()); + assertEquals(collectionConverter.toArray(stringss, String[].class), + new String[][] {{"a", "b", "c"}, {"d", "e", "f"}}); + } + + @Test + public void test5() { + try { + Method method = EzyLiteCollectionConverter.class + .getDeclaredMethod("toArray", Object.class, Class.class); + method.setAccessible(true); + method.invoke(collectionConverter, new String("abc"), String.class); + } catch(Exception e) { + e.printStackTrace(); + } + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test6() { + new EzySimpleCollectionConverter().toArray(Lists.newArrayList(), Void.class); + } + + @Test + private void test7() { + newArrayBuilder() + .append(new byte[] {1,2,3}, new byte[] {4,5,6}, new byte[]{7,8,9}) + .build(); + EzyArray array = EzyLiteEntityFactory.create(EzyArrayBuilder.class) + .append(EzyBase64.encode2utf(new byte[] {1,2,3})) + .append(EzyBase64.encode2utf(new byte[] {4,5,6})) + .append(EzyBase64.encode2utf(new byte[] {7,8,9})) + .build(); + assertEquals(array.toArray(byte[].class), new byte[][] { + {1, 2, 3}, {4, 5, 6}, {7, 8, 9} + }); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteOutputTransformerTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteOutputTransformerTest.java new file mode 100644 index 00000000..1dc03936 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLiteOutputTransformerTest.java @@ -0,0 +1,354 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyLiteEntityFactory; +import com.tvd12.ezyfoxserver.io.EzyLiteOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.testing.entity.EzyEntityTest; +import static org.testng.Assert.*; + +public class EzyLiteOutputTransformerTest extends EzyEntityTest { + + private EzyOutputTransformer transformer = new EzyLiteOutputTransformer(); + + @Test + public void test() { + assertEquals(transform(newArray(true, false, true), boolean[].class), + new boolean[] {true, false, true}); + assertEquals(transform(newArray((byte)1, (byte)2, (byte)3), byte[].class), + new byte[] {(byte)1, (byte)2, (byte)3}); + assertEquals(transform(new byte[] {(byte)1, (byte)2, (byte)3}, byte[].class), + new byte[] {(byte)1, (byte)2, (byte)3}); + assertEquals(transform(newArray('a', 'b', 'c'), char[].class), + new char[] {'a', 'b', 'c'}); + assertEquals(transform(new byte[] {'a', 'b', 'c'}, char[].class), + new char[] {'a', 'b', 'c'}); + assertEquals(transform(newArray(1D, 2D, 3D), double[].class), + new double[] {1D, 2D, 3D}); + assertEquals(transform(newArray(1F, 2F, 3F), float[].class), + new float[] {1F, 2F, 3F}); + assertEquals(transform(newArray(1, 2, 3), int[].class), + new int[] {1, 2, 3}); + assertEquals(transform(newArray(1L, 2L, 3L), long[].class), + new long[] {1L, 2L, 3L}); + assertEquals(transform(newArray((short)1, (short)2, (short)3), short[].class), + new short[] {(short)1, (short)2, (short)3}); + assertEquals(transform(newArray("a", "b", "c"), String[].class), + new String[] {"a", "b", "c"}); + + assertEquals(transform(newArray(true, false, true), Boolean[].class), + new Boolean[] {true, false, true}); + assertEquals(transform(newArray((byte)1, (byte)2, (byte)3), Byte[].class), + new Byte[] {(byte)1, (byte)2, (byte)3}); + assertEquals(transform(new byte[] {(byte)1, (byte)2, (byte)3}, Byte[].class), + new Byte[] {(byte)1, (byte)2, (byte)3}); + assertEquals(transform(newArray('a', 'b', 'c'), Character[].class), + new Character[] {'a', 'b', 'c'}); + assertEquals(transform(new byte[] {'a', 'b', 'c'}, Character[].class), + new Character[] {'a', 'b', 'c'}); + assertEquals(transform(newArray(1D, 2D, 3D), Double[].class), + new Double[] {1D, 2D, 3D}); + assertEquals(transform(newArray(1F, 2F, 3F), Float[].class), + new Float[] {1F, 2F, 3F}); + assertEquals(transform(newArray(1, 2, 3), Integer[].class), + new Integer[] {1, 2, 3}); + assertEquals(transform(newArray(1L, 2L, 3L), Long[].class), + new Long[] {1L, 2L, 3L}); + assertEquals(transform(newArray((short)1, (short)2, (short)3), Short[].class), + new Short[] {(short)1, (short)2, (short)3}); + assertEquals(transform(newArray("a", "b", "c"), String[].class), + new String[] {"a", "b", "c"}); + } + + @Test + public void test1() { + assertEquals(transform(true, boolean.class), true); + assertEquals(transform(1L, byte.class), (byte)1); + assertEquals(transform(1L, char.class), (char)1); + assertEquals(transform(1L, double.class), 1D); + assertEquals(transform(1L, float.class), (float)1F); + assertEquals(transform(1L, int.class), (int)1); + assertEquals(transform((byte)1, long.class), 1L); + assertEquals(transform(1L, short.class), (short)1); + + assertEquals(transform(true, Boolean.class), true); + assertEquals(transform(1L, Byte.class), (byte)1); + assertEquals(transform(1L, Character.class), (char)1); + assertEquals(transform(1L, Double.class), 1D); + assertEquals(transform(1L, Float.class), (float)1F); + assertEquals(transform(1L, Integer.class), (int)1); + assertEquals(transform((byte)1, Long.class), 1L); + assertEquals(transform(1L, Short.class), (short)1); + assertEquals(transform("a", String.class), "a"); + } + + @Test + public void test2() { + String encode = EzyBase64.encode2utf(EzyStrings.getUtfBytes("dungtv")); + assertEquals(transform(encode, byte[].class), EzyStrings.getUtfBytes("dungtv")); + } + + @Test + public void test3() { + char[] chs = new char[] {'d', 'u', 'n', 'g', 't', 'v'}; + String string = new String(chs); + assertEquals(transform(string, char[].class),chs); + } + + @Test + public void test4() { + EzyObject obj = newObjectBuilder() + .append("1", newArrayBuilder() + .append(new boolean[] {true, false, true}) + .append(new boolean[] {false, true, false}) + .append(new boolean[] {true, false, true})) + .append("2", newArrayBuilder() + .append(new byte[] {1, 2, 3}) + .append(new byte[] {4, 5, 6}) + .append(new byte[] {7, 8, 9})) + .append("3", newArrayBuilder() + .append(new char[] {1, 2, 3}) + .append(new char[] {4, 5, 6}) + .append(new char[] {7, 8, 9})) + .append("4", newArrayBuilder() + .append(new double[] {1, 2, 3}) + .append(new double[] {4, 5, 6}) + .append(new double[] {7, 8, 9})) + .append("5", newArrayBuilder() + .append(new float[] {1, 2, 3}) + .append(new float[] {4, 5, 6}) + .append(new float[] {7, 8, 9})) + .append("6", newArrayBuilder() + .append(new int[] {1, 2, 3}) + .append(new int[] {4, 5, 6}) + .append(new int[] {7, 8, 9})) + .append("7", newArrayBuilder() + .append(new long[] {1, 2, 3}) + .append(new long[] {4, 5, 6}) + .append(new long[] {7, 8, 9})) + .append("8", newArrayBuilder() + .append(new short[] {1, 2, 3}) + .append(new short[] {4, 5, 6}) + .append(new short[] {7, 8, 9})) + .append("9", newArrayBuilder() + .append(new String[] {"1", "2", "3"}, + new String[] {"4", "5", "6"}, + new String[] {"7", "8", "9"})) + .append("10", newArrayBuilder() + .append(new Boolean[] {true, false, true}, + new Boolean[] {false, true, false}, + new Boolean[] {true, false, true})) + .append("11", newArrayBuilder() + .append(new Byte[] {1, 2, 3}, + new Byte[] {4, 5, 6}, + new Byte[] {7, 8, 9})) + .append("12", newArrayBuilder() + .append(new Character[] {1, 2, 3}, + new Character[] {4, 5, 6}, + new Character[] {7, 8, 9})) + .append("13", newArrayBuilder() + .append(new Double[] {1D, 2D, 3D}, + new Double[] {4D, 5D, 6D}, + new Double[] {7D, 8D, 9d})) + .append("14", newArrayBuilder() + .append(new Float[] {1F, 2F, 3F}, + new Float[] {4F, 5F, 6F}, + new Float[] {7F, 8F, 9F})) + .append("15", newArrayBuilder() + .append(new Integer[] {1, 2, 3}, + new Integer[] {4, 5, 6}, + new Integer[] {7, 8, 9})) + .append("16", newArrayBuilder() + .append(new Long[] {1L, 2L, 3L}, + new Long[] {4L, 5L, 6L}, + new Long[] {7L, 8L, 9L})) + .append("17", newArrayBuilder() + .append(new Short[] {1, 2, 3}, + new Short[] {4, 5, 6}, + new Short[] {7, 8, 9})) + .build(); + test(obj); + + } + + @Test + public void test5() { + EzyObject obj = newObjectBuilder() + .append("1", newArrayBuilder() + .append(newArrayBuilder().append(true, false, true)) + .append(newArrayBuilder().append(false, true, false)) + .append(newArrayBuilder().append(true, false, true))) + .append("2", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("3", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("4", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("5", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("6", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("7", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("8", newArrayBuilder() + .append(newArrayBuilder().append(1, 2, 3)) + .append(newArrayBuilder().append(4, 5, 6)) + .append(newArrayBuilder().append(7, 8, 9))) + .append("9", newArrayBuilder() + .append(newArrayBuilder().append("1", "2", "3")) + .append(newArrayBuilder().append("4", "5", "6")) + .append(newArrayBuilder().append("7", "8", "9"))) + .append("10", newArrayBuilder() + .append(newArrayBuilder().append(new Boolean[] {true, false, true})) + .append(newArrayBuilder().append(new Boolean[] {false, true, false})) + .append(newArrayBuilder().append(new Boolean[] {true, false, true}))) + .append("11", newArrayBuilder() + .append(newArrayBuilder().append(new Byte[] {1, 2, 3})) + .append(newArrayBuilder().append(new Byte[] {4, 5, 6})) + .append(newArrayBuilder().append(new Byte[] {7, 8, 9}))) + .append("12", newArrayBuilder() + .append(newArrayBuilder().append(new Character[] {1, 2, 3})) + .append(newArrayBuilder().append(new Character[] {4, 5, 6})) + .append(newArrayBuilder().append(new Character[] {7, 8, 9}))) + .append("13", newArrayBuilder() + .append(newArrayBuilder().append(new Double[] {1D, 2D, 3D})) + .append(newArrayBuilder().append(new Double[] {4D, 5D, 6D})) + .append(newArrayBuilder().append(new Double[] {7D, 8D, 9d}))) + .append("14", newArrayBuilder() + .append(newArrayBuilder().append(new Float[] {1F, 2F, 3F})) + .append(newArrayBuilder().append(new Float[] {4F, 5F, 6F})) + .append(newArrayBuilder().append(new Float[] {7F, 8F, 9F}))) + .append("15", newArrayBuilder() + .append(newArrayBuilder().append(new Integer[] {1, 2, 3})) + .append(newArrayBuilder().append(new Integer[] {4, 5, 6})) + .append(newArrayBuilder().append(new Integer[] {7, 8, 9}))) + .append("16", newArrayBuilder() + .append(newArrayBuilder().append(new Long[] {1L, 2L, 3L})) + .append(newArrayBuilder().append(new Long[] {4L, 5L, 6L})) + .append(newArrayBuilder().append(new Long[] {7L, 8L, 9L}))) + .append("17", newArrayBuilder() + .append(newArrayBuilder().append(new Short[] {1, 2, 3})) + .append(newArrayBuilder().append(new Short[] {4, 5, 6})) + .append(newArrayBuilder().append(new Short[] {7, 8, 9}))) + .build(); + test(obj); + + } + + public void test(EzyObject obj) { + //check + assertEquals(obj.get("1", boolean[][].class), new boolean[][] { + new boolean[] {true, false, true}, + new boolean[] {false, true, false}, + new boolean[] {true, false, true}}); + assertEquals(obj.get("2", byte[][].class), new byte[][] { + new byte[] {1, 2, 3}, + new byte[] {4, 5, 6}, + new byte[] {7, 8, 9}}); + assertEquals(obj.get("3", char[][].class), new char[][] { + new char[] {1, 2, 3}, + new char[] {4, 5, 6}, + new char[] {7, 8, 9}}); + assertEquals(obj.get("4", double[][].class), new double[][] { + new double[] {1, 2, 3}, + new double[] {4, 5, 6}, + new double[] {7, 8, 9}}); + assertEquals(obj.get("5", float[][].class), new float[][] { + new float[] {1, 2, 3}, + new float[] {4, 5, 6}, + new float[] {7, 8, 9}}); + assertEquals(obj.get("6", int[][].class), new int[][] { + new int[] {1, 2, 3}, + new int[] {4, 5, 6}, + new int[] {7, 8, 9}}); + assertEquals(obj.get("7", long[][].class), new long[][] { + new long[] {1, 2, 3}, + new long[] {4, 5, 6}, + new long[] {7, 8, 9}}); + assertEquals(obj.get("8", short[][].class), new short[][] { + new short[] {1, 2, 3}, + new short[] {4, 5, 6}, + new short[] {7, 8, 9}}); + assertEquals(obj.get("9", String[][].class), new String[][] { + new String[] {"1", "2", "3"}, + new String[] {"4", "5", "6"}, + new String[] {"7", "8", "9"}}); + assertEquals(obj.get("10", Boolean[][].class), new Boolean[][] { + new Boolean[] {true, false, true}, + new Boolean[] {false, true, false}, + new Boolean[] {true, false, true}}); + assertEquals(obj.get("11", Byte[][].class), new Byte[][] { + new Byte[] {1, 2, 3}, + new Byte[] {4, 5, 6}, + new Byte[] {7, 8, 9}}); + assertEquals(obj.get("12", Character[][].class), new Character[][] { + new Character[] {1, 2, 3}, + new Character[] {4, 5, 6}, + new Character[] {7, 8, 9}}); + assertEquals(obj.get("13", Double[][].class), new Double[][] { + new Double[] {1D, 2D, 3D}, + new Double[] {4D, 5D, 6D}, + new Double[] {7D, 8D, 9d}}); + assertEquals(obj.get("14", Float[][].class), new Float[][] { + new Float[] {1F, 2F, 3F}, + new Float[] {4F, 5F, 6F}, + new Float[] {7F, 8F, 9F}}); + assertEquals(obj.get("15", Integer[][].class), new Integer[][] { + new Integer[] {1, 2, 3}, + new Integer[] {4, 5, 6}, + new Integer[] {7, 8, 9}}); + assertEquals(obj.get("16", Long[][].class), new Long[][] { + new Long[] {1L, 2L, 3L}, + new Long[] {4L, 5L, 6L}, + new Long[] {7L, 8L, 9L}}); + assertEquals(obj.get("17", Short[][].class), new Short[][] { + new Short[] {1, 2, 3}, + new Short[] {4, 5, 6}, + new Short[] {7, 8, 9}}); + } + + @SuppressWarnings("rawtypes") + private Object transform(Object value, Class type) { + return transformer.transform(value, type); + } + + @SuppressWarnings("unchecked") + private EzyArray newArray(T... items) { + return newArrayBuilder().append(items).build(); + } + + @Override + protected EzyObjectBuilder newObjectBuilder() { + return EzyLiteEntityFactory.create(EzyObjectBuilder.class); + } + + @Override + protected EzyArrayBuilder newArrayBuilder() { + return EzyLiteEntityFactory.create(EzyArrayBuilder.class); + } + + public static void main(String[] args) { + new EzyLiteOutputTransformerTest().test5(); + } + + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleCollectionConverterTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleCollectionConverterTest.java new file mode 100644 index 00000000..fa362042 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleCollectionConverterTest.java @@ -0,0 +1,248 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collection; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.io.EzyCollectionConverter; +import com.tvd12.ezyfoxserver.io.EzySimpleCollectionConverter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.testing.CommonBaseTest; + +public class EzySimpleCollectionConverterTest extends CommonBaseTest { + + private EzyCollectionConverter collectionConverter; + + public EzySimpleCollectionConverterTest() { + super(); + this.collectionConverter = new EzySimpleCollectionConverter(); + } + + @Test + public void test() { + Collection booleans = Lists.newArrayList(true, false, true); + assertEquals(collectionConverter.toArray(booleans, Boolean.class), + new Boolean[] {true, false, true}); + + Collection bytes = Lists.newArrayList((byte)1, (byte)2, (byte)3); + assertEquals(collectionConverter.toArray(bytes, Byte.class), + new Byte[] {(byte)1, (byte)2, (byte)3}); + + Collection characters = Lists.newArrayList('a', 'b', 'c'); + assertEquals(collectionConverter.toArray(characters, Character.class), + new Character[] {'a', 'b', 'c'}); + + Collection doubles = Lists.newArrayList(1D, 2D, 3D); + assertEquals(collectionConverter.toArray(doubles, Double.class), + new Double[] {1D, 2D, 3D}); + + Collection floats = Lists.newArrayList(1F, 2F, 3F); + assertEquals(collectionConverter.toArray(floats, Float.class), + new Float[] {1F, 2F, 3F}); + + Collection integers = Lists.newArrayList(1, 2, 3); + assertEquals(collectionConverter.toArray(integers, Integer.class), + new Integer[] {1, 2, 3}); + + Collection longs = Lists.newArrayList(1L, 2L, 3L); + assertEquals(collectionConverter.toArray(longs, Long.class), + new Long[] {1L, 2L, 3L}); + + Collection shorts = Lists.newArrayList((short)1, (short)2, (short)3); + assertEquals(collectionConverter.toArray(shorts, Short.class), + new Short[] {(short)1, (short)2, (short)3}); + + Collection strings = Lists.newArrayList("a", "b", "c"); + assertEquals(collectionConverter.toArray(strings, String.class), + new String[] {"a", "b", "c"}); + + EzyObject object = newObjectBuilder().append("1", "a").build(); + assertEquals(collectionConverter.toArray(Lists.newArrayList(object), EzyObject.class), + new EzyObject[] {object}); + } + + @Test + public void test1() { + Collection booleans = Lists.newArrayList(true, false, true); + assertEquals(collectionConverter.toArray(booleans, boolean.class), + new boolean[] {true, false, true}); + + Collection bytes = Lists.newArrayList((byte)1, (byte)2, (byte)3); + assertEquals(collectionConverter.toArray(bytes, byte.class), + new byte[] {(byte)1, (byte)2, (byte)3}); + + Collection characters = Lists.newArrayList('a', 'b', 'c'); + assertEquals(collectionConverter.toArray(characters, char.class), + new char[] {'a', 'b', 'c'}); + + Collection doubles = Lists.newArrayList(1D, 2D, 3D); + assertEquals(collectionConverter.toArray(doubles, double.class), + new double[] {1D, 2D, 3D}); + + Collection floats = Lists.newArrayList(1F, 2F, 3F); + assertEquals(collectionConverter.toArray(floats, float.class), + new float[] {1F, 2F, 3F}); + + Collection integers = Lists.newArrayList(1, 2, 3); + assertEquals(collectionConverter.toArray(integers, int.class), + new int[] {1, 2, 3}); + + Collection longs = Lists.newArrayList(1L, 2L, 3L); + assertEquals(collectionConverter.toArray(longs, long.class), + new long[] {1L, 2L, 3L}); + + Collection shorts = Lists.newArrayList((short)1, (short)2, (short)3); + assertEquals(collectionConverter.toArray(shorts, short.class), + new short[] {(short)1, (short)2, (short)3}); + + Collection strings = Lists.newArrayList("a", "b", "c"); + assertEquals(collectionConverter.toArray(strings, String.class), + new String[] {"a", "b", "c"}); + } + + @Test + public void test2() { + Collection> booleanss = new ArrayList<>(); + booleanss.add(Lists.newArrayList(true, false, true)); + booleanss.add(Lists.newArrayList(false, true, false)); + assertEquals(collectionConverter.toArray(booleanss, boolean[].class), + new boolean[][] {{true, false, true}, {false, true, false}}); + + Collection> bytess = new ArrayList<>(); + bytess.add(Lists.newArrayList((byte)1, (byte)2, (byte)3)); + bytess.add(Lists.newArrayList((byte)4, (byte)5, (byte)6)); + assertEquals(collectionConverter.toArray(bytess, byte[].class), + new byte[][] {{(byte)1, (byte)2, (byte)3}, {(byte)4, (byte)5, (byte)6}}); + + Collection> characterss = new ArrayList<>(); + characterss.add(Lists.newArrayList('a', 'b', 'c')); + characterss.add(Lists.newArrayList('d', 'e', 'f')); + assertEquals(collectionConverter.toArray(characterss, char[].class), + new char[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}}); + + Collection> doubless = new ArrayList<>(); + doubless.add(Lists.newArrayList(1D, 2D, 3D)); + doubless.add(Lists.newArrayList(4D, 5D, 6D)); + assertEquals(collectionConverter.toArray(doubless, double[].class), + new double[][] {{1D, 2D, 3D}, {4D, 5D, 6D}}); + + Collection> floatss = new ArrayList<>(); + floatss.add(Lists.newArrayList(1F, 2F, 3F)); + floatss.add(Lists.newArrayList(4F, 5F, 6F)); + assertEquals(collectionConverter.toArray(floatss, float[].class), + new float[][] {{1F, 2F, 3F}, {4F, 5F, 6F}}); + + Collection> integerss = new ArrayList<>(); + integerss.add(Lists.newArrayList(1, 2, 3)); + integerss.add(Lists.newArrayList(4, 5, 6)); + assertEquals(collectionConverter.toArray(integerss, int[].class), + new int[][] {{1, 2, 3}, {4, 5, 6}}); + + Collection> longss = new ArrayList<>(); + longss.add(Lists.newArrayList(1L, 2L, 3L)); + longss.add(Lists.newArrayList(4L, 5L, 6L)); + assertEquals(collectionConverter.toArray(longss, long[].class), + new long[][] {{1L, 2L, 3L}, {4L, 5L, 6L}}); + + Collection> shortss = new ArrayList<>(); + shortss.add(Lists.newArrayList((short)1, (short)2, (short)3)); + shortss.add(Lists.newArrayList((short)4, (short)5, (short)6)); + assertEquals(collectionConverter.toArray(shortss, short[].class), + new short[][] {{(short)1, (short)2, (short)3}, {(short)4, (short)5, (short)6}}); + + Collection> stringss = new ArrayList<>(); + stringss.add(Lists.newArrayList("a", "b", "c")); + stringss.add(Lists.newArrayList("d", "e", "f")); + assertEquals(collectionConverter.toArray(stringss, String[].class), + new String[][] {{"a", "b", "c"}, {"d", "e", "f"}}); + } + + + @Test + public void test3() { + Collection> booleanss = new ArrayList<>(); + booleanss.add(Lists.newArrayList(true, false, true)); + booleanss.add(Lists.newArrayList(false, true, false)); + assertEquals(collectionConverter.toArray(booleanss, Boolean[].class), + new Boolean[][] {{true, false, true}, {false, true, false}}); + + Collection> bytess = new ArrayList<>(); + bytess.add(Lists.newArrayList((byte)1, (byte)2, (byte)3)); + bytess.add(Lists.newArrayList((byte)4, (byte)5, (byte)6)); + assertEquals(collectionConverter.toArray(bytess, Byte[].class), + new Byte[][] {{(byte)1, (byte)2, (byte)3}, {(byte)4, (byte)5, (byte)6}}); + + Collection> characterss = new ArrayList<>(); + characterss.add(Lists.newArrayList('a', 'b', 'c')); + characterss.add(Lists.newArrayList('d', 'e', 'f')); + assertEquals(collectionConverter.toArray(characterss, Character[].class), + new Character[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}}); + + Collection> doubless = new ArrayList<>(); + doubless.add(Lists.newArrayList(1D, 2D, 3D)); + doubless.add(Lists.newArrayList(4D, 5D, 6D)); + assertEquals(collectionConverter.toArray(doubless, Double[].class), + new Double[][] {{1D, 2D, 3D}, {4D, 5D, 6D}}); + + Collection> floatss = new ArrayList<>(); + floatss.add(Lists.newArrayList(1F, 2F, 3F)); + floatss.add(Lists.newArrayList(4F, 5F, 6F)); + assertEquals(collectionConverter.toArray(floatss, Float[].class), + new Float[][] {{1F, 2F, 3F}, {4F, 5F, 6F}}); + + Collection> integerss = new ArrayList<>(); + integerss.add(Lists.newArrayList(1, 2, 3)); + integerss.add(Lists.newArrayList(4, 5, 6)); + assertEquals(collectionConverter.toArray(integerss, Integer[].class), + new Integer[][] {{1, 2, 3}, {4, 5, 6}}); + + Collection> longss = new ArrayList<>(); + longss.add(Lists.newArrayList(1L, 2L, 3L)); + longss.add(Lists.newArrayList(4L, 5L, 6L)); + assertEquals(collectionConverter.toArray(longss, Long[].class), + new Long[][] {{1L, 2L, 3L}, {4L, 5L, 6L}}); + + Collection> shortss = new ArrayList<>(); + shortss.add(Lists.newArrayList((short)1, (short)2, (short)3)); + shortss.add(Lists.newArrayList((short)4, (short)5, (short)6)); + assertEquals(collectionConverter.toArray(shortss, Short[].class), + new Short[][] {{(short)1, (short)2, (short)3}, {(short)4, (short)5, (short)6}}); + + Collection> stringss = new ArrayList<>(); + stringss.add(Lists.newArrayList("a", "b", "c")); + stringss.add(Lists.newArrayList("d", "e", "f")); + assertEquals(collectionConverter.toArray(stringss, String[].class), + new String[][] {{"a", "b", "c"}, {"d", "e", "f"}}); + } + + @Test + public void test4() { + assertEquals(collectionConverter.toArray( + Lists.newArrayList( + EzyBase64.encode2utf(new byte[] {1, 2, 3}), + EzyBase64.encode2utf(new byte[] {3, 4, 5})), + Byte[].class), + new Byte[][] {{1, 2, 3}, {3, 4, 5}}); + } + + @Test + public void test5() { + assertEquals(collectionConverter.toArray( + Lists.newArrayList( + new byte[] {1, 2, 3}, + new byte[] {3, 4, 5}), + Byte[].class), + new Byte[][] {{1, 2, 3}, {3, 4, 5}}); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test6() { + new EzySimpleCollectionConverter().toArray(Lists.newArrayList(), Void.class); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleInputTransformerTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleInputTransformerTest.java new file mode 100644 index 00000000..5039f1dc --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleInputTransformerTest.java @@ -0,0 +1,90 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.io.EzyInputTransformer; +import com.tvd12.ezyfoxserver.io.EzySimpleInputTransformer; +import com.tvd12.ezyfoxserver.testing.entity.EzyEntityTest; +import static org.testng.Assert.*; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +public class EzySimpleInputTransformerTest extends EzyEntityTest { + + private EzyInputTransformer transformer = new EzySimpleInputTransformer(); + + @Test + public void test() { + assertEquals(transform(new boolean[] {true, false, true}), + Lists.newArrayList(true, false, true)); + + assertEquals(transform(new double[] {1D, 2D, 3D}), + Lists.newArrayList(1D, 2D, 3D)); + + assertEquals(transform(new float[] {1F, 2F, 3F}), + Lists.newArrayList(1F, 2F, 3F)); + + assertEquals(transform(new int[] {1, 2, 3}), + Lists.newArrayList(1, 2, 3)); + + assertEquals(transform(new long[] {1L, 2L, 3L}), + Lists.newArrayList(1L, 2L, 3L)); + + assertEquals(transform(new short[] {(short)1, (short)2, (short)3}), + Lists.newArrayList((short)1, (short)2, (short)3)); + + assertEquals(transform(new String[] {"a", "b", "c"}), + Lists.newArrayList("a", "b", "c")); + + + assertEquals(transform(new Boolean[] {true, false, true}), + Lists.newArrayList(true, false, true)); + + assertEquals(transform(new Byte[] {1, 2, 3}), + new byte[] {1, 2, 3}); + + assertEquals(transform(new Character[] {'a', 'b', 'c'}), + new byte[] {'a', 'b', 'c'}); + + assertEquals(transform(new Double[] {1D, 2D, 3D}), + Lists.newArrayList(1D, 2D, 3D)); + + assertEquals(transform(new Float[] {1F, 2F, 3F}), + Lists.newArrayList(1F, 2F, 3F)); + + assertEquals(transform(new Integer[] {1, 2, 3}), + Lists.newArrayList(1, 2, 3)); + + assertEquals(transform(new Long[] {1L, 2L, 3L}), + Lists.newArrayList(1L, 2L, 3L)); + + assertEquals(transform(new Short[] {(short)1, (short)2, (short)3}), + Lists.newArrayList((short)1, (short)2, (short)3)); + + assertEquals(transform(new String[] {"a", "b", "c"}), + Lists.newArrayList("a", "b", "c")); + + assertEquals(transform(String.class), String.class.getName()); + + EzyObject[] objects = new EzyObject[] { + newObjectBuilder().append("1", "a").build() + }; + assertEquals(((EzyArray)transform(objects)).toList(), + Lists.newArrayList(objects)); + + assertEquals(transform(LocalDate.of(2017, 05, 30)), "2017-05-30"); + + assertEquals(transform(LocalDateTime.of(2017, 05, 30, 12, 34, 56, 78)), "2017-05-30T12:34:56:000"); + + transformer.transform(newArrayBuilder()); + } + + private Object transform(Object value) { + return transformer.transform(value); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleOutputTransformerTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleOutputTransformerTest.java new file mode 100644 index 00000000..0b49140d --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleOutputTransformerTest.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.io.EzyOutputTransformer; +import com.tvd12.ezyfoxserver.io.EzySimpleOutputTransformer; +import com.tvd12.ezyfoxserver.testing.entity.EzyEntityTest; + +public class EzySimpleOutputTransformerTest extends EzyEntityTest { + + private EzyOutputTransformer transfomer + = new EzySimpleOutputTransformer(); + + @Test + public void test() { + ClassA classA = new ClassA(); + EzyArray array = newArray(); + assertNull(transfomer.transform(null, String.class)); + assertEquals(transfomer.transform(classA, ClassA.class), classA); + assertEquals(transfomer.transform(String.class.getName(), Class.class), String.class); + assertEquals((((EzyObject[])transfomer.transform(array, EzyObject[].class))).length, 1); + + assertNull(transfomer.transform("124", Date.class)); + assertNull(transfomer.transform("124", Class.class)); + + assertNull(transfomer.transform("124", LocalDate.class)); + assertNull(transfomer.transform("124", LocalDateTime.class)); + + assertEquals(transfomer.transform("2017-05-30", LocalDate.class), + LocalDate.of(2017, 05, 30)); + assertEquals(transfomer.transform("2017-05-30T12:34:56:000", LocalDateTime.class), + LocalDateTime.of(2017, 05, 30, 12, 34, 56, 0)); + } + + private EzyArray newArray() { + EzyObjectBuilder objectBuilder = EzyEntityFactory.create(EzyObjectBuilder.class) + .append("1", "a"); + return EzyEntityFactory.create(EzyArrayBuilder.class).append(objectBuilder).build(); + } + + public static class ClassA { + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool1Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool1Test.java new file mode 100644 index 00000000..1ae497a5 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool1Test.java @@ -0,0 +1,145 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executors; +import java.util.function.Supplier; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyVoid; +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; +import com.tvd12.test.base.BaseTest; + +public class EzyObjectPool1Test extends BaseTest { + + @Test + public void test() throws Exception { + MyTestObjectPool pool = MyTestObjectPool.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + Thread.sleep(2 * 1000); + pool.destroy(); + + pool.getRemainObjects(); + } + + @Test + public void test1() throws Exception { + MyTestObjectPool pool = MyTestObjectPool.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .pool(new ConcurrentLinkedQueue<>()) + .objectFactory(new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }) + .validationService(Executors.newSingleThreadScheduledExecutor()) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + Thread.sleep(2 * 1000); + + } + + @Test + public void test2() throws Exception { + MyTestObjectPool pool = MyTestObjectPool.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .pool(new ConcurrentLinkedQueue<>()) + .objectFactory(new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }) + .validationService(Executors.newSingleThreadScheduledExecutor()) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + try { + Method tryReturnObject = EzyObjectPool.class.getDeclaredMethod("tryReturnObject", Object.class); + tryReturnObject.setAccessible(true); + Object invoke = tryReturnObject.invoke(pool, (String)null); + assertEquals(invoke, false); + } catch(Exception e) { + e.printStackTrace(); + } + + try { + Method runWithLock = EzyObjectPool.class.getDeclaredMethod("runWithLock", EzyVoid.class); + runWithLock.setAccessible(true); + runWithLock.invoke(pool, new EzyVoid() { + + @Override + public void apply() { + throw new RuntimeException(); + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + + try { + Method returnWithLock = EzyObjectPool.class.getDeclaredMethod("returnWithLock", Supplier.class); + returnWithLock.setAccessible(true); + returnWithLock.invoke(pool, new Supplier() { + @Override + public String get() { + throw new RuntimeException(); + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool2Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool2Test.java new file mode 100644 index 00000000..8fe3f7d0 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool2Test.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import org.testng.annotations.Test; + +import com.tvd12.test.base.BaseTest; + +public class EzyObjectPool2Test extends BaseTest { + + @Test + public void test() throws Exception { + MyTestObjectPool2 pool = MyTestObjectPool2.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + Thread.sleep(2 * 1000); + pool.destroy(); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool3Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool3Test.java new file mode 100644 index 00000000..101bfcbe --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool3Test.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import org.testng.annotations.Test; + +import com.tvd12.test.base.BaseTest; + +public class EzyObjectPool3Test extends BaseTest { + + @Test + public void test() throws Exception { + MyTestObjectPool3 pool = MyTestObjectPool3.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + Thread.sleep(2 * 1000); + pool.destroy(); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool4Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool4Test.java new file mode 100644 index 00000000..93853814 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool4Test.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import org.testng.annotations.Test; + +import com.tvd12.test.base.BaseTest; + +public class EzyObjectPool4Test extends BaseTest { + + @Test + public void test() throws Exception { + MyTestObjectPool4 pool = MyTestObjectPool4.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + Thread.sleep(2 * 1000); + pool.destroy(); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool5Test.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool5Test.java new file mode 100644 index 00000000..a51fa45a --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/EzyObjectPool5Test.java @@ -0,0 +1,103 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executors; +import java.util.function.Supplier; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyVoid; +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; +import com.tvd12.test.base.BaseTest; + +public class EzyObjectPool5Test extends BaseTest { + + @Test + public void test2() throws Exception { + MyTestObjectPool pool = MyTestObjectPool.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .pool(new ConcurrentLinkedQueue<>()) + .objectFactory(new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }) + .validationService(Executors.newSingleThreadScheduledExecutor()) + .build(); + pool.start(); + MyTestObject o1 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o2 = pool.borrowOne(); + Thread.sleep(31); + MyTestObject o3 = pool.borrowOne(); + Thread.sleep(31); + + pool.returnOne(o1); + Thread.sleep(31); + pool.returnOne(o2); + Thread.sleep(31); + pool.returnOne(o3); + + try { + Method tryReturnObject = EzyObjectPool.class.getDeclaredMethod("tryReturnObject", Object.class); + tryReturnObject.setAccessible(true); + Object invoke = tryReturnObject.invoke(pool, (String)null); + assertEquals(invoke, false); + } catch(Exception e) { + e.printStackTrace(); + } + + try { + Method runWithLock = EzyObjectPool.class.getDeclaredMethod("runWithLock", EzyVoid.class); + runWithLock.setAccessible(true); + runWithLock.invoke(pool, new EzyVoid() { + + @Override + public void apply() { + throw new RuntimeException(); + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + + try { + Method returnWithLock = EzyObjectPool.class.getDeclaredMethod("returnWithLock", Supplier.class); + returnWithLock.setAccessible(true); + returnWithLock.invoke(pool, new Supplier() { + @Override + public String get() { + throw new RuntimeException(); + } + }); + } catch(Exception e) { + e.printStackTrace(); + } + } + + @Test + public void test3() throws Exception { + MyTestObjectPool5 pool = MyTestObjectPool5.builder() + .maxObjects(3) + .minObjects(1) + .validationInterval(30) + .pool(new ConcurrentLinkedQueue<>()) + .objectFactory(new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }) + .validationService(Executors.newSingleThreadScheduledExecutor()) + .build(); + pool.start(); + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObject.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObject.java new file mode 100644 index 00000000..99b3a52b --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObject.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import java.util.concurrent.atomic.AtomicInteger; + +import lombok.Getter; + +public class MyTestObject { + + @Getter + private int id; + + private static final AtomicInteger ID_GENERATOR = new AtomicInteger(0); + + public MyTestObject() { + this(ID_GENERATOR.incrementAndGet()); + } + + public MyTestObject(int id) { + this.id = id; + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool.java new file mode 100644 index 00000000..42f32bef --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool.java @@ -0,0 +1,55 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import java.util.List; + +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; + +public class MyTestObjectPool extends EzyObjectPool { + + protected MyTestObjectPool(Builder builder) { + super(builder); + } + + public MyTestObject borrowOne() { + return borrowObject(); + } + + public void returnOne(MyTestObject object) { + returnObject(object); + } + + @Override + public List getRemainObjects() { + return super.getRemainObjects(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyObjectPool.Builder { + + @Override + public MyTestObjectPool build() { + return new MyTestObjectPool(this); + } + + @Override + protected String getProductName() { + return "test-object"; + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool2.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool2.java new file mode 100644 index 00000000..8eb4aeb5 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool2.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; + +public class MyTestObjectPool2 extends EzyObjectPool { + + protected MyTestObjectPool2(Builder builder) { + super(builder); + } + + public MyTestObject borrowOne() { + return borrowObject(); + } + + public void returnOne(MyTestObject object) { + returnObject(object); + } + + @Override + protected boolean isStaleObject(MyTestObject object) { + return object.getId() % 2 == 0; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyObjectPool.Builder { + + @Override + public MyTestObjectPool2 build() { + return new MyTestObjectPool2(this); + } + + @Override + protected String getProductName() { + return "test-object"; + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool3.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool3.java new file mode 100644 index 00000000..6f701c7f --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool3.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; + +public class MyTestObjectPool3 extends EzyObjectPool { + + protected MyTestObjectPool3(Builder builder) { + super(builder); + } + + public MyTestObject borrowOne() { + return borrowObject(); + } + + public void returnOne(MyTestObject object) { + returnObject(object); + } + + @Override + protected boolean isStaleObject(MyTestObject object) { + return object.getId() % 2 == 0; + } + + @Override + protected void removeStaleObjects() { + throw new RuntimeException(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyObjectPool.Builder { + + @Override + public MyTestObjectPool3 build() { + return new MyTestObjectPool3(this); + } + + @Override + protected String getProductName() { + return "test-object"; + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool4.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool4.java new file mode 100644 index 00000000..35cfe9f9 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool4.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; + +public class MyTestObjectPool4 extends EzyObjectPool { + + protected MyTestObjectPool4(Builder builder) { + super(builder); + } + + public MyTestObject borrowOne() { + return borrowObject(); + } + + public void returnOne(MyTestObject object) { + returnObject(object); + } + + @Override + protected boolean isStaleObject(MyTestObject object) { + return object.getId() % 2 == 0; + } + + @Override + protected void tryShutdown() { + throw new RuntimeException(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyObjectPool.Builder { + + @Override + public MyTestObjectPool4 build() { + return new MyTestObjectPool4(this); + } + + @Override + protected String getProductName() { + return "test-object"; + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool5.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool5.java new file mode 100644 index 00000000..9d97513c --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/pattern/MyTestObjectPool5.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.testing.pattern; + +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; + +public class MyTestObjectPool5 extends EzyObjectPool { + + protected MyTestObjectPool5(Builder builder) { + super(builder); + this.initializeObjects(); + } + + public MyTestObject borrowOne() { + return borrowObject(); + } + + public void returnOne(MyTestObject object) { + returnObject(object); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyObjectPool.Builder { + + @Override + public MyTestObjectPool5 build() { + return new MyTestObjectPool5(this); + } + + @Override + protected String getProductName() { + return "test-object"; + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyObjectFactory() { + @Override + public MyTestObject newProduct() { + return new MyTestObject(); + } + }; + } + + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java deleted file mode 100644 index 0517730a..00000000 --- a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.tvd12.ezyfoxserver.testing.performance; - -import org.testng.annotations.Test; - -import com.tvd12.ezyfoxserver.io.EzyBytes; -import com.tvd12.test.performance.Performance; - -public class EzyBytesCopyTest { - - @Test - public void test1() { - byte[][] bytess = new byte[][] { - {1,2},{3,4} - }; - long time = Performance.create() - .loop(1000000) - .test(()-> { - EzyBytes.copy(bytess); - }) - .getTime(); - System.out.println("test1 elapsed time = " + time); - } - -} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/NewArrayTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/NewArrayTest.java index 40b8571a..cf56c552 100644 --- a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/NewArrayTest.java +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/performance/NewArrayTest.java @@ -1,9 +1,11 @@ package com.tvd12.ezyfoxserver.testing.performance; +import java.util.HashMap; + import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.factory.EzyFactory; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; import com.tvd12.test.base.BaseTest; import com.tvd12.test.performance.Performance; @@ -11,11 +13,11 @@ public class NewArrayTest extends BaseTest { @Test public void test1() { - EzyFactory.create(EzyArrayBuilder.class); +// EzyFactory.create(EzyArrayBuilder.class); long time = Performance.create() - .loop(1) + .loop(1000000) .test(()-> { - EzyFactory.create(EzyArrayBuilder.class); + EzyEntityFactory.create(EzyArrayBuilder.class); }) .getTime(); System.out.println("test1 elapsed time = " + time); @@ -23,14 +25,15 @@ public void test1() { @Test public void test2() { - EzyFactory.create(EzyArrayBuilder.class); + EzyEntityFactory.create(EzyArrayBuilder.class); long time = Performance.create() - .loop(1) + .loop(1000000) .test(()-> { - EzyArrayBuilder builder = EzyFactory.create(EzyArrayBuilder.class); + EzyArrayBuilder builder = EzyEntityFactory.create(EzyArrayBuilder.class); builder.append((Object)null); builder.append(""); builder.append(1); + builder.append(new HashMap<>()); }) .getTime(); System.out.println("test2 elapsed time = " + time); diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntityBuildersTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntityBuildersTest.java new file mode 100644 index 00000000..9ac241b6 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntityBuildersTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; +import com.tvd12.test.base.BaseTest; + +public class EzyEntityBuildersTest extends BaseTest { + + @Test + public void test() { + XEntityBuilders bd = new XEntityBuilders(); + bd.newObjectBuilder(); + } + + public static class XEntityBuilders extends EzyEntityBuilders { + @Override + protected EzyObjectBuilder newObjectBuilder() { + return super.newObjectBuilder(); + } + } + +} diff --git a/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLiteEntityBuildersTest.java b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLiteEntityBuildersTest.java new file mode 100644 index 00000000..7400e348 --- /dev/null +++ b/ezyfox-server-common/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLiteEntityBuildersTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyLiteEntityBuilders; +import com.tvd12.test.base.BaseTest; + +public class EzyLiteEntityBuildersTest extends BaseTest { + + @Test + public void test() { + new A().test(); + } + + public static class A extends EzyLiteEntityBuilders { + + public void test() { + newArrayBuilder(); + newObjectBuilder(); + } + + } +} diff --git a/ezyfox-server-common/src/test/resources/AllTests.tng.xml b/ezyfox-server-common/src/test/resources/AllTests.tng.xml index 3f571ed5..27f7aad2 100644 --- a/ezyfox-server-common/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-common/src/test/resources/AllTests.tng.xml @@ -6,4 +6,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-concurrent/pom.xml b/ezyfox-server-concurrent/pom.xml new file mode 100644 index 00000000..cedbcbdd --- /dev/null +++ b/ezyfox-server-concurrent/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-concurrent + 1.0.0 + + ezyfox-server-concurrent + http://maven.apache.org + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-util + ${ezy.util.version} + + + + diff --git a/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java new file mode 100644 index 00000000..b5796a63 --- /dev/null +++ b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyExecutors.java @@ -0,0 +1,77 @@ +package com.tvd12.ezyfoxserver.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; + +public class EzyExecutors { + + private EzyExecutors() { + } + + public static ScheduledExecutorService newScheduledThreadPool( + int corePoolSize, String threadName) { + return newScheduledThreadPool(corePoolSize, newThreadFactory(threadName)); + } + + public static ExecutorService newFixedThreadPool( + int nThreads, String threadName) { + return newFixedThreadPool(nThreads, newThreadFactory(threadName)); + } + + public static ExecutorService newSingleThreadExecutor( + String threadName) { + return newSingleThreadExecutor(newThreadFactory(threadName)); + } + + public static ScheduledExecutorService newSingleThreadScheduledExecutor( + String threadName) { + return newSingleThreadScheduledExecutor(newThreadFactory(threadName)); + } + + // ====== by thread factory ========== + public static ScheduledExecutorService newScheduledThreadPool( + int corePoolSize, ThreadFactory threadFactory) { + return Executors.newScheduledThreadPool(corePoolSize, threadFactory); + } + + public static ExecutorService newFixedThreadPool( + int nThreads, ThreadFactory threadFactory) { + return Executors.newFixedThreadPool(nThreads, threadFactory); + } + + public static ExecutorService newSingleThreadExecutor( + ThreadFactory threadFactory) { + return Executors.newSingleThreadExecutor(threadFactory); + } + + public static ScheduledExecutorService newSingleThreadScheduledExecutor( + ThreadFactory threadFactory) { + return Executors.newSingleThreadScheduledExecutor(threadFactory); + } + // =================================== + + public static EzyThreadFactory newThreadFactory(String poolName) { + return newThreadFactory(poolName, false, Thread.NORM_PRIORITY); + } + + public static EzyThreadFactory newThreadFactory( + String poolName, int priority) { + return newThreadFactory(poolName, false, priority); + } + + public static EzyThreadFactory newThreadFactory( + String poolName, boolean daemon) { + return newThreadFactory(poolName, daemon, Thread.NORM_PRIORITY); + } + + public static EzyThreadFactory newThreadFactory( + String poolName, boolean daemon, int priority) { + return EzyThreadFactory.builder() + .daemon(daemon) + .priority(priority) + .poolName(poolName) + .build(); + } +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java similarity index 87% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java rename to ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java index 96756137..539d271a 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java +++ b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyLazyInitializer.java @@ -21,10 +21,14 @@ protected T initialize() throws ConcurrentException { @Override public T get() { try { - return super.get(); + return doGet(); } catch (ConcurrentException e) { throw new IllegalStateException(e); } } + protected T doGet() throws ConcurrentException { + return super.get(); + } + } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java similarity index 87% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java rename to ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java index 157f4006..edb8e690 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java +++ b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyThreadFactory.java @@ -26,7 +26,7 @@ protected EzyThreadFactory(Builder builder) { this.prefix = builder.prefix; this.daemon = builder.daemon; this.priority = builder.priority; - this.poolName = builder.poolName; + this.poolName = builder.getPoolName(); this.threadGroup = builder.threadGroup; this.poolName = getFullPoolName(); this.threadPrefix = poolName + '-' + poolId + '-'; @@ -34,11 +34,15 @@ protected EzyThreadFactory(Builder builder) { @Override public Thread newThread(Runnable runnable) { - Thread thread = new Thread(runnable, getThreadName()); + Thread thread = createThread(runnable, getThreadName()); setUpThread(thread); return thread; } + protected Thread createThread(Runnable runnable, String name) { + return new Thread(runnable, name); + } + protected void setUpThread(Thread thread) { try { trySetUpThread(thread); @@ -134,11 +138,17 @@ protected void validatePriority(int priority) { throw new IllegalArgumentException( "priority: " + priority + " (expected: Thread.MIN_PRIORITY <= priority <= Thread.MAX_PRIORITY)"); } + + protected ThreadGroup getSystemThreadGroup() { + return getSecurityManager() == null + ? Thread.currentThread().getThreadGroup() + : getSecurityManager().getThreadGroup(); + } + + protected SecurityManager getSecurityManager() { + return System.getSecurityManager(); + } + } - public static ThreadGroup getSystemThreadGroup() { - return System.getSecurityManager() == null - ? Thread.currentThread().getThreadGroup() - : System.getSecurityManager().getThreadGroup(); - } } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyWorker.java b/ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyWorker.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyWorker.java rename to ezyfox-server-concurrent/src/main/java/com/tvd12/ezyfoxserver/concurrent/EzyWorker.java diff --git a/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyExecutorsTest.java b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyExecutorsTest.java new file mode 100644 index 00000000..f04a9d10 --- /dev/null +++ b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyExecutorsTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.concurrent; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.test.base.BaseTest; + +public class EzyExecutorsTest extends BaseTest { + + @Test + public void test() { + EzyExecutors.newFixedThreadPool(5, "test"); + EzyExecutors.newScheduledThreadPool(5, "test"); + EzyExecutors.newSingleThreadExecutor("test"); + EzyExecutors.newSingleThreadScheduledExecutor("test"); + EzyExecutors.newThreadFactory("test", false); + EzyExecutors.newThreadFactory("test", Thread.NORM_PRIORITY); + } + + @Override + public Class getTestClass() { + return EzyExecutors.class; + } + +} diff --git a/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyLazyInitializerTest.java b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyLazyInitializerTest.java new file mode 100644 index 00000000..e17920b6 --- /dev/null +++ b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyLazyInitializerTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.testing.concurrent; + +import org.apache.commons.lang3.concurrent.ConcurrentException; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.concurrent.EzyLazyInitializer; +import com.tvd12.test.base.BaseTest; + +public class EzyLazyInitializerTest extends BaseTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() { + new EzyLazyInitializer(()-> new String()) { + @Override + protected String doGet() throws ConcurrentException { + throw new ConcurrentException(new Exception()); + } + }.get(); + } + + @Test + public void test1() { + String str = new EzyLazyInitializer<>(() -> new String("abc")).get(); + assert str.equals("abc"); + } +} diff --git a/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyThreadFactoryTest.java b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyThreadFactoryTest.java new file mode 100644 index 00000000..8a84077a --- /dev/null +++ b/ezyfox-server-concurrent/src/test/java/com/tvd12/ezyfoxserver/testing/concurrent/EzyThreadFactoryTest.java @@ -0,0 +1,118 @@ +package com.tvd12.ezyfoxserver.testing.concurrent; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.concurrent.EzyThreadFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyThreadFactoryTest extends BaseTest { + + @Test + public void test() { + EzyThreadFactory factory = newFactoryBuilder().build(); + Thread thread = factory.newThread(()-> {}); + assertEquals(thread.getName().startsWith("ezyfox-test"), true); + assertEquals(thread.isDaemon(), false); + + factory = newFactoryBuilder().prefix(null).build(); + thread = factory.newThread(()-> {}); + assertEquals(thread.getName().startsWith("test"), true); + + factory = newFactoryBuilder().daemon(true).poolName((String)null).build(); + thread = factory.newThread(()-> {}); + assertEquals(thread.isDaemon(), true); + factory = newFactoryBuilder().priority(Thread.MAX_PRIORITY).build(); + thread = factory.newThread(()-> {}); + assertEquals(thread.getPriority(), Thread.MAX_PRIORITY); + + } + + @Test + public void test1() { + new Builder1(); + new Builder2(); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + new Builder1().priority(-100000); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + new Builder1().priority(100000); + } + + @Test + public void test4() { + EzyThreadFactory factory = new Builder3().build(); + factory.newThread(() -> {}); + + } + + @Test + public void test5() { + EzyThreadFactory factory = new Builder4().build(); + factory.newThread(() -> {}); + + } + + @Test + public void test6() { + EzyThreadFactory factory = new Builder4().daemon(true).build(); + factory.newThread(() -> {}); + + } + + protected EzyThreadFactory.Builder newFactoryBuilder() { + return EzyThreadFactory.builder() + .daemon(false) + .poolName(EzyThreadFactoryTest.class) + .poolName("test") + .prefix("ezyfox") + .priority(Thread.NORM_PRIORITY) + .threadGroup(Thread.currentThread().getThreadGroup()); + } + + public static class Builder1 extends EzyThreadFactory.Builder { + @Override + protected SecurityManager getSecurityManager() { + return null; + } + } + + public static class Builder2 extends EzyThreadFactory.Builder { + @Override + protected SecurityManager getSecurityManager() { + return new SecurityManager(); + } + } + + public static class Builder3 extends EzyThreadFactory.Builder { + @Override + public EzyThreadFactory build() { + return new EzyThreadFactory(this) { + @Override + protected void trySetUpThread(Thread thread) { + throw new RuntimeException(); + } + }; + } + } + + public static class Builder4 extends EzyThreadFactory.Builder { + @Override + public EzyThreadFactory build() { + return new EzyThreadFactory(this) { + @Override + protected Thread createThread(Runnable runnable, String name) { + Thread thread = new Thread(runnable, name); + thread.setDaemon(true); + return thread; + } + }; + } + } +} diff --git a/ezyfox-server-concurrent/src/test/resources/AllTests.tng.xml b/ezyfox-server-concurrent/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..796dcb63 --- /dev/null +++ b/ezyfox-server-concurrent/src/test/resources/AllTests.tng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-core/pom.xml b/ezyfox-server-core/pom.xml index 5871386a..fa113da3 100644 --- a/ezyfox-server-core/pom.xml +++ b/ezyfox-server-core/pom.xml @@ -6,22 +6,48 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-core 1.0.0 ezyfox-server-core - http://maven.apache.org + http://www.tvd12.com/java/projects/ezyfox-server - 1.0.0 + 1.0.0 + 1.0.0 - + com.tvd12 - ezyfox-server-common - ${common.version} + ezyfox-server-codec + ${ezy.codec.version} + + + com.tvd12 + ezyfox-server-mapping + ${ezy.mapping.version} - + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.20 + + + src/test/resources/AllTests.tng.xml + + + ${project.basedir}/test-data/plugins/ezyfox-auth-plugin/ezyfox-auth-plugin.jar + + + + + + + diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppByIdFetcher.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppByIdFetcher.java new file mode 100644 index 00000000..0ee295c2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppByIdFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; + +public interface EzyAppByIdFetcher { + + EzyAppSetting getAppById(Integer id); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppFetcher.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppFetcher.java new file mode 100644 index 00000000..281965aa --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppFetcher.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; + +public interface EzyAppFetcher { + + EzySimpleAppSetting getAppById(Integer id); + + EzySimpleAppSetting getAppByName(String name); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppIdsFetcher.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppIdsFetcher.java new file mode 100644 index 00000000..fd3b89bd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppIdsFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver; + +import java.util.Set; + +public interface EzyAppIdsFetcher { + + Set getAppIds(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyApplication.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyApplication.java new file mode 100644 index 00000000..d213ae23 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyApplication.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; + +public interface EzyApplication { + + EzyAppSetting getSetting(); + + EzyAppUserManager getUserManager(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppsStarter.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppsStarter.java new file mode 100644 index 00000000..0b8f7a06 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyAppsStarter.java @@ -0,0 +1,106 @@ +package com.tvd12.ezyfoxserver; + +import java.util.Map; +import java.util.Set; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.ext.EzyAppEntry; +import com.tvd12.ezyfoxserver.ext.EzyAppEntryLoader; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; + +public class EzyAppsStarter extends EzyComponentStater { + + protected Map appClassLoaders; + + protected EzyAppsStarter(Builder builder) { + super(builder); + this.appClassLoaders = builder.appClassLoaders; + } + + @Override + public void start() { + startAllApps(); + } + + protected void startAllApps() { + Set appNames = getAppNames(); + getLogger().info("start apps: {}" + appNames); + appNames.forEach(this::startApp); + } + + protected void startApp(String appName) { + try { + getLogger().debug("app " + appName + " loading..."); + startApp(appName, newAppEntryLoader(appName)); + getLogger().debug("app " + appName + " loaded"); + } + catch(Exception e) { + getLogger().error("can not start app " + appName, e); + } + } + + protected void startApp(String appName, EzyAppEntryLoader loader) throws Exception { + startApp(appName, loader.load()); + } + + protected void startApp(String appName, EzyAppEntry entry) throws Exception { + entry.config(getAppContext(appName)); + entry.start(); + } + + @JsonIgnore + public Set getAppNames() { + return settings.getAppNames(); + } + + public EzyAppSetting getAppByName(String name) { + return settings.getAppByName(name); + } + + public Class + getAppEntryLoaderClass(String appName) throws Exception { + return getAppEntryLoaderClass(getAppByName(appName)); + } + + @SuppressWarnings("unchecked") + public Class + getAppEntryLoaderClass(EzyAppSetting app) throws Exception { + return (Class) + Class.forName(app.getEntryLoader(), true, getClassLoader(app.getName())); + } + + public EzyAppEntryLoader newAppEntryLoader(String appName) throws Exception { + return getAppEntryLoaderClass(appName).newInstance(); + } + + public EzyAppClassLoader getClassLoader(String appName) { + if(appClassLoaders.containsKey(appName)) + return appClassLoaders.get(appName); + throw new IllegalArgumentException("has no class loader for app " + appName); + } + + protected EzyAppContext getAppContext(String appName) { + return serverContext.getAppContext(appName); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyComponentStater.Builder { + protected Map appClassLoaders; + + public Builder appClassLoaders(Map appClassLoaders) { + this.appClassLoaders = appClassLoaders; + return this; + } + + @Override + public EzyAppsStarter build() { + return new EzyAppsStarter(this); + } + } + +} 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 7a2de25e..f9a9cbee 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 @@ -1,25 +1,21 @@ package com.tvd12.ezyfoxserver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.context.EzyAppContext; -import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; -import com.tvd12.ezyfoxserver.entity.EzyStartable; -import com.tvd12.ezyfoxserver.ext.EzyAppEntry; -import com.tvd12.ezyfoxserver.ext.EzyAppEntryLoader; -import com.tvd12.ezyfoxserver.ext.EzyPluginEntry; -import com.tvd12.ezyfoxserver.ext.EzyPluginEntryLoader; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; import com.tvd12.ezyfoxserver.wrapper.EzyManagers; -import lombok.Builder; +public class EzyBootstrap + extends EzyLoggable + implements EzyStartable, EzyDestroyable { -@Builder -public class EzyBootstrap implements EzyStartable, EzyDestroyable { + protected final EzyServerContext context; - protected EzyServerContext context; + protected EzyBootstrap(Builder builder) { + this.context = builder.context; + } @Override public void start() throws Exception { @@ -30,7 +26,7 @@ public void start() throws Exception { @Override public void destroy() { - //TODO destroy apps and plugins + // TODO } protected void startManagers() { @@ -39,75 +35,65 @@ protected void startManagers() { //====================== apps =================== protected void startAllApps() { - getServer().getAppNames().forEach(this::startApp); - } - - protected void startApp(String appName) { - try { - getLogger().debug("app " + appName + " loading..."); - startApp(appName, getServer().newAppEntryLoader(appName)); - getLogger().debug("app " + appName + " loaded"); - } - catch(Exception e) { - getLogger().error("can not start app " + appName, e); - } + getLogger().info("start all apps ..."); + startComponent(newAppsStaterBuilder()); } - protected void startApp(String appName, EzyAppEntryLoader loader) throws Exception { - startApp(appName, loader.load()); - } - - protected void startApp(String appName, EzyAppEntry entry) throws Exception { - entry.config(getAppContext(appName)); - entry.start(); + protected EzyAppsStarter.Builder newAppsStaterBuilder() { + return EzyAppsStarter.builder() + .appClassLoaders(getServer().getAppClassLoaders()); } //================================================= //===================== plugins =================== protected void startAllPlugins() { - getServer().getPluginNames().forEach(this::startPlugin); + getLogger().info("start all plugins ..."); + startComponent(newPluginsStaterBuilder()); } - protected void startPlugin(String pluginName) { - try { - getLogger().debug("plugin " + pluginName + " loading..."); - startPlugin(pluginName, getServer().newPluginEntryLoader(pluginName)); - getLogger().debug("plugin " + pluginName + " loaded"); - } - catch(Exception e) { - getLogger().error("can not start plugin " + pluginName, e); - } + protected EzyPluginsStarter.Builder newPluginsStaterBuilder() { + return EzyPluginsStarter.builder(); } - protected void startPlugin(String pluginName, EzyPluginEntryLoader loader) - throws Exception { - startPlugin(pluginName, loader.load()); - } - - protected void startPlugin(String pluginName, EzyPluginEntry entry) throws Exception { - entry.config(getPluginContext(pluginName)); - entry.start(); - } //================================================= - protected EzyServer getServer() { - return context.getBoss(); + protected void startComponent( + EzyComponentStater.Builder builder) { + EzyComponentStater starter = newComponentStater(builder); + starter.start(); } - protected EzyAppContext getAppContext(String appName) { - return context.getAppContext(appName); + protected EzyComponentStater newComponentStater( + EzyComponentStater.Builder builder) { + return builder + .serverContext(context) + .settings(getServer().getSettings()) + .build(); } - protected EzyPluginContext getPluginContext(String pluginName) { - return context.getPluginContext(pluginName); + protected EzyServer getServer() { + return context.getServer(); } protected EzyManagers getManagers() { return getServer().getManagers(); } - protected Logger getLogger() { - return LoggerFactory.getLogger(getClass()); + 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/EzyComponentStater.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponentStater.java new file mode 100644 index 00000000..ddcc658a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyComponentStater.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +public abstract class EzyComponentStater extends EzyLoggable implements EzyStartable { + + protected EzySettings settings; + protected EzyServerContext serverContext; + + protected EzyComponentStater(Builder builder) { + this.settings = builder.settings; + this.serverContext = builder.serverContext; + } + + @Override + public abstract void start(); + + public static abstract class Builder + > + implements EzyBuilder { + protected EzySettings settings; + protected EzyServerContext serverContext; + + public B settings(EzySettings settings) { + this.settings = settings; + return getThis(); + } + public B serverContext(EzyServerContext serverContext) { + this.serverContext = serverContext; + return getThis(); + } + + @SuppressWarnings("unchecked") + protected B getThis() { + return (B)this; + } + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java similarity index 99% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java rename to ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java index c93c7548..543829cc 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyEnvironment.java @@ -6,5 +6,4 @@ public class EzyEnvironment extends EzyEntity { 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/EzyHttpBootstrap.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyHttpBootstrap.java new file mode 100644 index 00000000..792085f4 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyHttpBootstrap.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +public interface EzyHttpBootstrap extends EzyStartable, EzyDestroyable { + +} 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 be3d2bed..4c1c8e5d 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 @@ -9,70 +9,108 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; import com.tvd12.ezyfoxserver.config.EzyConfig; -import com.tvd12.ezyfoxserver.config.EzySettings; -import com.tvd12.ezyfoxserver.service.EzyJsonMapping; -import com.tvd12.ezyfoxserver.service.EzyXmlReading; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; +import com.tvd12.ezyfoxserver.mapping.jackson.EzyJsonMapper; +import com.tvd12.ezyfoxserver.mapping.jackson.EzySimpleJsonMapper; +import com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.setting.EzySettingsReader; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettingsReader; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.wrapper.EzyEventPluginsMapper; import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyEventPluginsMapperImpl; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyManagersImpl; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyRequestMappersImpl; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyServerControllersImpl; /** * @author tavandung12 * */ -public class EzyLoader { +public class EzyLoader extends EzyLoggable { - protected Logger logger; protected EzyConfig config; - protected EzyManagers managers; protected ClassLoader classLoader; - protected EzyXmlReading xmlReading; - protected EzyJsonMapping jsonMapping; - protected EzyControllers controllers; - - private EzyLoader() { - this.logger = LoggerFactory.getLogger(getClass()); - } - - public static EzyLoader newInstance() { - return new EzyLoader(); - } public EzyServer load() { - EzyServer answer = new EzyServer(); + EzySettings settings = readSettings(); + EzySimpleServer answer = new EzySimpleServer(); answer.setConfig(config); - answer.setManagers(managers); - answer.setXmlReading(xmlReading); - answer.setJsonMapping(jsonMapping); + answer.setSettings(settings); + answer.setManagers(newManagers()); + answer.setJsonMapper(newJsonMapper()); answer.setClassLoader(classLoader); - answer.setSettings(readSettings()); - answer.setControllers(controllers); + answer.setControllers(newControllers()); + answer.setRequestMappers(newRequestMapper()); answer.setAppClassLoaders(newAppClassLoaders()); + answer.setEventPluginsMapper(newEventPluginsMapper(settings)); return answer; } - private EzySettings readSettings() { - logger.info("read setting file: " + getSettingsFilePath()); - return xmlReading.read(getSettingsFilePath(), EzySettings.class); + protected EzySettings readSettings() { + return newSettingsReader().read(); + } + + protected EzySettingsReader newSettingsReader() { + return EzySimpleSettingsReader.builder() + .homePath(getHomePath()) + .classLoader(classLoader) + .build(); + } + + protected EzyJsonMapper newJsonMapper() { + return EzySimpleJsonMapper.builder().build(); + } + + protected EzyManagers newManagers() { + EzyManagers managers = EzyManagersImpl.builder().build(); + addManagers(managers); + return managers; + } + + protected void addManagers(EzyManagers managers) { + } + + protected EzyServerControllers newControllers() { + EzyServerControllers controllers = EzyServerControllersImpl.builder().build(); + addControllers(controllers); + return controllers; + } + + protected void addControllers(EzyServerControllers controllers) { + } + + protected EzyRequestMappers newRequestMapper() { + EzyRequestMappers mappers = EzyRequestMappersImpl.builder().build(); + addRequestMappers(mappers); + return mappers; } - private Map newAppClassLoaders() { + protected void addRequestMappers(EzyRequestMappers mappers) { + } + + protected EzyEventPluginsMapper newEventPluginsMapper(EzySettings settings) { + return EzyEventPluginsMapperImpl.builder() + .plugins(settings.getPlugins()).build(); + } + + protected Map newAppClassLoaders() { Map answer = new ConcurrentHashMap<>(); for(File dir : getEntryFolders()) answer.put(dir.getName(), newAppClassLoader(dir)); return answer; } - private EzyAppClassLoader newAppClassLoader(File dir) { - logger.info("load " + dir); + protected EzyAppClassLoader newAppClassLoader(File dir) { + getLogger().info("load " + dir); return new EzyAppClassLoader(dir, classLoader); } - private File[] getEntryFolders() { + protected File[] getEntryFolders() { File entries = getEntriesFolder(); return entries.listFiles(new FileFilter() { @Override @@ -82,44 +120,32 @@ public boolean accept(File file) { }); } - private File getEntriesFolder() { + protected File getEntriesFolder() { String entriesPath = getEntriesPath(); File entries = new File(entriesPath); - if(!entries.exists() || entries.isFile()) - throw new IllegalStateException("entries path " + - entriesPath + " is not exists or is not a directory"); return entries; } - private String getEntriesPath() { - return getPath(getAppsPath(), "entries"); - } - - private String getAppsPath() { - return getPath(getHomePath(), "apps"); + protected String getEntriesPath() { + return getPath(getAppsPath(), EzyFolderNamesSetting.ENTRIES); } - private String getSettingsPath() { - return getPath(getHomePath(), "settings"); + protected String getAppsPath() { + return getPath(getHomePath(), EzyFolderNamesSetting.APPS); } - private String getSettingsFilePath() { - return getPath(getSettingsPath(), "ezy-settings.xml"); + protected String getSettingsPath() { + return getPath(getHomePath(), EzyFolderNamesSetting.SETTINGS); } - private String getPath(String first, String... more) { + protected String getPath(String first, String... more) { return Paths.get(first, more).toString(); } - private String getHomePath() { + protected String getHomePath() { return config.getEzyfoxHome(); } - @SuppressWarnings("unused") - private String getVersion() { - return config.getEzyfoxVersion(); - } - public EzyLoader classLoader(ClassLoader classLoader) { this.classLoader = classLoader; return this; @@ -130,24 +156,5 @@ public EzyLoader config(EzyConfig config) { return this; } - public EzyLoader managers(EzyManagers managers) { - this.managers = managers; - return this; - } - - public EzyLoader controllers(EzyControllers controllers) { - this.controllers = controllers; - return this; - } - - public EzyLoader xmlReading(EzyXmlReading xmlReading) { - this.xmlReading = xmlReading; - return this; - } - - public EzyLoader jsonMapping(EzyJsonMapping jsonMapping) { - this.jsonMapping = jsonMapping; - return this; - } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPlugin.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPlugin.java new file mode 100644 index 00000000..a886f975 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPlugin.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +public interface EzyPlugin { + + EzyPluginSetting getSetting(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginByIdFetcher.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginByIdFetcher.java new file mode 100644 index 00000000..a1c6e854 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginByIdFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +public interface EzyPluginByIdFetcher { + + EzyPluginSetting getPluginById(Integer id); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginIdsFetcher.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginIdsFetcher.java new file mode 100644 index 00000000..47b0cc00 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginIdsFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver; + +import java.util.Set; + +public interface EzyPluginIdsFetcher { + + Set getPluginIds(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginsStarter.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginsStarter.java new file mode 100644 index 00000000..86c5f1f1 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyPluginsStarter.java @@ -0,0 +1,88 @@ +package com.tvd12.ezyfoxserver; + +import java.util.Set; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.ext.EzyPluginEntry; +import com.tvd12.ezyfoxserver.ext.EzyPluginEntryLoader; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +public class EzyPluginsStarter extends EzyComponentStater { + + protected EzyPluginsStarter(Builder builder) { + super(builder); + } + + @Override + public void start() { + startAllPlugins(); + } + + protected void startAllPlugins() { + Set pluginNames = getPluginNames(); + getLogger().info("start plugins: {}", pluginNames); + pluginNames.forEach(this::startPlugin); + } + + protected void startPlugin(String pluginName) { + try { + getLogger().debug("plugin " + pluginName + " loading..."); + startPlugin(pluginName, newPluginEntryLoader(pluginName)); + getLogger().debug("plugin " + pluginName + " loaded"); + } + catch(Exception e) { + getLogger().error("can not start plugin " + pluginName, e); + } + } + + protected void startPlugin(String pluginName, EzyPluginEntryLoader loader) + throws Exception { + startPlugin(pluginName, loader.load()); + } + + protected void startPlugin(String pluginName, EzyPluginEntry entry) throws Exception { + entry.config(getPluginContext(pluginName)); + entry.start(); + } + + @JsonIgnore + public Set getPluginNames() { + return settings.getPluginNames(); + } + + public EzyPluginSetting getPluginByName(String name) { + return settings.getPluginByName(name); + } + + public Class + getPluginEntryLoaderClass(String pluginName) throws Exception { + return getPluginEntryLoaderClass(getPluginByName(pluginName)); + } + + @SuppressWarnings("unchecked") + public Class + getPluginEntryLoaderClass(EzyPluginSetting plugin) throws Exception { + return (Class) Class.forName(plugin.getEntryLoader()); + } + + public EzyPluginEntryLoader newPluginEntryLoader(String pluginName) throws Exception { + return getPluginEntryLoaderClass(pluginName).newInstance(); + } + + protected EzyPluginContext getPluginContext(String pluginName) { + return serverContext.getPluginContext(pluginName); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyComponentStater.Builder { + @Override + public EzyPluginsStarter build() { + return new EzyPluginsStarter(this); + } + } + +} 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 6848cfa2..d8cd987e 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 @@ -20,7 +20,8 @@ protected void validateArguments(String[] args) { } protected void startSystem(String configFile) throws Exception { - newStarter(configFile).start(); + EzyStarter starter = newStarter(configFile); + starter.start(); } protected EzyStarter newStarter(String configFile) { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServer.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServer.java index 7ce68119..3702eff7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServer.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyServer.java @@ -1,128 +1,38 @@ package com.tvd12.ezyfoxserver; import java.util.Map; -import java.util.Set; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; -import com.tvd12.ezyfoxserver.config.EzyApp; import com.tvd12.ezyfoxserver.config.EzyConfig; -import com.tvd12.ezyfoxserver.config.EzyPlugin; -import com.tvd12.ezyfoxserver.config.EzySettings; -import com.tvd12.ezyfoxserver.ext.EzyAppEntryLoader; -import com.tvd12.ezyfoxserver.ext.EzyPluginEntryLoader; -import com.tvd12.ezyfoxserver.service.EzyJsonMapping; -import com.tvd12.ezyfoxserver.service.EzyXmlReading; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; +import com.tvd12.ezyfoxserver.mapping.jackson.EzyJsonMapper; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.wrapper.EzyEventPluginsMapper; import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; -import lombok.Getter; -import lombok.Setter; +public interface EzyServer extends + EzyAppIdsFetcher, + EzyAppByIdFetcher, + EzyPluginIdsFetcher, + EzyPluginByIdFetcher { -/** - * Hello world! - * - */ -@Setter -@Getter -@JsonIgnoreProperties(ignoreUnknown = true) -public class EzyServer { - - protected EzyConfig config; - protected EzySettings settings; - - @JsonIgnore - protected EzyManagers managers; - @JsonIgnore - protected ClassLoader classLoader; - @JsonIgnore - protected EzyXmlReading xmlReading; - @JsonIgnore - protected EzyJsonMapping jsonMapping; - @JsonIgnore - protected EzyControllers controllers; - @JsonIgnore - protected Map appClassLoaders; - - @JsonIgnore - public Set getAppNames() { - return settings.getAppNames(); - } - - @JsonIgnore - public Set getAppIds() { - return settings.getAppIds(); - } - - public EzyApp getAppByName(final String name) { - return settings.getAppByName(name); - } - - public EzyApp getAppById(final Integer id) { - return settings.getAppById(id); - } - - public Class - getAppEntryLoaderClass(final String appName) throws Exception { - return getAppEntryLoaderClass(getAppByName(appName)); - } - - @SuppressWarnings("unchecked") - public Class - getAppEntryLoaderClass(final EzyApp app) throws Exception { - return (Class) - Class.forName(app.getEntryLoader(), true, getClassLoader(app.getName())); - } - - public EzyAppEntryLoader newAppEntryLoader(final String appName) throws Exception { - return getAppEntryLoaderClass(appName).newInstance(); - } - - //==================== plugins ================// - @JsonIgnore - public Set getPluginNames() { - return settings.getPluginNames(); - } - - @JsonIgnore - public Set getPluginIds() { - return settings.getPluginIds(); - } - - public EzyPlugin getPluginByName(final String name) { - return settings.getPluginByName(name); - } - - public EzyPlugin getPluginById(final Integer id) { - return settings.getPluginById(id); - } - - public Class - getPluginEntryLoaderClass(final String pluginName) throws Exception { - return getPluginEntryLoaderClass(getPluginByName(pluginName)); - } - - @SuppressWarnings("unchecked") - public Class - getPluginEntryLoaderClass(final EzyPlugin plugin) throws Exception { - return (Class) Class.forName(plugin.getEntryLoader()); - } - - public EzyPluginEntryLoader newPluginEntryLoader(final String pluginName) throws Exception { - return getPluginEntryLoaderClass(pluginName).newInstance(); - } - //=============================================// - - public EzyAppClassLoader getClassLoader(final String appName) { - if(appClassLoaders.containsKey(appName)) - return appClassLoaders.get(appName); - throw new IllegalArgumentException("has class loader for app " + appName); - } - - @Override - public String toString() { - return jsonMapping.writeAsString(this); - } + EzyConfig getConfig(); + + EzySettings getSettings(); + + EzyManagers getManagers(); + + ClassLoader getClassLoader(); + + EzyJsonMapper getJsonMapper(); + + EzyServerControllers getControllers(); + + EzyRequestMappers getRequestMappers(); + + EzyEventPluginsMapper getEventPluginsMapper(); + + Map getAppClassLoaders(); } 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 ae4ea2c2..8495def8 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 @@ -1,56 +1,62 @@ package com.tvd12.ezyfoxserver; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.tvd12.ezyfoxserver.command.EzyFireEvent; import com.tvd12.ezyfoxserver.constant.EzyEventType; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; -import com.tvd12.ezyfoxserver.entity.EzyStartable; import com.tvd12.ezyfoxserver.event.EzyEvent; import com.tvd12.ezyfoxserver.event.impl.EzyServerReadyEventImpl; +import com.tvd12.ezyfoxserver.util.EzyBannerPrinter; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; import lombok.Setter; -public abstract class EzyServerBootstrap implements EzyStartable, EzyDestroyable { +public abstract class EzyServerBootstrap + extends EzyLoggable + implements EzyStartable, EzyDestroyable { @Setter protected EzyServerContext context; @Setter - private EzyBootstrap localBootstrap; + protected EzyBootstrap localBootstrap; + @Setter + protected EzyHttpBootstrap httpBootstrap; @Override public void start() throws Exception { startLocalBootstrap(); - startOtherBootstraps(); - notifyServerReady(); + startHttpBootstrap(); + startOtherBootstraps(this::notifyServerReady); } - protected abstract void startOtherBootstraps() throws Exception; + protected void startHttpBootstrap() throws Exception { + getLogger().debug("starting http server bootstrap ...."); + httpBootstrap.start(); + getLogger().debug("http server bootstrap has started"); + } + protected abstract void startOtherBootstraps(Runnable callback) throws Exception; + + @Override public void destroy() { localBootstrap.destroy(); + httpBootstrap.destroy(); } protected void startLocalBootstrap() throws Exception { getLogger().debug("starting local bootstrap ...."); localBootstrap.start(); - getLogger().debug("starting local bootstrap successful"); + getLogger().debug("local bootstrap has started"); } protected void notifyServerReady() { + getLogger().info("\n{}\n", new EzyBannerPrinter().getBannerString()); context.get(EzyFireEvent.class).fire(EzyEventType.SERVER_READY, newServerReadyEvent()); } protected EzyEvent newServerReadyEvent() { - return EzyServerReadyEventImpl.builder().server(context.getBoss()).build(); + return EzyServerReadyEventImpl.builder().build(); } - protected Logger getLogger() { - return LoggerFactory.getLogger(getClass()); - } - - - } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleApplication.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleApplication.java new file mode 100644 index 00000000..b550b5fd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleApplication.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleApplication implements EzyApplication { + + protected EzyAppSetting setting; + protected EzyAppUserManager userManager; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimplePlugin.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimplePlugin.java new file mode 100644 index 00000000..9b5dfdf7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimplePlugin.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimplePlugin implements EzyPlugin { + + protected EzyPluginSetting setting; + +} 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 new file mode 100644 index 00000000..9c984b01 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySimpleServer.java @@ -0,0 +1,78 @@ +package com.tvd12.ezyfoxserver; + +import java.util.Map; +import java.util.Set; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; +import com.tvd12.ezyfoxserver.config.EzyConfig; +import com.tvd12.ezyfoxserver.mapping.jackson.EzyJsonMapper; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.wrapper.EzyEventPluginsMapper; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; + +import lombok.Getter; +import lombok.Setter; + +/** + * Hello world! + * + */ +@Setter +@Getter +@JsonIgnoreProperties(ignoreUnknown = true) +public class EzySimpleServer implements EzyServer { + + protected EzyConfig config; + protected EzySettings settings; + + @JsonIgnore + protected EzyManagers managers; + @JsonIgnore + protected ClassLoader classLoader; + @JsonIgnore + protected EzyJsonMapper jsonMapper; + @JsonIgnore + protected EzyServerControllers controllers; + @JsonIgnore + protected EzyRequestMappers requestMappers; + @JsonIgnore + protected EzyEventPluginsMapper eventPluginsMapper; + @JsonIgnore + protected Map appClassLoaders; + + @JsonIgnore + @Override + public Set getAppIds() { + return settings.getAppIds(); + } + + @Override + public EzyAppSetting getAppById(Integer id) { + return settings.getAppById(id); + } + + //==================== plugins ================// + @JsonIgnore + @Override + public Set getPluginIds() { + return settings.getPluginIds(); + } + + @Override + public EzyPluginSetting getPluginById(Integer id) { + return settings.getPluginById(id); + } + //=============================================// + + @Override + public String toString() { + return jsonMapper.writeAsString(this); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyStarter.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyStarter.java index 9ccbe284..97d4aef2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyStarter.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzyStarter.java @@ -6,21 +6,20 @@ import java.io.File; import java.nio.file.Paths; +import org.slf4j.LoggerFactory; + import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; import com.tvd12.ezyfoxserver.config.EzyConfig; -import com.tvd12.ezyfoxserver.entity.EzyStartable; -import com.tvd12.ezyfoxserver.loader.EzyConfigLoader; -import com.tvd12.ezyfoxserver.loader.impl.EzyConfigLoaderImpl; -import com.tvd12.ezyfoxserver.service.EzyJsonMapping; -import com.tvd12.ezyfoxserver.service.EzyXmlReading; -import com.tvd12.ezyfoxserver.service.impl.EzyJsonMappingImpl; -import com.tvd12.ezyfoxserver.service.impl.EzyXmlReadingImpl; +import com.tvd12.ezyfoxserver.config.EzyConfigLoader; +import com.tvd12.ezyfoxserver.config.EzySimpleConfigLoader; +import com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting; import com.tvd12.ezyfoxserver.util.EzyLoggable; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; -import com.tvd12.ezyfoxserver.wrapper.EzyManagers; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyControllersImpl; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyManagersImpl; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; /** * @author tavandung12 @@ -46,6 +45,7 @@ protected void startSystem() throws Exception { } protected void startSystem(EzyConfig config) throws Exception { + customLoggerConfig(config); setSystemProperties(config); startEzyFox(config); } @@ -55,74 +55,63 @@ protected void startEzyFox(EzyConfig config) throws Exception { } protected void startEzyFox(EzyServer ezyFox) throws Exception { - getLogger().info(ezyFox.toString()); + getLogger().info("settings: \n{}", ezyFox.toString()); newServerBoostrap(ezyFox).start(); } protected EzyServerBootstrap newServerBoostrap(EzyServer ezyFox) { return newServerBootstrapBuilder() - .port(3005) - .wsport(2208) - .boss(ezyFox) + .server(ezyFox) .build(); } protected abstract EzyServerBootstrapBuilder newServerBootstrapBuilder(); + protected void customLoggerConfig(EzyConfig config) { + LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); + loggerContext.reset(); + JoranConfigurator cfg = new JoranConfigurator(); + cfg.setContext(loggerContext); + String configFile = getLoggerConfigFile(config); + EzyProcessor.processWithLogException(() -> cfg.doConfigure(configFile)); + } + protected void setSystemProperties(EzyConfig config) { - System.setProperty("logback.configurationFile", getLogbackConfigFile(config)); + System.setProperty("logback.configurationFile", getLoggerConfigFile(config)); + System.setProperty("logging.config", getLoggerConfigFile(config)); } protected EzyServer loadEzyFox(EzyConfig config) { - return EzyLoader.newInstance() + return newLoader() .config(config) - .managers(newManagers()) - .controllers(newControllers()) - .xmlReading(getXmlReading()) - .jsonMapping(getJsonMapping()) .classLoader(getClassLoader()) .load(); } - protected EzyConfig readConfig(String configFile) throws Exception { - return getConfigLoader(configFile).load(); + protected EzyLoader newLoader() { + return new EzyLoader(); } - protected EzyConfigLoader getConfigLoader(String configFile) { - return EzyConfigLoaderImpl.newInstance().filePath(configFile); + protected EzyConfig readConfig(String configFile) throws Exception { + return getConfigLoader().load(configFile); } - public EzyManagers newManagers() { - return EzyManagersImpl.builder().build(); + protected EzyConfigLoader getConfigLoader() { + return new EzySimpleConfigLoader(); } - public EzyControllers newControllers() { - return EzyControllersImpl.builder().build(); - } - protected ClassLoader getClassLoader() { - return EzyServer.class.getClassLoader(); + return EzySimpleServer.class.getClassLoader(); } - protected String getLogbackConfigFile(EzyConfig config) { - return getPath(config.getEzyfoxHome(), "settings", config.getLogbackConfigFile()); + protected String getLoggerConfigFile(EzyConfig config) { + return getPath(config.getEzyfoxHome(), EzyFolderNamesSetting.SETTINGS, config.getLoggerConfigFile()); } protected String getPath(String first, String... more) { return Paths.get(first, more).toString(); } - protected EzyXmlReading getXmlReading() { - return EzyXmlReadingImpl.builder() - .classLoader(getClassLoader()) - .contextPath("com.tvd12.ezyfoxserver") - .build(); - } - - protected EzyJsonMapping getJsonMapping() { - return EzyJsonMappingImpl.builder().build(); - } - public abstract static class Builder> implements EzyBuilder { protected String configFile; 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 new file mode 100644 index 00000000..d9c6a4e7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/EzySystem.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver; + +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; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyServerReadyController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyServerReadyController.java index af6fac93..3e11259e 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyServerReadyController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyServerReadyController.java @@ -9,7 +9,7 @@ public class EzyServerReadyController @Override public void handle(EzyAppContext ctx, EzyServerReadyEvent event) { - getLogger().info("server ready controller"); + getLogger().info("app: server ready controller"); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserDisconnectController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserDisconnectController.java index 11add8dd..7b638d12 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserDisconnectController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserDisconnectController.java @@ -2,13 +2,13 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.controller.EzyAbstractAppEventController; -import com.tvd12.ezyfoxserver.event.EzyDisconnectEvent; +import com.tvd12.ezyfoxserver.event.EzyUserDisconnectEvent; public class EzyUserDisconnectController - extends EzyAbstractAppEventController { + extends EzyAbstractAppEventController { @Override - public void handle(EzyAppContext ctx, EzyDisconnectEvent event) { + public void handle(EzyAppContext ctx, EzyUserDisconnectEvent event) { getLogger().info("user {} disconnected", event.getUser().getName()); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserReconnectController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserReconnectController.java new file mode 100644 index 00000000..4329cea9 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserReconnectController.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.appcontroller; + +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.controller.EzyAbstractAppEventController; +import com.tvd12.ezyfoxserver.event.EzyUserReconnectEvent; + +public class EzyUserReconnectController + extends EzyAbstractAppEventController { + + @Override + public void handle(EzyAppContext ctx, EzyUserReconnectEvent event) { + getLogger().info("app: user reconnect"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestAppController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestAppController.java new file mode 100644 index 00000000..f6574a2e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestAppController.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.appcontroller; + +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.controller.EzyAbstractAppEventController; +import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; + +public class EzyUserRequestAppController + extends EzyAbstractAppEventController { + + @Override + public void handle(EzyAppContext ctx, EzyUserRequestAppEvent event) { + getLogger().info("user request controller"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestController.java deleted file mode 100644 index 9faeb556..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/appcontroller/EzyUserRequestController.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.tvd12.ezyfoxserver.appcontroller; - -import com.tvd12.ezyfoxserver.context.EzyAppContext; -import com.tvd12.ezyfoxserver.controller.EzyAbstractAppEventController; -import com.tvd12.ezyfoxserver.event.EzyRequestAppEvent; - -public class EzyUserRequestController - extends EzyAbstractAppEventController { - - @Override - public void handle(EzyAppContext ctx, EzyRequestAppEvent event) { - getLogger().info("user request controller"); - } - -} 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 d4cb3669..b5d97101 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 @@ -1,62 +1,109 @@ package com.tvd12.ezyfoxserver.builder; +import javax.net.ssl.SSLContext; + import com.tvd12.ezyfoxserver.EzyBootstrap; +import com.tvd12.ezyfoxserver.EzyHttpBootstrap; import com.tvd12.ezyfoxserver.EzyServer; import com.tvd12.ezyfoxserver.EzyServerBootstrap; +import com.tvd12.ezyfoxserver.config.EzyConfig; import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.setting.EzySocketSetting; +import com.tvd12.ezyfoxserver.setting.EzySslConfigSetting; +import com.tvd12.ezyfoxserver.setting.EzyWebSocketSetting; +import com.tvd12.ezyfoxserver.ssl.EzySslContextInitializer; public abstract class EzyAbtractServerBootstrapBuilder implements EzyServerBootstrapBuilder { - protected int port; - protected int wsport; - protected EzyServer boss; + protected EzyServer server; + protected EzyServerContext serverContext; /* * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder#port(int) + * @see com.tvd12.ezyfoxserver.mapping.builder.EzyServerBootstrapBuilder#boss(com.tvd12.ezyfoxserver.mapping.EzyServer) */ @Override - public EzyServerBootstrapBuilder port(int port) { - this.port = port; + public EzyAbtractServerBootstrapBuilder server(EzyServer server) { + this.server = server; + this.serverContext = newServerContext(server); return this; } - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder#wsport(int) - */ @Override - public EzyServerBootstrapBuilder wsport(int wsport) { - this.wsport = wsport; - return this; + public final EzyServerBootstrap build() { + prebuild(); + return doBuild(); } - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder#boss(com.tvd12.ezyfoxserver.EzyServer) - */ - @Override - public EzyServerBootstrapBuilder boss(EzyServer boss) { - this.boss = boss; - return this; + protected void prebuild() { + } + + protected EzyServerBootstrap doBuild() { + EzyServerBootstrap answer = newServerBootstrap(); + answer.setContext(serverContext); + answer.setHttpBootstrap(newHttpBottstrap()); + answer.setLocalBootstrap(newLocalBoostrap()); + return answer; + } + + protected EzyServerContext newServerContext(EzyServer server) { + return newServerContextBuilder() + .server(server) + .build(); } - protected EzyBootstrap newLocalBoostrap(EzyServerContext context) { - return EzyBootstrap.builder().context(context).build(); + protected SSLContext newSslContext(EzySslConfigSetting sslConfig) { + return newSslContextInitializer(sslConfig).init(); + } + + protected EzySslContextInitializer newSslContextInitializer(EzySslConfigSetting sslConfig) { + return newSslContextInitializerBuilder() + .sslConfig(sslConfig) + .homeFolderPath(getConfig().getEzyfoxHome()) + .build(); } - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.builder.EzyBuilder#build() - */ - @Override - public EzyServerBootstrap build() { - return build(newContext()); + protected EzySslContextInitializer.Builder newSslContextInitializerBuilder() { + return EzySslContextInitializer.builder(); } - - protected abstract EzyServerContext newContext(); - protected abstract EzyServerBootstrap build(EzyServerContext ctx); + + protected EzyBootstrap newLocalBoostrap() { + return EzyBootstrap.builder().context(serverContext).build(); + } + + protected String getCodecCreatorClassName() { + return getSocketSettings().getCodecCreator(); + } + + protected String getWsCodecCreatorClassName() { + return getWebsocketSettings().getCodecCreator(); + } + + protected EzyServerContextBuilder newServerContextBuilder() { + return new EzySimpleServerContextBuilder<>(); + } + + protected abstract EzyHttpBootstrap newHttpBottstrap(); + + protected abstract EzyServerBootstrap newServerBootstrap(); + + protected EzyConfig getConfig() { + return server.getConfig(); + } + + protected EzySettings getSettings() { + return server.getSettings(); + } + + protected EzySocketSetting getSocketSettings() { + return getSettings().getSocket(); + } + + protected EzyWebSocketSetting getWebsocketSettings() { + return getSettings().getWebsocket(); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyContextBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyContextBuilder.java deleted file mode 100644 index ca42f974..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyContextBuilder.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.tvd12.ezyfoxserver.builder; - -import com.tvd12.ezyfoxserver.EzyServer; -import com.tvd12.ezyfoxserver.context.EzyContext; - -public interface EzyContextBuilder> extends EzyBuilder { - - B boss(EzyServer boss); - -} 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 975e7368..8a76622b 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 @@ -5,28 +5,12 @@ public interface EzyServerBootstrapBuilder extends EzyBuilder { - /** - * set port - * - * @param port the port - * @return this pointer - */ - EzyServerBootstrapBuilder port(int port); - - /** - * set ws port - * - * @param wsport the ws port - * @return this pointer - */ - EzyServerBootstrapBuilder wsport(int wsport); - /** * set server * * @param boss the server * @return this pointer */ - EzyServerBootstrapBuilder boss(EzyServer boss); + EzyServerBootstrapBuilder server(EzyServer boss); } 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 new file mode 100644 index 00000000..cf815603 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzyServerContextBuilder.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.builder; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.context.EzyServerContext; + +public interface EzyServerContextBuilder> + extends EzyBuilder { + + B server(EzyServer server); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzySimpleServerContextBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzySimpleServerContextBuilder.java new file mode 100644 index 00000000..6fbf87f2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/builder/EzySimpleServerContextBuilder.java @@ -0,0 +1,111 @@ +package com.tvd12.ezyfoxserver.builder; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.ExecutorService; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.EzySimpleApplication; +import com.tvd12.ezyfoxserver.EzySimplePlugin; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.context.EzySimpleAppContext; +import com.tvd12.ezyfoxserver.context.EzySimplePluginContext; +import com.tvd12.ezyfoxserver.context.EzySimpleServerContext; +import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; +import com.tvd12.ezyfoxserver.service.impl.EzySimpleResponseSerializer; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyAppUserManagerImpl; + +public class EzySimpleServerContextBuilder> + implements EzyServerContextBuilder { + + protected EzyServer server; + + @Override + public EzyServerContext build() { + EzySimpleServerContext context = newServerContext(); + context.setServer(server); + context.setWorkerExecutor(newWorkerExecutor()); + context.addAppContexts(newAppContexts(context)); + context.addPluginContexts(newPluginContexts(context)); + context.setProperty(EzyResponseSerializer.class, newResponseSerializer()); + return context; + } + + protected EzySimpleServerContext newServerContext() { + return new EzySimpleServerContext(); + } + + protected ExecutorService newWorkerExecutor() { + String threadName = "worker"; + int nthreads = server.getSettings().getWorkerPoolSize(); + return EzyExecutors.newFixedThreadPool(nthreads, threadName); + } + + protected Collection newAppContexts(EzyServerContext parent) { + Collection contexts = new ArrayList<>(); + for(Integer appId : server.getAppIds()) + contexts.add(newAppContext(parent, server.getAppById(appId))); + return contexts; + } + + protected EzyAppContext newAppContext(EzyServerContext parent, EzyAppSetting setting) { + EzySimpleApplication app = new EzySimpleApplication(); + app.setSetting(setting); + app.setUserManager(EzyAppUserManagerImpl.builder().build()); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + appContext.setApp(app); + appContext.setParent(parent); + appContext.setWorkerExecutor(newAppWorkerExecutor(setting)); + return appContext; + } + + protected Collection newPluginContexts(EzyServerContext parent) { + Collection contexts = new ArrayList<>(); + for(Integer appId : server.getPluginIds()) + contexts.add(newPluginContext(parent, server.getPluginById(appId))); + return contexts; + } + + protected EzyPluginContext newPluginContext(EzyServerContext parent, EzyPluginSetting setting) { + EzySimplePlugin plugin = new EzySimplePlugin(); + plugin.setSetting(setting); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + pluginContext.setPlugin(plugin); + pluginContext.setParent(parent); + pluginContext.setWorkerExecutor(newPluginWorkerExecutor(setting)); + return pluginContext; + } + + protected ExecutorService newAppWorkerExecutor(EzyAppSetting app) { + String threadName = "app-worker"; + int nthreads = app.getWorkerPoolSize(); + return EzyExecutors.newFixedThreadPool(nthreads, threadName); + } + + protected ExecutorService newPluginWorkerExecutor(EzyPluginSetting plugin) { + String threadName = "plugin-worker"; + int nthreads = plugin.getWorkerPoolSize(); + return EzyExecutors.newFixedThreadPool(nthreads, threadName); + } + + protected EzyResponseSerializer newResponseSerializer() { + return EzySimpleResponseSerializer.builder().build(); + } + + @Override + public B server(EzyServer server) { + this.server = server; + return getThis(); + } + + @SuppressWarnings("unchecked") + protected B getThis() { + return (B)this; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ccl/EzyAppClassLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ccl/EzyAppClassLoader.java index d1cb694d..a3ff9e0f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ccl/EzyAppClassLoader.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ccl/EzyAppClassLoader.java @@ -4,16 +4,13 @@ package com.tvd12.ezyfoxserver.ccl; import java.io.File; -import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.tvd12.ezyfoxserver.util.EzyEntryFiles; - -import lombok.Getter; +import com.tvd12.ezyfoxserver.util.EzyDirectories; /** * @author tavandung12 @@ -21,8 +18,7 @@ */ public class EzyAppClassLoader extends URLClassLoader { - @Getter - protected Logger logger; + protected Logger logger = LoggerFactory.getLogger(getClass()); /** * @param urls @@ -30,11 +26,6 @@ public class EzyAppClassLoader extends URLClassLoader { */ public EzyAppClassLoader(File directory, ClassLoader parent) { super(getURLsByPath(directory), parent); - this.initialize(directory); - } - - private void initialize(File directory) { - this.logger = LoggerFactory.getLogger(getClass()); } /* (non-Javadoc) @@ -65,11 +56,18 @@ public URL findResource(String name) { } private static URL[] getURLsByPath(File directory) { + return getURLsByPath(new EzyDirectories().directory(directory)); + } + + private static URL[] getURLsByPath(EzyDirectories directories) { try { - return new EzyEntryFiles().directory(directory).getURLs(); - } catch (IOException e) { - throw new IllegalStateException("can not load classes from path: " + directory, e); + return directories.getURLs(); + } catch (Exception e) { + throw new IllegalStateException("can not load classes from path: " + directories, e); } } + protected Logger getLogger() { + return logger; + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAppResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAppResponse.java new file mode 100644 index 00000000..399725b9 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyAppResponse.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.command; + +public interface EzyAppResponse extends EzyResponse { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectSession.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectSession.java new file mode 100644 index 00000000..376868db --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectSession.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.command; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzySession; + +public interface EzyDisconnectSession extends EzyCommand { + + EzyDisconnectSession session(EzySession session); + + EzyDisconnectSession reason(EzyConstant reason); + + EzyDisconnectSession fireClientEvent(boolean value); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectUser.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectUser.java index 2538de22..42b84777 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectUser.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyDisconnectUser.java @@ -1,15 +1,12 @@ package com.tvd12.ezyfoxserver.command; import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.entity.EzySession; import com.tvd12.ezyfoxserver.entity.EzyUser; public interface EzyDisconnectUser extends EzyCommand { EzyDisconnectUser user(EzyUser user); - EzyDisconnectUser session(EzySession session); - EzyDisconnectUser reason(EzyConstant reason); EzyDisconnectUser fireClientEvent(boolean value); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyFireAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyFireAppEvent.java index 310c21e5..559bd247 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyFireAppEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyFireAppEvent.java @@ -1,5 +1,11 @@ package com.tvd12.ezyfoxserver.command; +import java.util.function.Predicate; + +import com.tvd12.ezyfoxserver.context.EzyAppContext; + public interface EzyFireAppEvent extends EzyFireEvent { + EzyFireAppEvent filter(Predicate filter); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyPluginResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyPluginResponse.java new file mode 100644 index 00000000..7261bf34 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyPluginResponse.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.command; + +public interface EzyPluginResponse extends EzyResponse { +} 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 new file mode 100644 index 00000000..78e169a1 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzyResponse.java @@ -0,0 +1,72 @@ +package com.tvd12.ezyfoxserver.command; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzyResponse extends EzyCommand { + + EzyResponse command(String command); + + EzyResponse params(EzyData params); + + EzyResponse user(EzyUser user, boolean exclude); + + EzyResponse users(EzyUser[] users, boolean exclude); + + EzyResponse users(Iterable users, boolean exclude); + + EzyResponse username(String username, boolean exclude); + + EzyResponse usernames(String[] usernames, boolean exclude); + + EzyResponse usernames(Iterable usernames, boolean exclude); + + EzyResponse session(EzySession session, boolean exclude); + + EzyResponse sessions(EzySession[] sessions, boolean exclude); + + EzyResponse sessions(Iterable sessions, boolean exclude); + + default EzyResponse user(EzyUser user) { + return user(user, false); + } + + default EzyResponse users(EzyUser... users) { + return users(users, false); + } + + default EzyResponse users(Iterable users) { + return users(users, false); + } + + default EzyResponse username(String username) { + return username(username, false); + } + + default EzyResponse usernames(String... usernames) { + return usernames(usernames, false); + } + + default EzyResponse usernames(Iterable usernames) { + return usernames(usernames, false); + } + + default EzyResponse session(EzySession session) { + return session(session, false); + } + + default EzyResponse sessions(EzySession... sessions) { + return sessions(sessions, false); + } + + default EzyResponse sessions(Iterable sessions) { + return sessions(sessions, false); + } + + default EzyResponse params(EzyBuilder builder) { + return params(builder.build()); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendMessage.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendMessage.java index 630d0b21..461ace47 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendMessage.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendMessage.java @@ -1,12 +1,17 @@ package com.tvd12.ezyfoxserver.command; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.entity.EzyData; import com.tvd12.ezyfoxserver.entity.EzySender; public interface EzySendMessage extends EzyCommand { + EzySendMessage data(EzyData data); + EzySendMessage sender(EzySender sender); - EzySendMessage data(EzyData data); + default EzySendMessage data(EzyBuilder builder) { + return data(builder.build()); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendResponse.java new file mode 100644 index 00000000..69f36f72 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/EzySendResponse.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.command; + +import com.tvd12.ezyfoxserver.entity.EzySender; +import com.tvd12.ezyfoxserver.response.EzyResponse; + +public interface EzySendResponse extends EzyCommand { + + EzySendResponse sender(EzySender sender); + + EzySendResponse response(EzyResponse response); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAbstractResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAbstractResponse.java new file mode 100644 index 00000000..e4efcedd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAbstractResponse.java @@ -0,0 +1,132 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import com.tvd12.ezyfoxserver.command.EzyResponse; +import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.controller.EzyMessageController; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; + +public abstract class EzyAbstractResponse + extends EzyMessageController + implements EzyResponse { + + protected String command; + protected EzyData params; + protected Set recipients = new HashSet<>(); + protected Set exrecipients = new HashSet<>(); + + protected final C context; + protected final EzyUserManager userManager; + + public EzyAbstractResponse(C context) { + this.context = context; + this.userManager = getUserManager(context); + } + + protected abstract EzyUserManager getUserManager(C context); + + @Override + public EzyResponse command(String command) { + this.command = command; + return this; + } + + public EzyResponse params(EzyData params) { + this.params = params; + return this; + } + + @Override + public EzyResponse user(EzyUser user, boolean exclude) { + if(user != null) { + if(exclude) + this.exrecipients.addAll(user.getSessions()); + else + this.recipients.addAll(user.getSessions()); + } + return this; + } + + @Override + public EzyResponse users(EzyUser[] users, boolean exclude) { + return users(Arrays.asList(users), exclude); + } + + @Override + public EzyResponse users(Iterable users, boolean exclude) { + users.forEach(u -> user(u, exclude)); + return this; + } + + @Override + public EzyResponse username(String username, boolean exclude) { + return user(userManager.getUser(username), exclude); + } + + @Override + public EzyResponse usernames(String[] usernames, boolean exclude) { + Arrays.stream(usernames).forEach(un -> username(un, exclude)); + return this; + } + + @Override + public EzyResponse usernames(Iterable usernames, boolean exclude) { + usernames.forEach(un -> username(un, exclude)); + return this; + } + + @Override + public EzyResponse session(EzySession session, boolean exclude) { + if(exclude) + this.exrecipients.add(session); + else + this.recipients.add(session); + return this; + } + + @Override + public EzyResponse sessions(EzySession[] sessions, boolean exclude) { + Arrays.stream(sessions).forEach(s -> session(s, exclude)); + return this; + } + + @Override + public EzyResponse sessions(Iterable sessions, boolean exclude) { + sessions.forEach(s -> session(s, exclude)); + return this; + } + + @Override + public Boolean execute() { + com.tvd12.ezyfoxserver.response.EzyResponse response = newResponse(); + recipients.removeAll(exrecipients); + recipients.forEach(s -> response(s, response)); + return Boolean.TRUE; + } + + protected void response(EzySession session, + com.tvd12.ezyfoxserver.response.EzyResponse response) { + response(context, session, response); + } + + protected com.tvd12.ezyfoxserver.response.EzyResponse newResponse() { + return newResponseBuilder(newData()).build(); + } + + protected abstract com.tvd12.ezyfoxserver.response.EzyResponse.Builder + newResponseBuilder(EzyData data); + + protected EzyData newData() { + return newArrayBuilder() + .append(command) + .append(params) + .build(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAddEventControllerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAddEventControllerImpl.java index c22a77a8..ac191911 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAddEventControllerImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAddEventControllerImpl.java @@ -1,9 +1,9 @@ package com.tvd12.ezyfoxserver.command.impl; import com.tvd12.ezyfoxserver.command.EzyAddEventController; -import com.tvd12.ezyfoxserver.config.EzyEventControllerAdder; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.controller.EzyEventController; +import com.tvd12.ezyfoxserver.setting.EzyEventControllerAdder; import lombok.AllArgsConstructor; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppFireEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppFireEventImpl.java index 66bf1806..5efe80b6 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppFireEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppFireEventImpl.java @@ -1,11 +1,11 @@ package com.tvd12.ezyfoxserver.command.impl; import com.tvd12.ezyfoxserver.command.EzyFireEvent; -import com.tvd12.ezyfoxserver.config.EzyApp; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.controller.EzyEventController; import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; public class EzyAppFireEventImpl @@ -18,9 +18,12 @@ public EzyAppFireEventImpl(EzyAppContext context) { this.context = context; } - @Override + @SuppressWarnings("rawtypes") + @Override public void fire(EzyConstant type, EzyEvent event) { - fire(getController(type), event); + EzyEventController ctrl = getController(type); + getLogger().debug("fire event {}, controller = {}", type, ctrl); + fire(ctrl, event); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -35,10 +38,10 @@ protected EzyEventController getController(EzyConstant type) { } protected EzyEventControllers getEventControllers() { - return getApp().getEventControllers(); + return getAppSetting().getEventControllers(); } - protected EzyApp getApp() { - return context.getApp(); + protected EzyAppSetting getAppSetting() { + return context.getApp().getSetting(); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppResponseImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppResponseImpl.java new file mode 100644 index 00000000..60a3d5fd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyAppResponseImpl.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import com.tvd12.ezyfoxserver.command.EzyAppResponse; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.response.EzyRequestAppResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse.Builder; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; + +public class EzyAppResponseImpl + extends EzyAbstractResponse + implements EzyAppResponse { + + public EzyAppResponseImpl(EzyAppContext context) { + super(context); + } + + @Override + protected EzyUserManager getUserManager(EzyAppContext context) { + return context.getApp().getUserManager(); + } + + @Override + protected Builder newResponseBuilder(EzyData data) { + return newResponseBuilder(context.getApp().getSetting(), data); + } + + protected Builder newResponseBuilder(EzyAppSetting setting, EzyData data) { + return EzyRequestAppResponse.builder() + .appId(setting.getId()) + .data(data); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectSessionImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectSessionImpl.java new file mode 100644 index 00000000..e3f7609e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectSessionImpl.java @@ -0,0 +1,69 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import com.tvd12.ezyfoxserver.command.EzyDisconnectSession; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyMessageController; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.response.EzyDisconnectResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; + +public class EzyDisconnectSessionImpl + extends EzyMessageController + implements EzyDisconnectSession { + + private EzySession session; + private EzyConstant reason; + private boolean fireClientEvent = true; + + private EzyServerContext context; + + public EzyDisconnectSessionImpl(EzyServerContext ctx) { + this.context = ctx; + } + + @Override + public Boolean execute() { + sendToClients(); + disconnectSession(); + return Boolean.TRUE; + } + + protected void sendToClients() { + if(fireClientEvent) + doSendToClient(); + } + + protected void disconnectSession() { + getLogger().info("disconnect session: {}, reason: {}", session.getClientAddress(), reason); + session.disconnect(); + session.close(); + } + + protected void doSendToClient() { + response(context, session, newResponse()); + } + + protected EzyResponse newResponse() { + return EzyDisconnectResponse.builder().reason(reason).build(); + } + + @Override + public EzyDisconnectSession session(EzySession session) { + this.session = session; + return this; + } + + @Override + public EzyDisconnectSession reason(EzyConstant reason) { + this.reason = reason; + return this; + } + + @Override + public EzyDisconnectSession fireClientEvent(boolean value) { + this.fireClientEvent = value; + return this; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectUserImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectUserImpl.java index 583816b3..24a6a8ce 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectUserImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyDisconnectUserImpl.java @@ -1,29 +1,34 @@ package com.tvd12.ezyfoxserver.command.impl; +import static com.tvd12.ezyfoxserver.context.EzyContexts.*; + +import java.util.ArrayList; +import java.util.List; + import com.tvd12.ezyfoxserver.command.EzyDisconnectUser; import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; -import com.tvd12.ezyfoxserver.command.EzySendMessage; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; import com.tvd12.ezyfoxserver.controller.EzyMessageController; -import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzySession; import com.tvd12.ezyfoxserver.entity.EzyUser; import com.tvd12.ezyfoxserver.event.EzyEvent; -import com.tvd12.ezyfoxserver.event.impl.EzyDisconnectEventImpl; +import com.tvd12.ezyfoxserver.event.impl.EzyUserDisconnectEventImpl; import com.tvd12.ezyfoxserver.response.EzyDisconnectResponse; import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; public class EzyDisconnectUserImpl extends EzyMessageController implements EzyDisconnectUser { private EzyUser user; - private EzySession session; private EzyConstant reason; private boolean fireClientEvent = true; private boolean fireServerEvent = true; + private List sessions = new ArrayList<>(); private EzyServerContext context; @@ -33,69 +38,86 @@ public EzyDisconnectUserImpl(EzyServerContext ctx) { @Override public Boolean execute() { - notifyServer(); - sendToClient(); - disconnect(); - return Boolean.TRUE; + notifyServer(); + removeUserFromApps(); + sendToClients(); + disconnectSessions(); + destroyUser(); + return Boolean.TRUE; } - protected void sendToClient() { + protected void sendToClients() { if(fireClientEvent) - doSendToClient(); + doSendToClients(); } - protected void doSendToClient() { - context.get(EzySendMessage.class) - .sender(session) - .data(getDisconnectData()) - .execute(); + protected void notifyServer() { + if(fireServerEvent) + doNotifyServer(); } - protected EzyArray getDisconnectData() { - return serializeToArray(context, newDisconnectResponse()); + protected void doNotifyServer() { + try { + context.get(EzyFireAppEvent.class) + .filter(appCtxt -> containsUser(appCtxt, user)) + .fire(EzyEventType.USER_DISCONNECT, newDisconnectEvent()); + } + catch(Exception e) { + getLogger().error("notify user disconnect to server error", e); + } } - protected EzyResponse newDisconnectResponse() { - return EzyDisconnectResponse.builder() + protected EzyEvent newDisconnectEvent() { + return EzyUserDisconnectEventImpl.builder() + .user(user) .reason(reason) .build(); } - protected void notifyServer() { - if(shouldNotifyServer()) - doNotifyServer(); + protected void disconnectSessions() { + sessions.forEach(this::disconnectSession); } - protected boolean shouldNotifyServer() { - return user != null && fireServerEvent; + protected void disconnectSession(EzySession session) { + getLogger().info("disconnect session: {}, reason: {}", session.getClientAddress(), reason); + session.disconnect(); + session.close(); + } + + protected void doSendToClients() { + sessions.forEach(this::doSendToClient); + } + + protected void doSendToClient(EzySession session) { + response(context, session, newResponse()); } - protected void doNotifyServer() { - context.get(EzyFireAppEvent.class) - .fire(EzyEventType.USER_DISCONNECT, newDisconnectEvent()); + protected void destroyUser() { + user.destroy(); } - protected EzyEvent newDisconnectEvent() { - return EzyDisconnectEventImpl.builder() - .user(user) - .reason(reason) - .build(); + protected void removeUserFromApps() { + forEachAppContexts(context, this::removeUserFromApp); + } + + protected void removeUserFromApp(EzyAppContext ctx) { + removeUserFromApp(ctx.getApp().getUserManager()); } - protected void disconnect() { - session.disconnect(); - session.close(); + protected void removeUserFromApp(EzyUserManager userManager) { + if(userManager.containsUser(user)) + userManager.removeUser(user); } + + protected EzyResponse newResponse() { + return EzyDisconnectResponse.builder().reason(reason).build(); + } @Override public EzyDisconnectUser user(EzyUser user) { this.user = user; - return user != null ? session(user.getSession()) : this; - } - - @Override - public EzyDisconnectUser session(EzySession session) { - this.session = session; + if(user != null) + this.sessions.addAll(user.getSessions()); return this; } @@ -113,7 +135,7 @@ public EzyDisconnectUser fireClientEvent(boolean value) { @Override public EzyDisconnectUser fireServerEvent(boolean value) { - this.fireClientEvent = value; + this.fireServerEvent = value; return this; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireAppEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireAppEventImpl.java index e4de8df9..58760883 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireAppEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireAppEventImpl.java @@ -1,6 +1,7 @@ package com.tvd12.ezyfoxserver.command.impl; import java.util.Set; +import java.util.function.Predicate; import com.tvd12.ezyfoxserver.EzyServer; import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; @@ -10,15 +11,24 @@ import com.tvd12.ezyfoxserver.context.EzyServerContext; import com.tvd12.ezyfoxserver.event.EzyEvent; -import lombok.AllArgsConstructor; - -@AllArgsConstructor public class EzyFireAppEventImpl extends EzyAbstractCommand implements EzyFireAppEvent { - private EzyServerContext context; + protected EzyServerContext context; + protected Predicate filter; + + public EzyFireAppEventImpl(EzyServerContext context) { + this.context = context; + } + + @Override + public EzyFireAppEvent filter(Predicate filter) { + this.filter = filter; + return this; + } @Override public void fire(EzyConstant type, EzyEvent event) { + getLogger().debug("fire event {}", type); fireAppsEvent(type, event); } @@ -27,18 +37,24 @@ protected void fireAppsEvent(EzyConstant type, EzyEvent event) { } protected void fireAppEvent(int appId, EzyConstant type, EzyEvent event) { - fireAppEvent(context.getAppContext(appId), type, event); + EzyAppContext appCtxt = context.getAppContext(appId); + if(shouldFireAppEvent(appCtxt)) + fireAppEvent(appCtxt, type, event); } protected void fireAppEvent(EzyAppContext ctx, EzyConstant type, EzyEvent event) { ctx.get(EzyFireEvent.class).fire(type, event); } + protected boolean shouldFireAppEvent(EzyAppContext appContext) { + return filter != null && filter.test(appContext); + } + protected Set getAppIds() { return getServer().getAppIds(); } protected EzyServer getServer() { - return context.getBoss(); + return context.getServer(); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireEventImpl.java index 80c636f2..07b82f93 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFireEventImpl.java @@ -19,6 +19,7 @@ public class EzyFireEventImpl extends EzyAbstractCommand implements EzyFireEvent @Override public void fire(EzyConstant type, EzyEvent event) { + getLogger().debug("fire event {}", type); firePluginsEvent(type, event); fireAppsEvent(type, event); } @@ -56,6 +57,6 @@ protected Set getPluginIds() { } protected EzyServer getServer() { - return context.getBoss(); + return context.getServer(); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFirePluginEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFirePluginEventImpl.java index dad1f721..3215e8ae 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFirePluginEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyFirePluginEventImpl.java @@ -2,30 +2,41 @@ import java.util.Set; -import com.tvd12.ezyfoxserver.EzyServer; import com.tvd12.ezyfoxserver.command.EzyFireEvent; import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.context.EzyPluginContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyEventPluginsMapper; -import lombok.AllArgsConstructor; - -@AllArgsConstructor public class EzyFirePluginEventImpl extends EzyAbstractCommand implements EzyFirePluginEvent { - private EzyServerContext context; + private final EzyServerContext context; + private final EzyEventPluginsMapper eventPluginsMapper; + + public EzyFirePluginEventImpl(EzyServerContext context) { + this.context = context; + this.eventPluginsMapper = context.getServer().getEventPluginsMapper(); + } @Override public void fire(EzyConstant type, EzyEvent event) { + getLogger().debug("fire event {}", type); firePluginsEvent(type, event); } + protected Set getValidPlugins(EzyConstant type) { + return eventPluginsMapper.getPlugins(type); + } + protected void firePluginsEvent(EzyConstant type, EzyEvent event) { - getPluginIds().forEach((pluginId) -> firePluginEvent(pluginId, type, event)); + getValidPlugins(type).forEach(plugin -> + firePluginEvent(plugin.getId(), type, event) + ); } protected void firePluginEvent(int pluginId, EzyConstant type, EzyEvent event) { @@ -35,12 +46,4 @@ protected void firePluginEvent(int pluginId, EzyConstant type, EzyEvent event) { protected void firePluginEvent(EzyPluginContext ctx, EzyConstant type, EzyEvent event) { ctx.get(EzyFireEvent.class).fire(type, event); } - - protected Set getPluginIds() { - return getServer().getPluginIds(); - } - - protected EzyServer getServer() { - return context.getBoss(); - } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyHasSenderCommand.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyHasSenderCommand.java new file mode 100644 index 00000000..c73f27cd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyHasSenderCommand.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import com.tvd12.ezyfoxserver.entity.EzySender; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public abstract class EzyHasSenderCommand> extends EzyAbstractCommand { + + protected EzySender sender; + + @SuppressWarnings("unchecked") + public T sender(EzySender sender) { + this.sender = sender; + return (T)this; + } + + protected String getSenderName() { + if(sender instanceof EzyUser) + return ((EzyUser)sender).getName(); + return ((EzySession)sender).getClientAddress().toString(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginFireEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginFireEventImpl.java index df62980e..8e4768d7 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginFireEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginFireEventImpl.java @@ -1,10 +1,11 @@ package com.tvd12.ezyfoxserver.command.impl; import com.tvd12.ezyfoxserver.command.EzyFireEvent; -import com.tvd12.ezyfoxserver.config.EzyPlugin; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.controller.EzyEventController; import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; public class EzyPluginFireEventImpl @@ -17,17 +18,30 @@ public EzyPluginFireEventImpl(EzyPluginContext context) { this.context = context; } - @SuppressWarnings("unchecked") - @Override + @SuppressWarnings("rawtypes") + @Override public void fire(EzyConstant type, EzyEvent event) { - getEventControllers().getController(type).handle(context, event); + EzyEventController ctrl = getEventController(type); + getLogger().debug("fire event {}, controller = {}", type, ctrl); + fire(ctrl, event); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected void fire(EzyEventController ctrl, EzyEvent event) { + if(ctrl != null) + ctrl.handle(context, event); + } + + @SuppressWarnings("rawtypes") + protected EzyEventController getEventController(EzyConstant type) { + return getEventControllers().getController(type); } protected EzyEventControllers getEventControllers() { - return getPlugin().getEventControllers(); + return getPluginSetting().getEventControllers(); } - protected EzyPlugin getPlugin() { - return context.getPlugin(); + protected EzyPluginSetting getPluginSetting() { + return context.getPlugin().getSetting(); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginResponseImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginResponseImpl.java new file mode 100644 index 00000000..d1968bb8 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzyPluginResponseImpl.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import com.tvd12.ezyfoxserver.command.EzyPluginResponse; +import com.tvd12.ezyfoxserver.context.EzyContexts; +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.response.EzyRequestPluginResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse.Builder; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; + +public class EzyPluginResponseImpl + extends EzyAbstractResponse + implements EzyPluginResponse { + + public EzyPluginResponseImpl(EzyPluginContext context) { + super(context); + } + + @Override + protected EzyUserManager getUserManager(EzyPluginContext context) { + return EzyContexts.getUserManager(context.getParent()); + } + + @Override + protected Builder newResponseBuilder(EzyData data) { + return newResponseBuilder(context.getPlugin().getSetting(), data); + } + + protected Builder newResponseBuilder(EzyPluginSetting setting, EzyData data) { + return EzyRequestPluginResponse.builder() + .pluginName(setting.getName()) + .data(data); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendMessageImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendMessageImpl.java index 58abc5c3..82d8e256 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendMessageImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendMessageImpl.java @@ -2,18 +2,18 @@ import com.tvd12.ezyfoxserver.command.EzySendMessage; import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzySender; -public class EzySendMessageImpl extends EzyAbstractCommand implements EzySendMessage { +public class EzySendMessageImpl + extends EzyHasSenderCommand + implements EzySendMessage { - private EzyData data; - private EzySender sender; + protected EzyData data; @Override public Boolean execute() { try { sender.send(data); - getLogger().debug("send data {} to client", data); + getLogger().debug("send to {} data {}", getSenderName(), data); return Boolean.TRUE; } catch(Exception e) { @@ -22,12 +22,6 @@ public Boolean execute() { return Boolean.FALSE; } - @Override - public EzySendMessage sender(EzySender sender) { - this.sender = sender; - return this; - } - @Override public EzySendMessage data(EzyData data) { this.data = data; 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 new file mode 100644 index 00000000..e5c59bdd --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/command/impl/EzySendResponseImpl.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.command.impl; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.command.EzySendResponse; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; + +public class EzySendResponseImpl + extends EzyHasSenderCommand + implements EzySendResponse { + + protected EzyResponse response; + + protected final Set unloggableCommands; + protected final EzyResponseSerializer responseSerializer; + + public EzySendResponseImpl(EzyServerContext context) { + this.responseSerializer = context.get(EzyResponseSerializer.class); + this.unloggableCommands = context.getServer() + .getSettings().getLogger().getIgnoredCommands().getCommands(); + } + + @Override + public Boolean execute() { + EzyArray data = responseSerializer.serializeToArray(response); + debugLogResponse(data); + sender.send(data); + return Boolean.TRUE; + } + + protected void debugLogResponse(Object data) { + if(!unloggableCommands.contains(response.getCommand())) + getLogger().debug("send to {} data {}", getSenderName(), data); + } + + @Override + public EzySendResponse response(EzyResponse response) { + this.response = response; + return this; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyAbstractConfig.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyAbstractConfig.java deleted file mode 100644 index 91757d97..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyAbstractConfig.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.concurrent.atomic.AtomicInteger; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.controller.EzyEventController; -import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; - -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -@XmlAccessorType(XmlAccessType.NONE) -public abstract class EzyAbstractConfig implements EzyEventControllerAdder { - - protected final int id; - - @XmlElement(name = "name") - protected String name; - - @XmlElement(name = "entry-loader") - protected String entryLoader; - - protected int numThreads; - - @JsonIgnore - protected transient EzyEventControllers eventControllers; - - { - numThreads = 30; - eventControllers = newEventControllers(); - } - - public EzyAbstractConfig() { - this.id = getIdCounter().incrementAndGet(); - } - - @SuppressWarnings("rawtypes") - @Override - public void addEventController(EzyConstant eventType, EzyEventController ctrl) { - eventControllers.addController(eventType, ctrl); - } - - protected abstract AtomicInteger getIdCounter(); - protected abstract EzyEventControllers newEventControllers(); - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApp.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApp.java deleted file mode 100644 index 34bd3ac5..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApp.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.concurrent.atomic.AtomicInteger; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; - -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyEventAppControllersImpl; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Setter -@Getter -@ToString -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "application") -@JsonPropertyOrder({"id", "name", "entryLoader"}) -public class EzyApp extends EzyAbstractConfig { - - private static final AtomicInteger COUNTER; - - static { - COUNTER = new AtomicInteger(0); - } - - protected EzyEventControllers newEventControllers() { - return EzyEventAppControllersImpl.builder().build(); - } - - @Override - protected AtomicInteger getIdCounter() { - return COUNTER; - } -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApps.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApps.java deleted file mode 100644 index 6d9f5778..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyApps.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Setter -@Getter -@ToString -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "applications") -@JsonIgnoreProperties({"appsByIds", "appsByNames", "appNames", "appIds"}) -@JsonPropertyOrder({"size", "apps"}) -public class EzyApps { - - protected final List apps; - protected final Map appsByIds; - protected final Map appsByNames; - - public EzyApps() { - this.apps = new ArrayList<>(); - this.appsByIds = new ConcurrentHashMap<>(); - this.appsByNames = new ConcurrentHashMap<>(); - } - - @XmlElement(name = "application") - public void setItems(final EzyApp[] items) { - for(EzyApp item : items) - setItem(item); - } - - @XmlTransient - private void setItem(final EzyApp item) { - apps.add(item); - appsByIds.put(item.getId(), item); - appsByNames.put(item.getName(), item); - } - - public Set getAppNames() { - return appsByNames.keySet(); - } - - public Set getAppIds() { - return appsByIds.keySet(); - } - - public EzyApp getAppByName(final String name) { - if(appsByNames.containsKey(name)) - return appsByNames.get(name); - throw new IllegalArgumentException("has no app with name: " + name); - } - - public EzyApp getAppById(final Integer id) { - if(appsByIds.containsKey(id)) - return appsByIds.get(id); - throw new IllegalArgumentException("has no app with id: " + id); - } - - public int getSize() { - return apps.size(); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfig.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfig.java index 1c8bb3ff..b6a89d6f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfig.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfig.java @@ -1,23 +1,11 @@ package com.tvd12.ezyfoxserver.config; -import com.tvd12.properties.file.annotation.Property; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Setter -@Getter -@ToString -public class EzyConfig { - - @Property("ezyfox.home") - private String ezyfoxHome; - - @Property("ezyfox.version") - private String ezyfoxVersion; - - @Property("logback.config.file") - private String logbackConfigFile; - +public interface EzyConfig { + + String getEzyfoxHome(); + + String getEzyfoxVersion(); + + String getLoggerConfigFile(); + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigLoader.java new file mode 100644 index 00000000..7d3cb7f5 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyConfigLoader.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.config; + +import com.tvd12.ezyfoxserver.function.EzyLoader; + +public interface EzyConfigLoader extends EzyLoader { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugin.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugin.java deleted file mode 100644 index a84dad7c..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugin.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.concurrent.atomic.AtomicInteger; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyEventPluginControllersImpl; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Setter -@Getter -@ToString -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "plugin") -@JsonPropertyOrder({"id", "name", "entryLoader", "priority"}) -public class EzyPlugin extends EzyAbstractConfig { - - @XmlElement(name = "priority") - protected int priority; - - private static final AtomicInteger COUNTER; - - static { - COUNTER = new AtomicInteger(0); - } - - @Override - protected EzyEventControllers newEventControllers() { - return EzyEventPluginControllersImpl.builder().build(); - } - - @Override - protected AtomicInteger getIdCounter() { - return COUNTER; - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugins.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugins.java deleted file mode 100644 index 6f3a68dc..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyPlugins.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Setter -@Getter -@ToString -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "plugins") -@JsonIgnoreProperties({"pluginsByIds", "pluginsByNames", "pluginNames", "pluginIds"}) -@JsonPropertyOrder({"size", "plugins"}) -public class EzyPlugins { - - protected final List plugins; - protected final Map pluginsByIds; - protected final Map pluginsByNames; - - public EzyPlugins() { - this.plugins = new ArrayList<>(); - this.pluginsByIds = new ConcurrentHashMap<>(); - this.pluginsByNames = new ConcurrentHashMap<>(); - } - - @XmlElement(name = "plugin") - public void setItems(final EzyPlugin[] items) { - for(EzyPlugin item : items) - setItem(item); - } - - @XmlTransient - private void setItem(final EzyPlugin item) { - plugins.add(item); - pluginsByIds.put(item.getId(), item); - pluginsByNames.put(item.getName(), item); - } - - public Set getPluginNames() { - return pluginsByNames.keySet(); - } - - public Set getPluginIds() { - return pluginsByIds.keySet(); - } - - public EzyPlugin getPluginByName(final String name) { - if(pluginsByNames.containsKey(name)) - return pluginsByNames.get(name); - throw new IllegalArgumentException("has no plugin with name: " + name); - } - - public EzyPlugin getPluginById(final Integer id) { - if(pluginsByIds.containsKey(id)) - return pluginsByIds.get(id); - throw new IllegalArgumentException("has no plugin with id: " + id); - } - - public int getSize() { - return plugins.size(); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySettings.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySettings.java deleted file mode 100644 index f9f6cb3a..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySettings.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.tvd12.ezyfoxserver.config; - -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Getter -@Setter -@ToString -@XmlAccessorType(XmlAccessType.NONE) -@XmlRootElement(name = "settings") -@JsonIgnoreProperties(ignoreUnknown = true) -public class EzySettings { - - protected int numThreads; - - @XmlElement(name = "applications") - protected EzyApps applications; - - @XmlElement(name = "plugins") - protected EzyPlugins plugins; - - { - numThreads = 30; - } - - //==================== apps ================// - @JsonIgnore - public Set getAppNames() { - return applications.getAppNames(); - } - - @JsonIgnore - public Set getAppIds() { - return applications.getAppIds(); - } - - public EzyApp getAppByName(final String name) { - return applications.getAppByName(name); - } - - public EzyApp getAppById(final Integer id) { - return applications.getAppById(id); - } - //=============================================// - - //==================== plugins ================// - @JsonIgnore - public Set getPluginNames() { - return plugins.getPluginNames(); - } - - @JsonIgnore - public Set getPluginIds() { - return plugins.getPluginIds(); - } - - public EzyPlugin getPluginByName(final String name) { - return plugins.getPluginByName(name); - } - - public EzyPlugin getPluginById(final Integer id) { - return plugins.getPluginById(id); - } - //=============================================// - -} 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 new file mode 100644 index 00000000..deb33233 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfig.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.config; + +import com.tvd12.ezyfoxserver.util.EzyReturner; +import com.tvd12.properties.file.annotation.Property; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleConfig implements EzyConfig { + + @Property("ezyfox.home") + private String ezyfoxHome; + + @Property("ezyfox.version") + private String ezyfoxVersion; + + @Property("logger.config.file") + private String loggerConfigFile; + + public String getEzyfoxHome() { + return EzyReturner.returnNotNull(ezyfoxHome, ""); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfigLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfigLoader.java new file mode 100644 index 00000000..63177876 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzySimpleConfigLoader.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.config; + +import com.tvd12.ezyfoxserver.mapping.properties.EzyPropertiesFileReader; +import com.tvd12.ezyfoxserver.mapping.properties.EzySimplePropertiesFileMapper; + +public class EzySimpleConfigLoader implements EzyConfigLoader { + + @Override + public EzyConfig load(String filePath) { + return newPropertiesReader().read(filePath, EzySimpleConfig.class); + } + + protected EzyPropertiesFileReader newPropertiesReader() { + return EzySimplePropertiesFileMapper.builder() + .context(getClass()) + .build(); + } +} 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 02a867c8..df2fefb7 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 @@ -1,15 +1,24 @@ package com.tvd12.ezyfoxserver.constant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + import lombok.Getter; public enum EzyCommand implements EzyConstant { - ERROR(0), - HAND_SHAKE(1), - LOGIN(2), - ACCESS_APP(3), - REQUEST_APP(4), - DISCONNECT(5); + ERROR(10), + HANDSHAKE(11), + PING(12), + PONG(13), + DISCONNECT(14), + PLUGIN_REQUEST(15), + LOGIN(20), + LOGIN_ERROR(21), + LOGOUT(22), + APP_ACCESS(30), + APP_REQUEST(31), + APP_JOINED(32), + APP_EXIT(33); @Getter private final int id; @@ -24,10 +33,7 @@ public String getName() { } public static EzyCommand valueOf(int id) { - for(EzyCommand cmd : values()) - if(cmd.getId() == id) - return cmd; - throw new IllegalArgumentException("has no command with id = " + id); + return EzyEnums.valueOf(values(), id); } } 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 new file mode 100644 index 00000000..e9315103 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConnectionType.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +import lombok.Getter; + +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(); + } + +} 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 35ccde9f..ee9b21ed 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 @@ -1,5 +1,7 @@ package com.tvd12.ezyfoxserver.constant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + import lombok.Getter; public enum EzyDisconnectReason implements EzyConstant { @@ -7,7 +9,11 @@ public enum EzyDisconnectReason implements EzyConstant { UNKNOWN(0), IDLE(1), NOT_LOGGED_IN(2), - ANOTHER_DEVICE_LOGIN(3); + ANOTHER_SESSION_LOGIN(3), + ADMIN_BAN(4), + ADMIN_KICK(5), + MAX_REQUEST_PER_SECOND(6), + MAX_REQUEST_SIZE(7); @Getter private final int id; @@ -22,10 +28,7 @@ public String getName() { } public static EzyDisconnectReason valueOf(int id) { - for(EzyDisconnectReason reason : values()) - if(reason.getId() == id) - return reason; - throw new IllegalArgumentException("has no event with id = " + id); + return EzyEnums.valueOf(values(), id); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java new file mode 100644 index 00000000..520ce05a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyError implements EzyIError { + + MAX_REQUEST_PER_SECOND(0, "max request per second"); + + @Getter + private final int id; + + @Getter + private final String message; + + private EzyError(int id, String message) { + this.id = id; + this.message = message; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyError valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } + +} 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 67934c1b..678148bc 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 @@ -1,14 +1,24 @@ package com.tvd12.ezyfoxserver.constant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + import lombok.Getter; public enum EzyEventType implements EzyConstant { SERVER_READY(1), - USER_LOGIN(2), - USER_REQUEST(3), - USER_DISCONNECT(4); - + USER_HANDSHAKE(20), + USER_LOGIN(21), + USER_SESSION_LOGIN(22), + USER_REQUEST(23), + USER_DISCONNECT(24), + USER_RECONNECT(25), + USER_ACCESS_APP(26), + USER_JOINED_APP(27), + USER_ADDED(28), + USER_REMOVED(29), + SESSION_REMOVED(35); + @Getter private final int id; @@ -22,10 +32,7 @@ public String getName() { } public static EzyEventType valueOf(int id) { - for(EzyEventType event : values()) - if(event.getId() == id) - return event; - throw new IllegalArgumentException("has no event with id = " + id); + return EzyEnums.valueOf(values(), id); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyIError.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyIError.java new file mode 100644 index 00000000..891d4500 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyIError.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyIError extends EzyConstant { + + String getMessage(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyILoginError.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyILoginError.java new file mode 100644 index 00000000..03eb8398 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyILoginError.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyILoginError extends EzyIError { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLockName.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLockName.java new file mode 100644 index 00000000..83d846ca --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLockName.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.constant; + +public final class EzyLockName { + + public static final String REMOVE = "REMOVE"; + + private EzyLockName() { + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLoginError.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLoginError.java new file mode 100644 index 00000000..a2e9a142 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyLoginError.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyLoginError implements EzyILoginError { + + INVALID_DATA(0, "invalid data"), + ALREADY_LOGIN(1, "already logged in"), + INVALID_USERNAME(2, "invalid user name"), + INVALID_PASSWORD(3, "invalid password"), + INVALID_TOKEN(4, "invalid token"), + MAXIMUM_SESSION(5, "has gotten maximum sessions"); + + @Getter + private final int id; + + @Getter + private final String message; + + private EzyLoginError(int id, String message) { + this.id = id; + this.message = message; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyLoginError valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } + +} 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 new file mode 100644 index 00000000..0b41f642 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyMaxRequestPerSecondAction.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyMaxRequestPerSecondAction implements EzyConstant { + + DROP_REQUEST(1), + DISCONNECT_SESSION(2); + + @Getter + private final int id; + + private EzyMaxRequestPerSecondAction(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyMaxRequestPerSecondAction valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzySessionRemoveReason.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzySessionRemoveReason.java index fcf0fb37..2142bd0f 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzySessionRemoveReason.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzySessionRemoveReason.java @@ -1,5 +1,7 @@ package com.tvd12.ezyfoxserver.constant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + import lombok.Getter; public enum EzySessionRemoveReason implements EzyConstant { @@ -7,7 +9,11 @@ public enum EzySessionRemoveReason implements EzyConstant { UNKNOWN(0), IDLE(1), NOT_LOGGED_IN(2), - ANOTHER_DEVICE_LOGIN(3); + ANOTHER_DEVICE_LOGIN(3), + ADMIN_BAN(4), + ADMIN_KICK(5), + MAX_REQUEST_PER_SECOND(6), + MAX_REQUEST_SIZE(7); @Getter private final int id; @@ -22,10 +28,7 @@ public String getName() { } public static EzySessionRemoveReason valueOf(int id) { - for(EzySessionRemoveReason reason : values()) - if(reason.getId() == id) - return reason; - throw new IllegalArgumentException("has no event with id = " + id); + return EzyEnums.valueOf(values(), 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 new file mode 100644 index 00000000..c8ad6eb2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyTransportType.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +import lombok.Getter; + +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(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyUserRemoveReason.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyUserRemoveReason.java new file mode 100644 index 00000000..42c0c51e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/constant/EzyUserRemoveReason.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.constant; + +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyUserRemoveReason implements EzyConstant { + + UNKNOWN(0), + IDLE(1), + ADMIN_BAN(4), + ADMIN_KICK(5); + + @Getter + private final int id; + + private EzyUserRemoveReason(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyUserRemoveReason valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } + +} 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 261f51ae..a41680b2 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 @@ -19,11 +19,7 @@ public abstract class EzyAbstractContext extends EzyEntity { protected ExecutorService workerExecutor; @SuppressWarnings("rawtypes") - protected Map commandSuppliers; - - { - commandSuppliers = defaultCommandSuppliers(); - } + protected Map commandSuppliers = defaultCommandSuppliers(); @SuppressWarnings("rawtypes") protected Map defaultCommandSuppliers() { 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 0555d950..3a450aac 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 @@ -1,9 +1,9 @@ package com.tvd12.ezyfoxserver.context; -import com.tvd12.ezyfoxserver.config.EzyApp; +import com.tvd12.ezyfoxserver.EzyApplication; -public interface EzyAppContext extends EzyContext { +public interface EzyAppContext extends EzyChildContext { - EzyApp getApp(); + EzyApplication getApp(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyChildContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyChildContext.java index 878ee45e..b751c398 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyChildContext.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyChildContext.java @@ -1,48 +1,7 @@ package com.tvd12.ezyfoxserver.context; -import java.util.Set; +public interface EzyChildContext extends EzyContext { -import com.google.common.collect.Sets; - -import lombok.Setter; - -public class EzyChildContext extends EzyAbstractContext { - - @Setter - protected EzyContext parent; - - @SuppressWarnings("rawtypes") - protected Set unsafeCommands; - - { - unsafeCommands = defaultUnsafeCommands(); - } - - @SuppressWarnings("unchecked") - public T get(Class clazz) { - if(unsafeCommands.contains(clazz)) - throw newUnsafeCommandException(clazz); - if(commandSuppliers.containsKey(clazz)) - return (T) commandSuppliers.get(clazz).get(); - if(containsKey(clazz)) - return getProperty(clazz); - return parent.get(clazz); - } - - @SuppressWarnings("rawtypes") - protected Set defaultUnsafeCommands() { - Set answer = Sets.newConcurrentHashSet(); - addUnsafeCommands(answer); - return answer; - } - - @SuppressWarnings("rawtypes") - protected void addUnsafeCommands(Set unsafeCommands) { - //TODO add some commands - } - - @SuppressWarnings("rawtypes") - protected RuntimeException newUnsafeCommandException(Class command) { - return new IllegalArgumentException("can not execute command " + command + " at app context"); - } + EzyServerContext getParent(); + } 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 f503088e..2b2d69fb 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 @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.context; -import com.tvd12.ezyfoxserver.entity.EzyProperties; +import com.tvd12.ezyfoxserver.util.EzyProperties; public interface EzyContext extends EzyProperties { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContexts.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContexts.java new file mode 100644 index 00000000..c81a4caa --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzyContexts.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.context; + +import java.util.Collection; +import java.util.function.Consumer; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; + +public final class EzyContexts { + + private EzyContexts() { + } + + public static EzySettings getSettings(EzyServerContext context) { + return context.getServer().getSettings(); + } + + public static boolean containsUser(EzyAppContext context, EzyUser user) { + return getUserManager(context).containsUser(user); + } + + public static boolean containsUser(EzyAppContext context, String username) { + return getUserManager(context).containsUser(username); + } + + public static EzyManagers getManagers(EzyServerContext context) { + return context.getServer().getManagers(); + } + + public static EzyUserManager getUserManager(EzyAppContext context) { + return context.getApp().getUserManager(); + } + + public static EzyServerUserManager getUserManager(EzyServerContext context) { + return getManagers(context).getManager(EzyServerUserManager.class); + } + + public static void forEachAppContexts( + EzyServerContext context, Consumer consumer) { + for(int appId : getAppIds(context)) + consumer.accept(context.getAppContext(appId)); + } + + public static Collection getAppIds(EzyServerContext context) { + return context.getServer().getAppIds(); + } + +} 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 bbcd70d1..7d8da4cf 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 @@ -1,9 +1,9 @@ package com.tvd12.ezyfoxserver.context; -import com.tvd12.ezyfoxserver.config.EzyPlugin; +import com.tvd12.ezyfoxserver.EzyPlugin; -public interface EzyPluginContext extends EzyContext { +public interface EzyPluginContext extends EzyChildContext { - EzyPlugin getPlugin(); + 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 391b3862..b583d7b7 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 @@ -4,7 +4,7 @@ public interface EzyServerContext extends EzyContext { - EzyServer getBoss(); + EzyServer getServer(); EzyAppContext getAppContext(int appId); 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 1544c7a8..5f75c276 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 @@ -4,31 +4,35 @@ import java.util.Set; import java.util.function.Supplier; +import com.tvd12.ezyfoxserver.EzyApplication; import com.tvd12.ezyfoxserver.command.EzyAddEventController; +import com.tvd12.ezyfoxserver.command.EzyAppResponse; import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; import com.tvd12.ezyfoxserver.command.EzyFireEvent; import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; import com.tvd12.ezyfoxserver.command.impl.EzyAddEventControllerImpl; import com.tvd12.ezyfoxserver.command.impl.EzyAppFireEventImpl; -import com.tvd12.ezyfoxserver.config.EzyApp; +import com.tvd12.ezyfoxserver.command.impl.EzyAppResponseImpl; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; import lombok.Getter; import lombok.Setter; public class EzySimpleAppContext - extends EzyChildContext + extends EzySimpleChildContext implements EzyAppContext { @Setter @Getter - protected EzyApp app; + protected EzyApplication app; @SuppressWarnings("rawtypes") @Override protected void addCommandSuppliers(Map suppliers) { super.addCommandSuppliers(suppliers); suppliers.put(EzyFireEvent.class, () -> new EzyAppFireEventImpl(this)); - suppliers.put(EzyAddEventController.class, () -> new EzyAddEventControllerImpl(app)); + suppliers.put(EzyAppResponse.class, () -> new EzyAppResponseImpl(this)); + suppliers.put(EzyAddEventController.class, () -> new EzyAddEventControllerImpl(getSetting())); } @SuppressWarnings("rawtypes") @@ -39,4 +43,7 @@ protected void addUnsafeCommands(Set unsafeCommands) { unsafeCommands.add(EzyFireAppEvent.class); } + protected EzyAppSetting getSetting() { + return app.getSetting(); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleChildContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleChildContext.java new file mode 100644 index 00000000..d8a18861 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleChildContext.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.context; + +import java.util.Set; + +import com.google.common.collect.Sets; + +import lombok.Getter; +import lombok.Setter; + +public class EzySimpleChildContext extends EzyAbstractContext { + + @Setter + @Getter + protected EzyServerContext parent; + + @SuppressWarnings("rawtypes") + protected Set unsafeCommands = defaultUnsafeCommands(); + + @SuppressWarnings("unchecked") + public T get(Class clazz) { + if(unsafeCommands.contains(clazz)) + throw newUnsafeCommandException(clazz); + if(commandSuppliers.containsKey(clazz)) + return (T) commandSuppliers.get(clazz).get(); + if(containsKey(clazz)) + return getProperty(clazz); + return parent.get(clazz); + } + + @SuppressWarnings("rawtypes") + protected Set defaultUnsafeCommands() { + Set answer = Sets.newConcurrentHashSet(); + addUnsafeCommands(answer); + return answer; + } + + @SuppressWarnings("rawtypes") + protected void addUnsafeCommands(Set unsafeCommands) { + //TODO add some commands + } + + @SuppressWarnings("rawtypes") + protected RuntimeException newUnsafeCommandException(Class command) { + return new IllegalArgumentException("can not execute command " + command + " at app context"); + } +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleContext.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleContext.java deleted file mode 100644 index db57e4dd..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleContext.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.tvd12.ezyfoxserver.context; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -import com.tvd12.ezyfoxserver.EzyServer; -import com.tvd12.ezyfoxserver.command.EzyDisconnectUser; -import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; -import com.tvd12.ezyfoxserver.command.EzyFireEvent; -import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.command.impl.EzyDisconnectUserImpl; -import com.tvd12.ezyfoxserver.command.impl.EzyFireAppEventImpl; -import com.tvd12.ezyfoxserver.command.impl.EzyFireEventImpl; -import com.tvd12.ezyfoxserver.command.impl.EzyFirePluginEventImpl; -import com.tvd12.ezyfoxserver.command.impl.EzySendMessageImpl; -import com.tvd12.ezyfoxserver.config.EzyApp; -import com.tvd12.ezyfoxserver.config.EzyPlugin; - -import lombok.Getter; -import lombok.Setter; - -public class EzySimpleContext extends EzyAbstractContext implements EzyServerContext { - - @Setter - @Getter - protected EzyServer boss; - - protected Map appContextsById; - protected Map appContextsByName; - protected Map pluginContextsById; - protected Map pluginContextsByName; - - { - appContextsById = new ConcurrentHashMap<>(); - appContextsByName = new ConcurrentHashMap<>(); - pluginContextsById = new ConcurrentHashMap<>(); - pluginContextsByName = new ConcurrentHashMap<>(); - } - - @SuppressWarnings("unchecked") - @Override - public T get(Class clazz) { - if(commandSuppliers.containsKey(clazz)) - return (T) commandSuppliers.get(clazz).get(); - if(containsKey(clazz)) - return getProperty(clazz); - throw new IllegalArgumentException("has no instance of " + clazz); - } - - public void addAppContext(EzyApp app, EzyAppContext appContext) { - appContextsById.putIfAbsent(app.getId(), appContext); - appContextsByName.putIfAbsent(app.getName(), appContext); - } - - public void addAppContexts(Collection appContexts) { - for(EzyAppContext ctx : appContexts) - addAppContext(ctx.getApp(), ctx); - } - - public void addPluginContext(EzyPlugin plugin, EzyPluginContext pluginContext) { - pluginContextsById.putIfAbsent(plugin.getId(), pluginContext); - pluginContextsByName.putIfAbsent(plugin.getName(), pluginContext); - } - - public void addPluginContexts(Collection pluginContexts) { - for(EzyPluginContext ctx : pluginContexts) - addPluginContext(ctx.getPlugin(), ctx); - } - - @Override - public EzyAppContext getAppContext(int appId) { - if(appContextsById.containsKey(appId)) - return appContextsById.get(appId); - throw new IllegalArgumentException("has not app with id = " + appId); - } - - @Override - public EzyAppContext getAppContext(String appName) { - if(appContextsByName.containsKey(appName)) - return appContextsByName.get(appName); - throw new IllegalArgumentException("has not app with name = " + appName); - } - - @Override - public EzyPluginContext getPluginContext(int pluginId) { - if(pluginContextsById.containsKey(pluginId)) - return pluginContextsById.get(pluginId); - throw new IllegalArgumentException("has not plugin with id = " + pluginId); - } - - @Override - public EzyPluginContext getPluginContext(String pluginName) { - if(pluginContextsByName.containsKey(pluginName)) - return pluginContextsByName.get(pluginName); - throw new IllegalArgumentException("has not plugin with name = " + pluginName); - } - - @SuppressWarnings("rawtypes") - @Override - protected void addCommandSuppliers(Map suppliers) { - super.addCommandSuppliers(suppliers); - suppliers.put(EzySendMessage.class, () -> new EzySendMessageImpl()); - suppliers.put(EzyFireEvent.class, () -> new EzyFireEventImpl(this)); - suppliers.put(EzyFirePluginEvent.class, () -> new EzyFirePluginEventImpl(this)); - suppliers.put(EzyFireAppEvent.class, ()-> new EzyFireAppEventImpl(this)); - suppliers.put(EzyDisconnectUser.class, ()-> new EzyDisconnectUserImpl(this)); - } - -} 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 a8ae7ad9..d4218e9d 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 @@ -4,18 +4,21 @@ import java.util.Set; import java.util.function.Supplier; +import com.tvd12.ezyfoxserver.EzyPlugin; import com.tvd12.ezyfoxserver.command.EzyAddEventController; import com.tvd12.ezyfoxserver.command.EzyFireEvent; import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; +import com.tvd12.ezyfoxserver.command.EzyPluginResponse; import com.tvd12.ezyfoxserver.command.impl.EzyAddEventControllerImpl; import com.tvd12.ezyfoxserver.command.impl.EzyPluginFireEventImpl; -import com.tvd12.ezyfoxserver.config.EzyPlugin; +import com.tvd12.ezyfoxserver.command.impl.EzyPluginResponseImpl; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; import lombok.Getter; import lombok.Setter; public class EzySimplePluginContext - extends EzyChildContext + extends EzySimpleChildContext implements EzyPluginContext { @Setter @@ -27,7 +30,8 @@ public class EzySimplePluginContext protected void addCommandSuppliers(Map suppliers) { super.addCommandSuppliers(suppliers); suppliers.put(EzyFireEvent.class, () -> new EzyPluginFireEventImpl(this)); - suppliers.put(EzyAddEventController.class, () -> new EzyAddEventControllerImpl(plugin)); + suppliers.put(EzyPluginResponse.class, () -> new EzyPluginResponseImpl(this)); + suppliers.put(EzyAddEventController.class, () -> new EzyAddEventControllerImpl(getSetting())); } @SuppressWarnings("rawtypes") @@ -37,4 +41,8 @@ protected void addUnsafeCommands(Set unsafeCommands) { unsafeCommands.add(EzyFirePluginEvent.class); } + protected EzyPluginSetting getSetting() { + return plugin.getSetting(); + } + } 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 new file mode 100644 index 00000000..67665314 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/context/EzySimpleServerContext.java @@ -0,0 +1,111 @@ +package com.tvd12.ezyfoxserver.context; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.command.EzyDisconnectSession; +import com.tvd12.ezyfoxserver.command.EzyDisconnectUser; +import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; +import com.tvd12.ezyfoxserver.command.EzyFireEvent; +import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; +import com.tvd12.ezyfoxserver.command.EzySendMessage; +import com.tvd12.ezyfoxserver.command.EzySendResponse; +import com.tvd12.ezyfoxserver.command.impl.EzyDisconnectSessionImpl; +import com.tvd12.ezyfoxserver.command.impl.EzyDisconnectUserImpl; +import com.tvd12.ezyfoxserver.command.impl.EzyFireAppEventImpl; +import com.tvd12.ezyfoxserver.command.impl.EzyFireEventImpl; +import com.tvd12.ezyfoxserver.command.impl.EzyFirePluginEventImpl; +import com.tvd12.ezyfoxserver.command.impl.EzySendMessageImpl; +import com.tvd12.ezyfoxserver.command.impl.EzySendResponseImpl; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +import lombok.Getter; +import lombok.Setter; + +public class EzySimpleServerContext extends EzyAbstractContext implements EzyServerContext { + + @Setter + @Getter + protected EzyServer server; + + protected Map appContextsById = new ConcurrentHashMap<>(); + protected Map appContextsByName = new ConcurrentHashMap<>(); + protected Map pluginContextsById = new ConcurrentHashMap<>(); + protected Map pluginContextsByName = new ConcurrentHashMap<>(); + + @SuppressWarnings("unchecked") + @Override + public T get(Class clazz) { + if(commandSuppliers.containsKey(clazz)) + return (T) commandSuppliers.get(clazz).get(); + if(containsKey(clazz)) + return getProperty(clazz); + throw new IllegalArgumentException("has no instance of " + clazz); + } + + public void addAppContext(EzyAppSetting app, EzyAppContext appContext) { + appContextsById.put(app.getId(), appContext); + appContextsByName.put(app.getName(), appContext); + } + + public void addAppContexts(Collection appContexts) { + for(EzyAppContext ctx : appContexts) + addAppContext(ctx.getApp().getSetting(), ctx); + } + + public void addPluginContext(EzyPluginSetting plugin, EzyPluginContext pluginContext) { + pluginContextsById.put(plugin.getId(), pluginContext); + pluginContextsByName.put(plugin.getName(), pluginContext); + } + + public void addPluginContexts(Collection pluginContexts) { + for(EzyPluginContext ctx : pluginContexts) + addPluginContext(ctx.getPlugin().getSetting(), ctx); + } + + @Override + public EzyAppContext getAppContext(int appId) { + if(appContextsById.containsKey(appId)) + return appContextsById.get(appId); + throw new IllegalArgumentException("has not app with id = " + appId); + } + + @Override + public EzyAppContext getAppContext(String appName) { + if(appContextsByName.containsKey(appName)) + return appContextsByName.get(appName); + throw new IllegalArgumentException("has not app with name = " + appName); + } + + @Override + public EzyPluginContext getPluginContext(int pluginId) { + if(pluginContextsById.containsKey(pluginId)) + return pluginContextsById.get(pluginId); + throw new IllegalArgumentException("has not plugin with id = " + pluginId); + } + + @Override + public EzyPluginContext getPluginContext(String pluginName) { + if(pluginContextsByName.containsKey(pluginName)) + return pluginContextsByName.get(pluginName); + throw new IllegalArgumentException("has not plugin with name = " + pluginName); + } + + @SuppressWarnings("rawtypes") + @Override + protected void addCommandSuppliers(Map suppliers) { + super.addCommandSuppliers(suppliers); + suppliers.put(EzySendMessage.class, () -> new EzySendMessageImpl()); + suppliers.put(EzySendResponse.class, () -> new EzySendResponseImpl(this)); + suppliers.put(EzyFireEvent.class, () -> new EzyFireEventImpl(this)); + suppliers.put(EzyFirePluginEvent.class, () -> new EzyFirePluginEventImpl(this)); + suppliers.put(EzyFireAppEvent.class, ()-> new EzyFireAppEventImpl(this)); + suppliers.put(EzyDisconnectUser.class, ()-> new EzyDisconnectUserImpl(this)); + suppliers.put(EzyDisconnectSession.class, ()-> new EzyDisconnectSessionImpl(this)); + } + +} 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 9f0dc9e6..8ce244f5 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 @@ -1,9 +1,9 @@ package com.tvd12.ezyfoxserver.controller; -import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; public abstract class EzyAbstractAppEventController - extends EzyLoggable + extends EzyEntityBuilders implements EzyAppEventController { } 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 c99dff08..1d07562b 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 @@ -5,23 +5,28 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; import com.tvd12.ezyfoxserver.wrapper.EzyManagers; import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; -import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; public class EzyAbstractServerController extends EzyAbstractController { protected EzyServer getServer(EzyServerContext ctx) { - return ctx.getBoss(); + return ctx.getServer(); + } + + protected EzySettings getSettings(EzyServerContext ctx) { + return getServer(ctx).getSettings(); } protected EzyManagers getManagers(EzyServerContext ctx) { return getServer(ctx).getManagers(); } - protected EzyUserManager getUserManager(EzyServerContext ctx) { - return getManagers(ctx).getManager(EzyUserManager.class); + protected EzyServerUserManager getUserManager(EzyServerContext ctx) { + return getManagers(ctx).getManager(EzyServerUserManager.class); } @SuppressWarnings("unchecked") @@ -37,7 +42,7 @@ protected EzyAppContext getAppContext(EzyServerContext ctx, String appName) { return ctx.getAppContext(appName); } - protected EzyControllers getControllers(EzyServerContext ctx) { + protected EzyServerControllers getControllers(EzyServerContext ctx) { return getServer(ctx).getControllers(); } @@ -45,4 +50,5 @@ protected EzyControllers getControllers(EzyServerContext ctx) { 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 d0e1b839..b01ab6be 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 @@ -1,46 +1,61 @@ package com.tvd12.ezyfoxserver.controller; -import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.config.EzyApp; -import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.EzyApplication; +import com.tvd12.ezyfoxserver.command.EzyFireEvent; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.entity.EzySession; import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.EzyUserAccessAppEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserAccessAppEventImpl; +import com.tvd12.ezyfoxserver.event.impl.EzyUserJoinedAppEventImpl; +import com.tvd12.ezyfoxserver.request.EzyAccessAppParams; +import com.tvd12.ezyfoxserver.request.EzyAccessAppRequest; import com.tvd12.ezyfoxserver.response.EzyAccessAppResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; public class EzyAccessAppController extends EzyAbstractServerController - implements EzyServerController { + implements EzyServerController { @Override - public void handle(EzyServerContext ctx, EzyUser user, EzyArray data) { - getLogger().info("begin access app handler {}", data); - process(ctx, user, data); - getLogger().info("end access app handler"); + public void handle(EzyServerContext ctx, EzyAccessAppRequest request) { + EzyAccessAppParams params = request.getParams(); + EzyAppContext appContext = ctx.getAppContext(params.getAppName()); + EzyApplication app = appContext.getApp(); + EzyAppSetting appSetting = app.getSetting(); + EzyAppUserManager appUserManger = app.getUserManager(); + EzyUser user = request.getUser(); + addUser(appUserManger, user, appSetting); + EzyUserAccessAppEvent accessAppEvent = newAccessAppEvent(user); + appContext.get(EzyFireEvent.class).fire(EzyEventType.USER_ACCESS_APP, accessAppEvent); + EzyData ouput = accessAppEvent.getOutput(); + EzySession session = request.getSession(); + response(ctx, session, newAccessAppResponse(appSetting, ouput)); + EzyEvent joinedAppEvent = newJoinedAppEvent(user, session); + appContext.get(EzyFireEvent.class).fire(EzyEventType.USER_JOINED_APP, joinedAppEvent); } - protected void process(EzyServerContext ctx, EzyUser user, EzyArray data) { - String appName = data.get(0); - EzyApp app = ctx.getAppContext(appName).getApp(); - response(ctx, user, getAccessAppResponse(ctx, app, newAccessAppData())); + protected void addUser(EzyAppUserManager appUserManger, EzyUser user, EzyAppSetting setting) { + if(appUserManger.addUser(user) != null) + throw new IllegalStateException("user " + user.getName() + " has already joined app " + setting.getName()); } - protected void response(EzyContext ctx, EzyUser user, EzyData out) { - ctx.get(EzySendMessage.class).sender(user).data(out).execute(); - } + protected EzyEvent newJoinedAppEvent(EzyUser user, EzySession session) { + return EzyUserJoinedAppEventImpl.builder().user(user).session(session).build(); + } - protected EzyObject newAccessAppData() { - return newObjectBuilder().build(); + protected EzyUserAccessAppEvent newAccessAppEvent(EzyUser user) { + return EzyUserAccessAppEventImpl.builder().user(user).build(); } - protected EzyArray getAccessAppResponse(EzyContext ctx, EzyApp app, EzyData out) { - return serializeToArray(ctx, newAccessAppData(app, out)); + protected EzyResponse newAccessAppResponse(EzyAppSetting app, EzyData out) { + return EzyAccessAppResponse.builder().app(app).data(out).build(); } - protected EzyAccessAppResponse newAccessAppData(EzyApp app, EzyData out) { - return EzyAccessAppResponse.builder().data(out).appId(app.getId()).build(); - } - } 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 15ca6cfa..d30d3e91 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 @@ -2,6 +2,6 @@ import com.tvd12.ezyfoxserver.context.EzyAppContext; -public interface EzyAppController - extends EzyController { +public interface EzyAppController + extends EzyController { } 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 46008b35..1a015e6e 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 { +public interface EzyController { - void handle(C ctx, R rev, D data); + void handle(C ctx, R request); } 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 a9ec5752..859c7aaa 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 @@ -1,75 +1,84 @@ package com.tvd12.ezyfoxserver.controller; -import com.tvd12.ezyfoxserver.command.EzySendMessage; import com.tvd12.ezyfoxserver.context.EzyContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyHandShakeParams; +import com.tvd12.ezyfoxserver.request.EzyHandShakeRequest; +import com.tvd12.ezyfoxserver.request.EzyReconnectRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleReconnectParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleReconnectRequest; import com.tvd12.ezyfoxserver.response.EzyHandShakeResponse; -import com.tvd12.ezyfoxserver.sercurity.EzyAsyCrypt; +import com.tvd12.ezyfoxserver.response.EzyResponse; import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting; +import com.tvd12.ezyfoxserver.util.EzyIfElse; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; public class EzyHandShakeController extends EzyAbstractServerController - implements EzyServerController { + implements EzyServerController { + private EzyReconnectController reconnectController = new EzyReconnectController(); + @Override - public void handle(EzyServerContext ctx, EzySession session, EzyArray data) { - getLogger().debug("begin hanshake handler key = {} token = {}", data.get(1), data.get(2)); - updateSession(session, data); - response(ctx, session); - getLogger().debug("end hanshake handler, token = {}", session.getReconnectToken()); + public void handle(EzyServerContext ctx, EzyHandShakeRequest request) { + EzySession session = request.getSession(); + EzyHandShakeParams params = request.getParams(); + updateSession(session, params); + process(ctx, request); } - protected void updateSession(EzySession session, EzyArray data) { - session.setClientId(data.get(0)); - session.setClientKey(EzyBase64.decode(data.get(1, String.class))); + protected void process(EzyServerContext ctx, EzyHandShakeRequest request) { + EzySessionManagementSetting setting = getSessionManagementSetting(ctx); + EzySessionManager sessionManager = getSessionManager(ctx); + EzySession newsession = request.getSession(); + EzyHandShakeParams params = request.getParams(); + String reconnectToken = params.getReconnectToken(); + EzySession oldsession = sessionManager.getSession(reconnectToken); + boolean allowReconnect = setting.isSessionAllowReconnect(); + boolean isReconnect = oldsession != null && allowReconnect; + EzyIfElse.withIf(isReconnect, ()-> processReconnect(ctx, oldsession, newsession)); + response(ctx, newsession, isReconnect); } - protected boolean isReconnect(EzyServerContext ctx, String reconnectToken) { - return getSessionManager(ctx).containsSession(reconnectToken); + protected void updateSession(EzySession session, EzyHandShakeParams params) { + session.setClientId(params.getClientId()); + session.setClientKey(EzyBase64.decode(params.getClientKey())); + session.setClientType(params.getClientType()); + session.setClientVersion(params.getClientVersion()); } - protected void response(EzyContext ctx, EzySession session) { - ctx.get(EzySendMessage.class) - .data(getResponse(ctx, session)) - .sender(session).execute(); + protected void processReconnect( + EzyServerContext ctx, EzySession oldsession, EzySession newsession) { + getLogger().info("session {} is reconnect", newsession.getClientAddress()); + reconnectController.handle(ctx, newReconnectRequest(oldsession, newsession)); } - protected EzyArray getResponse(EzyContext ctx, EzySession session) { - return serializeToArray(ctx, newResponse(session)); - } - - protected EzyHandShakeResponse newResponse(EzySession session) { - return EzyHandShakeResponse.builder() - .publicKey(encryptServerPublicKey(session)) - .reconnectToken(encryptReconnectToken(session)) - .build(); - } + protected EzyReconnectRequest + newReconnectRequest(EzySession oldsession, EzySession newsession) { + return EzySimpleReconnectRequest.builder() + .session(newsession) + .oldSession(oldsession) + .params(EzySimpleReconnectParams.builder().build()) + .build(); + } - protected String encryptServerPublicKey(EzySession session) { - return EzyBase64.decode2utf8(session.getPublicKey()); + protected void response(EzyContext ctx, EzySession session, boolean reconnect) { + response(ctx, session, newHandShakeResponse(session, reconnect)); } - protected String encryptReconnectToken(EzySession session) { - return encryptReconnectToken(session.getClientKey(), session.getReconnectToken()); + protected EzyResponse newHandShakeResponse(EzySession session, boolean reconnect) { + return EzyHandShakeResponse.builder() + .reconnect(reconnect) + .clientKey(session.getClientKey()) + .serverPublicKey(session.getPublicKey()) + .reconnectToken(session.getReconnectToken()) + .build(); } - protected String encryptReconnectToken(byte[] key, String token) { - try { - return tryEncryptReconnectToken(key, token); - } - catch(Exception e) { - throw new IllegalArgumentException(e); - } + protected EzySessionManagementSetting getSessionManagementSetting(EzyServerContext context) { + return getSettings(context).getSessionManagement(); } - protected String tryEncryptReconnectToken(byte[] key, String token) - throws Exception { - return EzyAsyCrypt.builder() - .algorithm("RSA") - .publicKey(key) - .build().encrypt(token, String.class); - } - } 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 23922e68..1f1a4184 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 @@ -1,99 +1,69 @@ package com.tvd12.ezyfoxserver.controller; import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; -import com.tvd12.ezyfoxserver.command.EzySendMessage; import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.constant.EzyILoginError; import com.tvd12.ezyfoxserver.context.EzyContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.entity.EzySimpleUser; -import com.tvd12.ezyfoxserver.entity.EzyUser; import com.tvd12.ezyfoxserver.event.EzyUserLoginEvent; import com.tvd12.ezyfoxserver.event.impl.EzyUserLoginEventImpl; -import com.tvd12.ezyfoxserver.response.EzyLoginResponse; +import com.tvd12.ezyfoxserver.exception.EzyLoginErrorException; +import com.tvd12.ezyfoxserver.request.EzyLoginParams; +import com.tvd12.ezyfoxserver.request.EzyLoginRequest; +import com.tvd12.ezyfoxserver.response.EzyLoginErrorResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; public class EzyLoginController extends EzyAbstractServerController - implements EzyServerController { + implements EzyServerController { @Override - public void handle(EzyServerContext ctx, EzySession session, EzyArray data) { - getLogger().info("begin login handler {}", data); - doHandle(ctx, session, data); - updateSession(session); - getLogger().info("end login handler"); + public void handle(EzyServerContext ctx, EzyLoginRequest request) { + try { + EzySession session = request.getSession(); + EzyLoginParams params = request.getParams(); + control(ctx, newLoginEvent(session, params)); + } + catch(EzyLoginErrorException e) { + processException(ctx, request.getSession(), e); + throw e; + } } - private void doHandle(EzyServerContext ctx, EzySession session, EzyArray data) { - try { - process(ctx, newLoginEvent(session, data)); - } - catch(Exception e) { - getLogger().error("login error", e); - } + protected void processException( + EzyServerContext ctx, EzySession session, EzyLoginErrorException e) { + responseLoginError(ctx, session, e.getError()); } - protected void process(EzyServerContext ctx, EzyUserLoginEvent event) { + protected void control(EzyServerContext ctx, EzyUserLoginEvent event) { firePluginEvent(ctx, event); - process(ctx, newUser(event), event); + process(ctx, event); } - protected void updateSession(EzySession session) { - session.setLoggedIn(true); + protected void process(EzyServerContext ctx, EzyUserLoginEvent event) { + EzyLoginProcessor.builder().context(ctx).event(event).build().apply(); } protected void firePluginEvent(EzyServerContext ctx, EzyUserLoginEvent event) { - ctx.get(EzyFirePluginEvent.class).fire(EzyEventType.USER_LOGIN, event); - } - - protected void process(EzyServerContext ctx, EzyUser user, EzyUserLoginEvent event) { - addUser(ctx, user); - response(ctx, user, event); - } - - protected void addUser(EzyServerContext ctx, EzyUser user) { - getUserManager(ctx).addUser(user); - } - - protected EzyUser newUser(EzyUserLoginEvent event) { - EzySimpleUser user = new EzySimpleUser(); - user.setName(event.getUsername()); - user.setSession(event.getSession()); - user.setPassword(event.getPassword()); - return user; - } + ctx.get(EzyFirePluginEvent.class).fire(EzyEventType.USER_LOGIN, event); + } - protected void response(EzyContext ctx, EzyUser user, EzyUserLoginEvent event) { - ctx.get(EzySendMessage.class) - .sender(user) - .data(getResponse(ctx, user, event.getOutput())) - .execute(); - } - - protected EzyArray getResponse(EzyContext ctx, EzyUser user, Object out) { - return serializeToArray(ctx, newResponse(user, out)); - } - - protected EzyLoginResponse newResponse(EzyUser user, Object output) { - return EzyLoginResponse.builder() - .data(output) - .userId(user.getId()) - .username(user.getName()) - .build(); - } - - protected EzyUserLoginEvent newLoginEvent(EzySession session, EzyArray data) { + protected EzyUserLoginEvent newLoginEvent(EzySession session, EzyLoginParams params) { return EzyUserLoginEventImpl.builder() - .username(data.get(0)) - .password(data.get(1)) - .data(getLoginData(data)) + .data(params.getData()) + .username(params.getUsername()) + .password(params.getPassword()) .session(session) .build(); } - private Object getLoginData(EzyArray data) { - return data.size() > 2 ? data.get(2) : newObjectBuilder().build(); - } - + protected void responseLoginError(EzyContext ctx, EzySession session, EzyILoginError error) { + response(ctx, session, newLoginErrorReponse(error)); + } + + protected EzyResponse newLoginErrorReponse(EzyILoginError error) { + return EzyLoginErrorResponse.builder().error(error).build(); + } + } 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 new file mode 100644 index 00000000..ed1a4e52 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyLoginProcessor.java @@ -0,0 +1,263 @@ +package com.tvd12.ezyfoxserver.controller; + +import static com.tvd12.ezyfoxserver.context.EzyContexts.containsUser; +import static com.tvd12.ezyfoxserver.context.EzyContexts.forEachAppContexts; +import static com.tvd12.ezyfoxserver.context.EzyContexts.getSettings; +import static com.tvd12.ezyfoxserver.context.EzyContexts.getUserManager; + +import java.util.concurrent.locks.Lock; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; +import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; +import com.tvd12.ezyfoxserver.command.EzySendResponse; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.constant.EzyLoginError; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.delegate.EzySimpleUserRemoveDelegate; +import com.tvd12.ezyfoxserver.delegate.EzyUserRemoveDelegate; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyHasSessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.EzyUserLoginEvent; +import com.tvd12.ezyfoxserver.event.impl.EzySessionLoginEventImpl; +import com.tvd12.ezyfoxserver.event.impl.EzyUserAddedEventImpl; +import com.tvd12.ezyfoxserver.exception.EzyLoginErrorException; +import com.tvd12.ezyfoxserver.function.EzyVoid; +import com.tvd12.ezyfoxserver.response.EzyLoginResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.setting.EzyUserManagementSetting; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; + +public class EzyLoginProcessor + extends EzyEntityBuilders + implements EzyVoid { + + protected EzyUserLoginEvent event; + protected EzyServerContext context; + protected EzyServerUserManager userManager; + protected boolean alreadyLoggedIn; + protected boolean allowGuestLogin; + protected String guestNamePrefix; + protected String userNamePattern; + + @Override + public void apply() { + EzyProcessor.processWithLock(this::process, getLock()); + } + + protected void process() { + checkUsername(); + EzyUser user = getUser(); + checkMaximumSessions(user); + EzySession session = getSession(); + updateSession(session); + mapUserSession(user, session); + user.addSession(session); + notifyLoggedIn(user, session); + fireUserAddedEvent(user); + response(user, newLoginReponse(user)); + fireSessionLoginEvent(user); + } + + protected void checkUsername() { + if(!getUsername().matches(userNamePattern)) + throw new EzyLoginErrorException(EzyLoginError.INVALID_USERNAME); + } + + protected void checkMaximumSessions(EzyUser user) { + if(user.getSessionCount() >= getMaxSession()) + throw new EzyLoginErrorException(EzyLoginError.MAXIMUM_SESSION); + } + + protected void mapUserSession(EzyUser user, EzySession session) { + if(alreadyLoggedIn) + userManager.bind(session, user); + else + userManager.addUser(session, user); + } + + protected EzyUser getUser() { + return alreadyLoggedIn ? userManager.getUser(getUsername()) : newUser(); + } + + protected void updateSession(EzySession session) { + session.setLoggedIn(true); + session.setLoggedInTime(System.currentTimeMillis()); + } + + protected void notifyLoggedIn(EzyUser user, EzySession session) { + EzyHasSessionDelegate hasDelegate = (EzyHasSessionDelegate)getSession(); + hasDelegate.getDelegate().onSessionLoggedIn(user); + } + + protected void fireSessionLoginEvent(EzyUser user) { + if(alreadyLoggedIn) + doFireSessionLoginEvent(newSessionLoginEvent(user)); + } + + protected void doFireSessionLoginEvent(EzyEvent event) { + context.get(EzyFireAppEvent.class) + .filter(appCtx -> containsUser(appCtx, getUsername())) + .fire(EzyEventType.USER_SESSION_LOGIN, event); + } + + protected void fireUserAddedEvent(EzyUser user) { + if(!alreadyLoggedIn) + doFireUserAddedEvent(newUserAddedEvent(user)); + } + + protected void doFireUserAddedEvent(EzyEvent event) { + try { + context.get(EzyFirePluginEvent.class) + .fire(EzyEventType.USER_ADDED, event); + } + catch(Exception e) { + getLogger().error("user added error", e); + } + } + + protected EzyUser newUser() { + EzySettings settings = getSettings(context); + EzyUserManagementSetting ust = settings.getUserManagement(); + EzySimpleUser user = new EzySimpleUser(); + user.setName(getNewUsername(user.getId(), event.getUsername())); + user.setPassword(event.getPassword()); + user.setMaxIdleTime(ust.getUserMaxIdleTime()); + user.setMaxSessions(ust.getMaxSessionPerUser()); + user.setRemoveDelegate(newUserRemoveDelegate(user)); + return user; + } + + protected String getNewUsername(long userId, String currentName) { + if(!StringUtils.isEmpty(currentName)) + return currentName; + if(allowGuestLogin) + return guestNamePrefix + userId; + throw new EzyLoginErrorException(EzyLoginError.INVALID_USERNAME); + } + + protected EzyUserRemoveDelegate newUserRemoveDelegate(EzyUser user) { + return EzySimpleUserRemoveDelegate.builder() + .context(context) + .user(user) + .build(); + } + + protected EzyEvent newSessionLoginEvent(EzyUser user) { + return EzySessionLoginEventImpl.builder() + .session(getSession()) + .user(user) + .build(); + } + + protected EzyEvent newUserAddedEvent(EzyUser user) { + return EzyUserAddedEventImpl.builder() + .user(user) + .session(getSession()) + .loginData(getLoginData()) + .build(); + } + + protected void response(EzyUser user, EzyResponse response) { + context.get(EzySendResponse.class) + .sender(user) + .response(response) + .execute(); + } + + protected EzyResponse newLoginReponse(EzyUser user) { + return EzyLoginResponse.builder() + .data(event.getOutput()) + .userId(user.getId()) + .username(user.getName()) + .joinedApps(getJoinedAppsInfo()) + .build(); + + } + + protected Lock getLock() { + return userManager.getLock(getUsername()); + } + + protected String getUsername() { + return event.getUsername(); + } + + protected EzySession getSession() { + return event.getSession(); + } + + protected EzyArray getLoginData() { + return event.getData(); + } + + protected int getMaxSession() { + return context + .getServer() + .getSettings() + .getUserManagement() + .getMaxSessionPerUser(); + } + + protected EzyArray getJoinedAppsInfo() { + EzyArrayBuilder builder = newArrayBuilder(); + forEachAppContexts(context, (appCtx) -> { + if(containsUser(appCtx, getUsername())) + builder.append(newJoinedAppInfo(appCtx)); + }); + return builder.build(); + } + + @SuppressWarnings("unchecked") + protected EzyArrayBuilder newJoinedAppInfo(EzyAppContext appCtx) { + EzyAppSetting app = appCtx.getApp().getSetting(); + return newArrayBuilder().append(app.getId(), app.getName()); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected EzyUserLoginEvent event; + protected EzyServerContext context; + + public Builder event(EzyUserLoginEvent event) { + this.event = event; + return this; + } + + public Builder context(EzyServerContext context) { + this.context = context; + return this; + } + + @Override + public EzyLoginProcessor build() { + EzyServerUserManager userManager = getUserManager(context); + EzyUserManagementSetting setting = getSettings(context).getUserManagement(); + EzyLoginProcessor answer = new EzyLoginProcessor(); + answer.event = event; + answer.context = context; + answer.userManager = userManager; + answer.allowGuestLogin = setting.isAllowGuestLogin(); + answer.guestNamePrefix = setting.getGuestNamePrefix(); + answer.userNamePattern = setting.getUserNamePattern(); + answer.alreadyLoggedIn = userManager.containsUser(event.getUsername()); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyMessageController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyMessageController.java index 749801b2..1b0398e5 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyMessageController.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyMessageController.java @@ -1,35 +1,15 @@ package com.tvd12.ezyfoxserver.controller; -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.command.EzySendResponse; import com.tvd12.ezyfoxserver.context.EzyContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.factory.EzyFactory; +import com.tvd12.ezyfoxserver.entity.EzySender; import com.tvd12.ezyfoxserver.response.EzyResponse; -import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; -import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; -public class EzyMessageController extends EzyLoggable { - - protected EzyResponseSerializer getResponseSerializer(EzyContext ctx) { - return ctx.get(EzyResponseSerializer.class); - } - - protected EzyObject serializeToObject(EzyContext ctx, EzyResponse response) { - return getResponseSerializer(ctx).serializeToObject(response); - } - - protected EzyArray serializeToArray(EzyContext ctx, EzyResponse response) { - return getResponseSerializer(ctx).serializeToArray(response); - } - - protected EzyArrayBuilder newArrayBuilder() { - return EzyFactory.create(EzyArrayBuilder.class); - } +public class EzyMessageController extends EzyEntityBuilders { - protected EzyObjectBuilder newObjectBuilder() { - return EzyFactory.create(EzyObjectBuilder.class); - } + protected void response(EzyContext ctx, EzySender sender, EzyResponse response) { + ctx.get(EzySendResponse.class).sender(sender).response(response).execute(); + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPingController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPingController.java new file mode 100644 index 00000000..675523de --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyPingController.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.controller; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.request.EzyPingRequest; +import com.tvd12.ezyfoxserver.response.EzyPongResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; + +public class EzyPingController + extends EzyAbstractServerController + implements EzyServerController { + + @Override + public void handle(EzyServerContext ctx, EzyPingRequest request) { + response(ctx, request.getSession(), newPongResponse()); + } + + protected EzyResponse newPongResponse() { + return EzyPongResponse.builder().build(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyReconnectController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyReconnectController.java new file mode 100644 index 00000000..ace82379 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyReconnectController.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.controller; + +import static com.tvd12.ezyfoxserver.context.EzyContexts.containsUser; + +import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserReconnectEventImpl; +import com.tvd12.ezyfoxserver.request.EzyReconnectRequest; +import com.tvd12.ezyfoxserver.util.EzyIfElse; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; + +public class EzyReconnectController + extends EzyAbstractServerController + implements EzyServerController{ + + @Override + public void handle(EzyServerContext ctx, EzyReconnectRequest request) { + EzySession newsession = request.getSession(); + EzySession oldsession = request.getOldSession(); + EzyServerUserManager userManager = getUserManager(ctx); + EzySessionManager sessionManager = getSessionManager(ctx); + EzyUser user = userManager.findAndUpdateUser(oldsession, newsession); + sessionManager.returnSession(oldsession, EzyDisconnectReason.ANOTHER_SESSION_LOGIN); + EzyIfElse.withIf(user != null, () -> processUser(ctx, user, newsession)); + } + + protected void processUser(EzyServerContext ctx, EzyUser user, EzySession newsession) { + ctx.get(EzyFireAppEvent.class) + .filter(appCtx -> containsUser(appCtx, user)) + .fire(EzyEventType.USER_RECONNECT, newReconnectEvent(user, newsession)); + } + + protected EzyEvent newReconnectEvent(EzyUser user, EzySession session) { + return EzyUserReconnectEventImpl.builder().user(user).session(session).build(); + } + +} 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 3e3093f9..4f45b842 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 @@ -4,32 +4,43 @@ import com.tvd12.ezyfoxserver.constant.EzyEventType; import com.tvd12.ezyfoxserver.context.EzyAppContext; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyUser; import com.tvd12.ezyfoxserver.event.EzyEvent; -import com.tvd12.ezyfoxserver.event.impl.EzyRequestAppEventImpl; +import com.tvd12.ezyfoxserver.event.impl.EzyUserRequestAppEventImpl; +import com.tvd12.ezyfoxserver.request.EzyRequestAppRequest; +import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; public class EzyRequestAppController extends EzyAbstractServerController - implements EzyServerController { + implements EzyServerController { @Override - public void handle(EzyServerContext ctx, EzyUser user, EzyArray data) { - getLogger().info("begin access app handler {}", data); - process(ctx, user, data); - getLogger().info("end access app handler"); - } - - protected void process(EzyServerContext ctx, EzyUser user, EzyArray data) { - getLogger().info("process access app, data {}", data); - EzyAppContext appCtx = ctx.getAppContext(data.get(0, int.class)); - EzyEvent event = newRequestAppEvent(user, data.get(1)); - EzyEventType type = EzyEventType.USER_REQUEST; - appCtx.get(EzyFireEvent.class).fire(type, event); + public void handle(EzyServerContext ctx, EzyRequestAppRequest request) { + EzyRequestAppParams params = request.getParams(); + EzyAppContext appCtx = ctx.getAppContext(params.getAppId()); + + // 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 + if(!userManger.containsUser(user)) + throw new IllegalStateException("user " + user.getName() + " hasn't joined app"); + + EzyEvent event = newRequestAppEvent(request); + + // redirect handling to app + appCtx.get(EzyFireEvent.class).fire(EzyEventType.USER_REQUEST, event); } - protected EzyEvent newRequestAppEvent(EzyUser user, EzyArray params) { - return EzyRequestAppEventImpl.builder().user(user).data(params).build(); + protected EzyEvent newRequestAppEvent(EzyRequestAppRequest request) { + return EzyUserRequestAppEventImpl.builder() + .user(request.getUser()) + .session(request.getSession()) + .data(request.getParams().getData()) + .build(); } } 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 new file mode 100644 index 00000000..b89f9dac --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/controller/EzyRequestPluginController.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.controller; + +import com.tvd12.ezyfoxserver.command.EzyFireEvent; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserRequestPluginEventImpl; +import com.tvd12.ezyfoxserver.request.EzyRequestPluginParams; +import com.tvd12.ezyfoxserver.request.EzyRequestPluginRequest; + +public class EzyRequestPluginController + extends EzyAbstractServerController + implements EzyServerController { + + @Override + public void handle(EzyServerContext ctx, EzyRequestPluginRequest request) { + EzyRequestPluginParams params = request.getParams(); + EzyPluginContext pluginCtx = ctx.getPluginContext(params.getPluginName()); + EzyEvent event = newRequestPluginEvent(request); + EzyEventType type = EzyEventType.USER_REQUEST; + pluginCtx.get(EzyFireEvent.class).fire(type, event); + } + + protected EzyEvent newRequestPluginEvent(EzyRequestPluginRequest request) { + return EzyUserRequestPluginEventImpl.builder() + .user(request.getUser()) + .session(request.getSession()) + .data(request.getParams().getData()) + .build(); + } + +} 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 adb6c25f..b22a73da 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 @@ -1,8 +1,7 @@ package com.tvd12.ezyfoxserver.controller; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyArray; public interface EzyServerController - 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 new file mode 100644 index 00000000..f079026e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyAbstractSessionDelegate.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.delegate; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzyAbstractSessionDelegate + extends EzyLoggable implements EzySessionDelegate { + + @Override + public void onSessionReturned(EzyConstant reason) { + } + + @Override + public void onSessionLoggedIn(EzyUser user) { + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java new file mode 100644 index 00000000..b54043d9 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionDelegate.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.delegate; + +public interface EzySessionDelegate + extends EzySessionRemoveDelegate, EzySessionLoginDelegate { + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionLoginDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionLoginDelegate.java new file mode 100644 index 00000000..c1804340 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionLoginDelegate.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.delegate; + +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzySessionLoginDelegate { + + void onSessionLoggedIn(EzyUser user); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionRemoveDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionRemoveDelegate.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionRemoveDelegate.java rename to ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySessionRemoveDelegate.java diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySimpleUserRemoveDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySimpleUserRemoveDelegate.java new file mode 100644 index 00000000..6852a9cb --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzySimpleUserRemoveDelegate.java @@ -0,0 +1,84 @@ +package com.tvd12.ezyfoxserver.delegate; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.command.EzyDisconnectUser; +import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.context.EzyContext; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserRemovedEventImpl; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@Setter +public class EzySimpleUserRemoveDelegate + extends EzyLoggable + implements EzyUserRemoveDelegate { + + protected EzyUser user; + protected EzyContext context; + + @Override + public void onUserRemoved(EzyConstant reason) { + notifyUserRemoved(reason); + disconectUser(reason); + } + + protected void notifyUserRemoved(EzyConstant reason) { + try { + context + .get(EzyFirePluginEvent.class) + .fire(EzyEventType.USER_REMOVED, newUserRemovedEvent(reason)); + } + catch(Exception e) { + getLogger().error("notify user removed error", e); + } + } + + protected EzyEvent newUserRemovedEvent(EzyConstant reason) { + return EzyUserRemovedEventImpl.builder() + .user(user) + .reason(reason) + .build(); + } + + protected void disconectUser(EzyConstant reason) { + context.get(EzyDisconnectUser.class) + .user(user) + .reason(reason) + .fireClientEvent(true) + .fireServerEvent(true) + .execute(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected EzyUser user; + protected EzyContext context; + + public Builder user(EzyUser user) { + this.user = user; + return this; + } + + public Builder context(EzyContext context) { + this.context = context; + return this; + } + + @Override + public EzyUserRemoveDelegate build() { + EzySimpleUserRemoveDelegate answer = new EzySimpleUserRemoveDelegate(); + answer.setContext(context); + answer.setUser(user); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyUserRemoveDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyUserRemoveDelegate.java new file mode 100644 index 00000000..d54bac9e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/delegate/EzyUserRemoveDelegate.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.delegate; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyUserRemoveDelegate { + + void onUserRemoved(EzyConstant reason); + +} 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 3e46d5c7..16cc3fa5 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 @@ -1,12 +1,18 @@ package com.tvd12.ezyfoxserver.entity; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.constant.EzyTransportType; import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; import com.tvd12.ezyfoxserver.sercurity.EzyMD5; +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; -import lombok.EqualsAndHashCode; +import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.ToString; @@ -14,38 +20,52 @@ @Getter @Setter @ToString(exclude = {"privateKey", "publicKey", "clientKey", "fullReconnectToken"}) -@EqualsAndHashCode(of = "id", callSuper = false) -public abstract class EzyAbstractSession extends EzyEntity implements EzySession { - - protected long id; - protected Lock lock; +public abstract class EzyAbstractSession + extends EzyEntity + implements EzySession, EzyHasSessionDelegate { + private static final long serialVersionUID = -4112736666616219904L; + + protected long id; + protected String name; + protected String clientId; protected long creationTime; - protected long lastActivityTime; protected long lastReadTime; protected long lastWriteTime; protected long readBytes; protected long writtenBytes; - protected long maxIdleTime; + protected long lastActivityTime; + protected int readRequests; + protected int writtenResponses; + protected byte[] privateKey; protected byte[] publicKey; protected byte[] clientKey; - protected boolean loggedIn; - protected boolean activated; + protected long loggedInTime; - protected long maxWaitingTime; + + protected volatile boolean loggedIn; + protected volatile boolean activated; + + protected String clientType; + protected String clientVersion; protected String reconnectToken; protected String fullReconnectToken; - protected EzySessionDelegate delegate; - - { - maxIdleTime = 3 * 60 * 1000; - maxWaitingTime = 6 * 1000; - lock = new ReentrantLock(); - } + protected EzyConnectionType connectionType; + protected long maxWaitingTime = 5 * 1000; + protected long maxIdleTime = 3 * 60 * 1000; + + protected transient EzySessionDelegate delegate; + + @Setter(AccessLevel.NONE) + protected Map locks = new ConcurrentHashMap<>(); + + protected static final String RECONNECT_TOKEN_SALT = "$1$reconnectToken"; + + @Override public void setReconnectToken(String token) { this.fullReconnectToken = token; - this.reconnectToken = EzyMD5.cryptUTF(token); + this.reconnectToken = EzyMD5.cryptUtf(token, RECONNECT_TOKEN_SALT); } @Override @@ -58,9 +78,57 @@ public void addWrittenBytes(long bytes) { this.writtenBytes += bytes; } + @Override + public void addReadRequests(int requests) { + this.readRequests += requests; + } + + @Override + public void addWrittenResponses(int responses) { + this.writtenResponses += responses; + } + @Override public void setActivated(boolean value) { this.activated = value; } + @Override + public Lock getLock(String name) { + return locks.computeIfAbsent(name, k -> new ReentrantLock()); + } + + @Override + public final void send(EzyData data, EzyTransportType type) { + if(!activated) return; + addWrittenResponses(1); + setLastWriteTime(System.currentTimeMillis()); + setLastActivityTime(System.currentTimeMillis()); + sendData(data, type); + } + + protected abstract void sendData(EzyData data, EzyTransportType type); + + @Override + public void destroy() { + this.delegate = null; + this.activated = false; + this.loggedIn = false; + this.readBytes = 0L; + this.writtenBytes = 0L; + this.properties.clear(); + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(c -> c.id) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes().append(id).toHashCode(); + } + } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasSessionDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasSessionDelegate.java new file mode 100644 index 00000000..c5b8ea3c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasSessionDelegate.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.entity; + +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; + +public interface EzyHasSessionDelegate { + + /** + * @param delegate the delegate + */ + void setDelegate(EzySessionDelegate delegate); + + /** + * @return the delegate + */ + EzySessionDelegate getDelegate(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasUserRemoveDelegate.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasUserRemoveDelegate.java new file mode 100644 index 00000000..e94944c0 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzyHasUserRemoveDelegate.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.entity; + +import com.tvd12.ezyfoxserver.delegate.EzyUserRemoveDelegate; + +public interface EzyHasUserRemoveDelegate { + + /** + * @param delegate the delegate + */ + void setRemoveDelegate(EzyUserRemoveDelegate delegate); + + /** + * @return the delegate + */ + EzyUserRemoveDelegate getRemoveDelegate(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java new file mode 100644 index 00000000..88b17802 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/entity/EzySender.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.entity; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; + +public interface EzySender { + + void send(EzyData data, EzyTransportType type); + + default void send(EzyData data) { + send(data, EzyTransportType.TCP); + } + +} 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 cade1afb..7c18464f 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 @@ -1,11 +1,14 @@ package com.tvd12.ezyfoxserver.entity; +import java.io.Serializable; import java.net.SocketAddress; import java.util.concurrent.locks.Lock; -import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyProperties; -public interface EzySession extends EzySender, EzyProperties { +public interface EzySession extends EzySender, EzyProperties, EzyDestroyable, Serializable { /** * Get session id @@ -14,6 +17,13 @@ public interface EzySession extends EzySender, EzyProperties { */ long getId(); + /** + * Get session name + * + * @return the name + */ + String getName(); + /** * Get client id * @@ -43,6 +53,42 @@ public interface EzySession extends EzySender, EzyProperties { */ void setClientKey(byte[] key); + + /** + * 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 + */ + EzyConnectionType getConnectionType(); + /** * Get session reconnect token * @@ -169,6 +215,34 @@ public interface EzySession extends EzySender, EzyProperties { */ 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); + + /** + * Get written responses + * + * @return number of written responses + */ + int getWrittenResponses(); + + /** + * add written responses + * + * @param responses number of reponses + */ + void addWrittenResponses(int responses); + /** * Get max idle time * @@ -227,19 +301,11 @@ public interface EzySession extends EzySender, EzyProperties { boolean isActivated(); /** + * + * @param name the lock name * @return the lock */ - Lock getLock(); - - /** - * @param delegate the delegate - */ - void setDelegate(EzySessionDelegate delegate); - - /** - * @return the delegate - */ - EzySessionDelegate getDelegate(); + Lock getLock(String name); /** * Get client full ip address 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 c3f5d041..4df0d9f2 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 @@ -1,39 +1,112 @@ package com.tvd12.ezyfoxserver.entity; import java.io.Serializable; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; -import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzyEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import lombok.EqualsAndHashCode; +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.delegate.EzyUserRemoveDelegate; +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; +import com.tvd12.ezyfoxserver.util.EzyNameAware; + +import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @Setter @Getter -@EqualsAndHashCode(of = "id", callSuper = false) -public class EzySimpleUser extends EzyEntity implements EzyUser, Serializable { +public class EzySimpleUser + extends EzyEntity + implements EzyUser, EzyNameAware, EzyHasUserRemoveDelegate, Serializable { private static final long serialVersionUID = -7846882289922504595L; - protected long id; - protected String name; - protected String password; - protected transient EzySession session; + protected long id = COUNTER.incrementAndGet(); + + protected String name = ""; + + protected String password = ""; + + protected int maxSessions = 30; + + protected long maxIdleTime = 3 * 60 * 1000; + + protected long startIdleTime = System.currentTimeMillis(); + + protected transient EzyUserRemoveDelegate removeDelegate; - private transient static final AtomicLong COUNTER; + @Setter(AccessLevel.NONE) + protected Map locks = new ConcurrentHashMap<>(); - static { - COUNTER = new AtomicLong(0); + @Setter(AccessLevel.NONE) + protected Map sessionMap = new ConcurrentHashMap<>(); + + @Setter(AccessLevel.NONE) + protected Logger logger = LoggerFactory.getLogger(getClass()); + + private transient static final AtomicLong COUNTER = new AtomicLong(0); + + @Override + public void addSession(EzySession session) { + sessionMap.put(session.getReconnectToken(), session); } - public EzySimpleUser() { - this.id = COUNTER.incrementAndGet(); + @Override + public void removeSession(EzySession session) { + setStartIdleTime(System.currentTimeMillis()); + sessionMap.remove(session.getReconnectToken()); + getLogger().debug("remove session {} from user {}, remain {} sessions", + session.getClientAddress(), getName(), sessionMap.size()); } @Override - public void send(EzyData data) { - session.send(data); + public Collection getSessions() { + return sessionMap.values(); } + @Override + public int getSessionCount() { + return sessionMap.size(); + } + + @Override + public Lock getLock(String name) { + return locks.computeIfAbsent(name, k -> new ReentrantLock()); + } + + @Override + public void send(EzyData data, EzyTransportType type) { + for(EzySession session : getSessions()) + session.send(data, type); + } + + @Override + public void destroy() { + this.removeDelegate = null; + this.properties.clear(); + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(c -> c.id) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes().append(id).toHashCode(); + } + + protected Logger getLogger() { + return logger; + } + } 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 d42b8683..d93aaeb5 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 @@ -1,6 +1,12 @@ package com.tvd12.ezyfoxserver.entity; -public interface EzyUser extends EzySender, EzyProperties { +import java.util.Collection; +import java.util.concurrent.locks.Lock; + +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyProperties; + +public interface EzyUser extends EzySender, EzyProperties, EzyDestroyable { /** * Get user id @@ -16,18 +22,66 @@ public interface EzyUser extends EzySender, EzyProperties { */ String getName(); + /** + * 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 + */ + int getSessionCount(); + /** * Get current session * * @return the current session */ - EzySession getSession(); + Collection getSessions(); /** - * Set current session + * Add new session * - * @param session the session to set + * @param session the session to add + */ + void addSession(EzySession session); + + /** + * remove a session + * + * @param session the session to remove + */ + void removeSession(EzySession session); + + /** + * @param name the lock name + * @return the lock */ - void setSession(EzySession session); + Lock getLock(String name); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyDisconnectEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyDisconnectEvent.java deleted file mode 100644 index 95a01b2f..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyDisconnectEvent.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.event; - -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.entity.EzyUser; - -public interface EzyDisconnectEvent extends EzyEvent { - - EzyUser getUser(); - - EzyConstant getReason(); - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyRequestAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyRequestAppEvent.java deleted file mode 100644 index 49b6c183..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyRequestAppEvent.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.event; - -import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzyUser; - -public interface EzyRequestAppEvent extends EzyEvent { - - EzyUser getUser(); - - T getData(); - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyServerReadyEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyServerReadyEvent.java index 01294511..7e901bc2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyServerReadyEvent.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyServerReadyEvent.java @@ -1,9 +1,4 @@ package com.tvd12.ezyfoxserver.event; -import com.tvd12.ezyfoxserver.EzyServer; - public interface EzyServerReadyEvent extends EzyEvent { - - EzyServer getServer(); - } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionEvent.java new file mode 100644 index 00000000..8b2c31a3 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzySession; + +public interface EzySessionEvent extends EzyEvent { + + EzySession getSession(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionLoginEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionLoginEvent.java new file mode 100644 index 00000000..e08c812b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionLoginEvent.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.event; + +public interface EzySessionLoginEvent extends EzyUserSessionEvent { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionRemovedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionRemovedEvent.java new file mode 100644 index 00000000..395e81e4 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzySessionRemovedEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzySessionRemovedEvent extends EzyUserSessionEvent { + + EzyConstant getReason(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAccessAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAccessAppEvent.java new file mode 100644 index 00000000..1993536a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAccessAppEvent.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzyData; + +public interface EzyUserAccessAppEvent extends EzyUserEvent { + + EzyData getOutput(); + + void setOutput(EzyData output); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAddedEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAddedEvent.java new file mode 100644 index 00000000..876ba14d --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserAddedEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyUserAddedEvent extends EzyUserSessionEvent { + + EzyArray getLoginData(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserDisconnectEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserDisconnectEvent.java new file mode 100644 index 00000000..4cf3700b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserDisconnectEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyUserDisconnectEvent extends EzyUserEvent { + + EzyConstant getReason(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserEvent.java new file mode 100644 index 00000000..9cb8b8d0 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzyUserEvent extends EzyEvent { + + EzyUser getUser(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserJoinedAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserJoinedAppEvent.java new file mode 100644 index 00000000..ba6ac033 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserJoinedAppEvent.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.event; + +public interface EzyUserJoinedAppEvent extends EzyUserSessionEvent { +} 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 f951eeae..5aab0a7e 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 @@ -1,20 +1,19 @@ package com.tvd12.ezyfoxserver.event; -import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; -public interface EzyUserLoginEvent extends EzyEvent { +public interface EzyUserLoginEvent extends EzySessionEvent { - Object getOutput(); + EzyData getOutput(); String getUsername(); String getPassword(); - EzySession getSession(); - - T getData(); + EzyArray getData(); - void setOutput(Object output); + void setOutput(EzyData output); void setUsername(String username); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserReconnectEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserReconnectEvent.java new file mode 100644 index 00000000..436b2fc1 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserReconnectEvent.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.event; + +public interface EzyUserReconnectEvent extends EzyUserEvent { +} 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 new file mode 100644 index 00000000..11d7d451 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRemovedEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyUserRemovedEvent extends EzyUserEvent { + + EzyConstant getReason(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestAppEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestAppEvent.java new file mode 100644 index 00000000..fa85a818 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestAppEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyUserRequestAppEvent extends EzyUserSessionEvent { + + EzyArray getData(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestPluginEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestPluginEvent.java new file mode 100644 index 00000000..1bb62813 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserRequestPluginEvent.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.event; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyUserRequestPluginEvent extends EzyUserSessionEvent { + + EzyArray getData(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserSessionEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserSessionEvent.java new file mode 100644 index 00000000..bd90ce88 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/EzyUserSessionEvent.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.event; + +public interface EzyUserSessionEvent extends EzyUserEvent, EzySessionEvent { + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyAbstractEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyAbstractEvent.java deleted file mode 100644 index 8cdfc3ed..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyAbstractEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.tvd12.ezyfoxserver.event.impl; - -import com.tvd12.ezyfoxserver.event.EzyEvent; - -public abstract class EzyAbstractEvent { - - protected EzyAbstractEvent(Builder builder) { - } - - public abstract static class Builder> { - public abstract EzyEvent build(); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyDisconnectEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyDisconnectEventImpl.java deleted file mode 100644 index 9bfa545f..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyDisconnectEventImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.tvd12.ezyfoxserver.event.impl; - -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.entity.EzyUser; -import com.tvd12.ezyfoxserver.event.EzyDisconnectEvent; - -import lombok.Getter; - -public class EzyDisconnectEventImpl - extends EzyAbstractEvent - implements EzyDisconnectEvent { - - @Getter - private EzyUser user; - @Getter - private EzyConstant reason; - - protected EzyDisconnectEventImpl(Builder builder) { - super(builder); - this.user = builder.user; - this.reason = builder.reason; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyAbstractEvent.Builder { - private EzyUser user; - private EzyConstant reason; - - public Builder user(EzyUser user) { - this.user = user; - return this; - } - - public Builder reason(EzyConstant reason) { - this.reason = reason; - return this; - } - - @Override - public EzyDisconnectEvent build() { - return new EzyDisconnectEventImpl(this); - } - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyRequestAppEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyRequestAppEventImpl.java deleted file mode 100644 index eecb821e..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyRequestAppEventImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.tvd12.ezyfoxserver.event.impl; - -import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzyUser; -import com.tvd12.ezyfoxserver.event.EzyEvent; -import com.tvd12.ezyfoxserver.event.EzyRequestAppEvent; - -import lombok.Getter; - -public class EzyRequestAppEventImpl - extends EzyAbstractEvent - implements EzyRequestAppEvent { - - @Getter - private EzyUser user; - @Getter - private EzyData data; - - protected EzyRequestAppEventImpl(Builder builder) { - super(builder); - this.user = builder.user; - this.data = builder.data; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyAbstractEvent.Builder { - private EzyUser user; - private EzyData data; - - public Builder user(EzyUser user) { - this.user = user; - return this; - } - - public Builder data(EzyData data) { - this.data = data; - return this; - } - - @Override - public EzyEvent build() { - return new EzyRequestAppEventImpl(this); - } - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyServerReadyEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyServerReadyEventImpl.java index 2bccfbd1..791aabe8 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyServerReadyEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyServerReadyEventImpl.java @@ -1,38 +1,25 @@ package com.tvd12.ezyfoxserver.event.impl; -import com.tvd12.ezyfoxserver.EzyServer; -import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.event.EzyServerReadyEvent; import lombok.Getter; +import lombok.Setter; -public class EzyServerReadyEventImpl - extends EzyAbstractEvent - implements EzyServerReadyEvent { - - @Getter - private EzyServer server; - - protected EzyServerReadyEventImpl(Builder builder) { - super(builder); - this.server = builder.server; - } +@Getter +@Setter +public class EzyServerReadyEventImpl implements EzyServerReadyEvent { public static Builder builder() { return new Builder(); } - public static class Builder extends EzyAbstractEvent.Builder { - private EzyServer server; - - public Builder server(EzyServer server) { - this.server = server; - return this; - } + public static class Builder implements EzyBuilder { @Override - public EzyEvent build() { - return new EzyServerReadyEventImpl(this); + public EzyServerReadyEvent build() { + EzyServerReadyEventImpl answer = new EzyServerReadyEventImpl(); + return answer; } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionLoginEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionLoginEventImpl.java new file mode 100644 index 00000000..995582bf --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionLoginEventImpl.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.event.EzySessionLoginEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySessionLoginEventImpl + extends EzySimpleUserSessionEvent + implements EzySessionLoginEvent { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + + @Override + protected EzySessionLoginEventImpl newProduct() { + return new EzySessionLoginEventImpl(); + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionRemovedEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionRemovedEventImpl.java new file mode 100644 index 00000000..0a054b33 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySessionRemovedEventImpl.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.event.EzySessionRemovedEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySessionRemovedEventImpl + extends EzySimpleUserSessionEvent + implements EzySessionRemovedEvent { + + protected EzyConstant reason; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + + protected EzyConstant reason; + + public Builder reason(EzyConstant reason) { + this.reason = reason; + return this; + } + + @Override + protected EzySessionRemovedEventImpl newProduct() { + EzySessionRemovedEventImpl answer = new EzySessionRemovedEventImpl(); + answer.setReason(reason); + return answer; + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleSessionEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleSessionEvent.java new file mode 100644 index 00000000..dcc5a399 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleSessionEvent.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.EzySessionEvent; + +import lombok.Getter; + +@Getter +public class EzySimpleSessionEvent implements EzySessionEvent { + + protected EzySession session; + + public static class Builder> implements EzyBuilder { + + protected EzySession session; + + @SuppressWarnings("unchecked") + public B session(EzySession session) { + this.session = session; + return (B)this; + } + + @Override + public EzyEvent build() { + EzySimpleSessionEvent answer = newProduct(); + answer.session = session; + return answer; + } + + protected EzySimpleSessionEvent newProduct() { + return new EzySimpleSessionEvent(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserEvent.java new file mode 100644 index 00000000..e4617883 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserEvent.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.EzyUserEvent; + +import lombok.Getter; + +@Getter +public class EzySimpleUserEvent implements EzyUserEvent { + + protected EzyUser user; + + public static class Builder> implements EzyBuilder { + + protected EzyUser user; + + @SuppressWarnings("unchecked") + public B user(EzyUser user) { + this.user = user; + return (B)this; + } + + @Override + public EzyEvent build() { + EzySimpleUserEvent answer = newProduct(); + answer.user = user; + return answer; + } + + protected EzySimpleUserEvent newProduct() { + return new EzySimpleUserEvent(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserSessionEvent.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserSessionEvent.java new file mode 100644 index 00000000..a7b69173 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzySimpleUserSessionEvent.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.EzyUserSessionEvent; + +import lombok.Getter; + +@Getter +public class EzySimpleUserSessionEvent implements EzyUserSessionEvent { + + protected EzyUser user; + protected EzySession session; + + public static class Builder> implements EzyBuilder { + + protected EzyUser user; + protected EzySession session; + + @SuppressWarnings("unchecked") + public B user(EzyUser user) { + this.user = user; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B session(EzySession session) { + this.session = session; + return (B)this; + } + + @Override + public EzyEvent build() { + EzySimpleUserSessionEvent answer = newProduct(); + answer.user = user; + answer.session = session; + return answer; + } + + protected EzySimpleUserSessionEvent newProduct() { + return new EzySimpleUserSessionEvent(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAccessAppEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAccessAppEventImpl.java new file mode 100644 index 00000000..c566ef4e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAccessAppEventImpl.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.event.EzyUserAccessAppEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserAccessAppEventImpl + extends EzySimpleUserEvent + implements EzyUserAccessAppEvent { + + protected EzyData output; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserEvent.Builder { + + @Override + public EzyUserAccessAppEvent build() { + return (EzyUserAccessAppEvent)super.build(); + } + + @Override + protected EzyUserAccessAppEventImpl newProduct() { + return new EzyUserAccessAppEventImpl(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAddedEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAddedEventImpl.java new file mode 100644 index 00000000..98612925 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserAddedEventImpl.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.event.EzyUserAddedEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserAddedEventImpl + extends EzySimpleUserSessionEvent + implements EzyUserAddedEvent { + + protected EzyArray loginData; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + + protected EzyArray loginData; + + public Builder loginData(EzyArray data) { + this.loginData = data; + return this; + } + + @Override + protected EzyUserAddedEventImpl newProduct() { + EzyUserAddedEventImpl answer = new EzyUserAddedEventImpl(); + answer.setLoginData(loginData); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserDisconnectEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserDisconnectEventImpl.java new file mode 100644 index 00000000..c97ce0a9 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserDisconnectEventImpl.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.event.EzyUserDisconnectEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserDisconnectEventImpl + extends EzySimpleUserEvent + implements EzyUserDisconnectEvent { + + protected EzyConstant reason; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserEvent.Builder { + protected EzyConstant reason; + + public Builder reason(EzyConstant reason) { + this.reason = reason; + return this; + } + + @Override + public EzyUserDisconnectEventImpl newProduct() { + EzyUserDisconnectEventImpl answer = new EzyUserDisconnectEventImpl(); + answer.setReason(reason); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserJoinedAppEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserJoinedAppEventImpl.java new file mode 100644 index 00000000..5c069fdf --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserJoinedAppEventImpl.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.event.EzyUserJoinedAppEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserJoinedAppEventImpl + extends EzySimpleUserSessionEvent + implements EzyUserJoinedAppEvent { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + + @Override + protected EzyUserJoinedAppEventImpl newProduct() { + return new EzyUserJoinedAppEventImpl(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserLoginEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserLoginEventImpl.java index a5d21176..2180be3c 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserLoginEventImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserLoginEventImpl.java @@ -1,55 +1,37 @@ package com.tvd12.ezyfoxserver.event.impl; -import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; import com.tvd12.ezyfoxserver.event.EzyUserLoginEvent; import lombok.Getter; import lombok.Setter; -public class EzyUserLoginEventImpl - extends EzyAbstractEvent - implements EzyUserLoginEvent { +@Setter +@Getter +public class EzyUserLoginEventImpl extends EzySimpleSessionEvent implements EzyUserLoginEvent { - @Getter - private Object data; - @Getter - @Setter - private String username; - @Setter - @Getter - private String password; - @Setter - @Getter - private Object output; - @Getter - private EzySession session; - - protected EzyUserLoginEventImpl(Builder builder) { - super(builder); - this.data = builder.data; - this.output = builder.output; - this.session = builder.session; - this.username = builder.username; - this.password = builder.password; - } + protected EzyArray data; + protected String username; + protected String password; + protected EzyData output; public static Builder builder() { return new Builder(); } - public static class Builder extends EzyAbstractEvent.Builder { - private Object data; - private Object output; - private String username; - private String password; - private EzySession session; + public static class Builder extends EzySimpleSessionEvent.Builder { + protected EzyArray data; + protected EzyData output; + protected String username; + protected String password; - public Builder data(Object data) { + public Builder data(EzyArray data) { this.data = data; return this; } - public Builder output(Object output) { + public Builder output(EzyData output) { this.output = output; return this; } @@ -64,14 +46,19 @@ public Builder password(String password) { return this; } - public Builder session(EzySession session) { - this.session = session; - return this; + @Override + public EzyUserLoginEvent build() { + return (EzyUserLoginEvent)super.build(); } @Override - public EzyUserLoginEvent build() { - return new EzyUserLoginEventImpl(this); + protected EzyUserLoginEventImpl newProduct() { + EzyUserLoginEventImpl answer = new EzyUserLoginEventImpl(); + answer.setData(data); + answer.setOutput(output); + answer.setUsername(username); + answer.setPassword(password); + return answer; } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserReconnectEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserReconnectEventImpl.java new file mode 100644 index 00000000..641343d2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserReconnectEventImpl.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.event.EzyUserReconnectEvent; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzyUserReconnectEventImpl + extends EzySimpleUserSessionEvent + implements EzyUserReconnectEvent { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + + @Override + protected EzyUserReconnectEventImpl newProduct() { + return new EzyUserReconnectEventImpl(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRemovedEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRemovedEventImpl.java new file mode 100644 index 00000000..c3b9cda4 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRemovedEventImpl.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.event.EzyUserRemovedEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserRemovedEventImpl + extends EzySimpleUserEvent + implements EzyUserRemovedEvent { + + protected EzyConstant reason; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserEvent.Builder { + protected EzyConstant reason; + + public Builder reason(EzyConstant reason) { + this.reason = reason; + return this; + } + + @Override + protected EzyUserRemovedEventImpl newProduct() { + EzyUserRemovedEventImpl answer = new EzyUserRemovedEventImpl(); + answer.setReason(reason); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestAppEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestAppEventImpl.java new file mode 100644 index 00000000..9ee01f14 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestAppEventImpl.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserRequestAppEventImpl + extends EzySimpleUserSessionEvent + implements EzyUserRequestAppEvent { + + protected EzyArray data; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + protected EzyArray data; + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + @Override + protected EzyUserRequestAppEventImpl newProduct() { + EzyUserRequestAppEventImpl answer = new EzyUserRequestAppEventImpl(); + answer.setData(data); + return answer; + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestPluginEventImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestPluginEventImpl.java new file mode 100644 index 00000000..b2e008b2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/event/impl/EzyUserRequestPluginEventImpl.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.event.impl; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.event.EzyUserRequestPluginEvent; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzyUserRequestPluginEventImpl + extends EzySimpleUserSessionEvent + implements EzyUserRequestPluginEvent { + + protected EzyArray data; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleUserSessionEvent.Builder { + protected EzyArray data; + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + @Override + protected EzyUserRequestPluginEventImpl newProduct() { + EzyUserRequestPluginEventImpl answer = new EzyUserRequestPluginEventImpl(); + answer.setData(data); + return answer; + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyLoginErrorException.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyLoginErrorException.java new file mode 100644 index 00000000..4ee6aee5 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyLoginErrorException.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.exception; + +import com.tvd12.ezyfoxserver.constant.EzyILoginError; +import com.tvd12.ezyfoxserver.constant.EzyLoginError; + +import lombok.Getter; + +public class EzyLoginErrorException extends IllegalStateException { + private static final long serialVersionUID = 1432595688787320396L; + + @Getter + private final EzyILoginError error; + + public EzyLoginErrorException() { + this(EzyLoginError.ALREADY_LOGIN); + } + + public EzyLoginErrorException(EzyILoginError error) { + super(error.getMessage()); + this.error = error; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyReadingXmlException.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyReadingXmlException.java deleted file mode 100644 index f051b432..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/exception/EzyReadingXmlException.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.tvd12.ezyfoxserver.exception; - -public class EzyReadingXmlException extends IllegalStateException { - private static final long serialVersionUID = 3571161488931185555L; - - public EzyReadingXmlException() { - } - - public EzyReadingXmlException(final String msg) { - super(msg); - } - - public EzyReadingXmlException(final Throwable e) { - super(e); - } - - public EzyReadingXmlException(final String msg, final Throwable e) { - super(msg, e); - } - -} 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 d9a75f71..e29309b9 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 @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.ext; -import com.tvd12.ezyfoxserver.entity.EzyProperties; +import com.tvd12.ezyfoxserver.util.EzyProperties; public interface EzyAppEntryLoader extends EzyProperties { diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyEntry.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyEntry.java index b222f7ca..7a25b160 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyEntry.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ext/EzyEntry.java @@ -3,14 +3,12 @@ */ package com.tvd12.ezyfoxserver.ext; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyStartable; /** * @author tavandung12 * */ -public interface EzyEntry extends EzyDestroyable { - - void start() throws Exception; - +public interface EzyEntry extends EzyStartable, EzyDestroyable { } 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 6120761c..e1c96fc0 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 @@ -1,7 +1,7 @@ package com.tvd12.ezyfoxserver.ext; import com.tvd12.ezyfoxserver.context.EzyPluginContext; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; public interface EzyPluginEntry extends EzyEntry, EzyDestroyable { 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 5822edcf..196926db 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 @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.ext; -import com.tvd12.ezyfoxserver.entity.EzyProperties; +import com.tvd12.ezyfoxserver.util.EzyProperties; public interface EzyPluginEntryLoader extends EzyProperties { 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 a6965ff7..ee11e6ac 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 @@ -11,7 +11,7 @@ public abstract class EzyAbstractSessionFactory private final AtomicInteger counter = new AtomicInteger(0); @Override - public S newProduct() { + public final S newProduct() { S session = newSession(); initSession((EzyAbstractSession)session); return session; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyAbstractDataHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyAbstractDataHandler.java new file mode 100644 index 00000000..d19fb96c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyAbstractDataHandler.java @@ -0,0 +1,123 @@ +package com.tvd12.ezyfoxserver.handler; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.command.EzySendResponse; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyIError; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.response.EzyErrorResponse; +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting.EzyMaxRequestPerSecond; + +public class EzyAbstractDataHandler + extends EzyLoggable + implements EzyDestroyable { + + protected S session; + protected EzyUser user; + protected EzyServerContext context; + protected EzyServerControllers controllers; + protected EzyServerUserManager userManager; + protected EzyRequestMappers requestMappers; + protected EzySessionManager sessionManager; + protected Lock lock = new ReentrantLock(); + + protected EzyConstant disconnectReason; + + protected EzySettings settings; + protected Set unloggableCommands; + protected EzySessionManagementSetting sessionManagementSetting; + + //===== for measure max request per second ===== + protected EzyMaxRequestPerSecond maxRequestPerSecond; + protected long milestoneRequestTime = System.currentTimeMillis(); + protected AtomicInteger requestInSecondCount = new AtomicInteger(0); + //===== ===== + + protected volatile boolean active = false; + + protected EzyAppContext getAppContext(int appId) { + return context.getAppContext(appId); + } + + public void setContext(EzyServerContext ctx) { + this.context = ctx; + this.userManager = getUserManager(); + this.sessionManager = getSessionManager(); + this.controllers = getServer().getControllers(); + this.requestMappers = getServer().getRequestMappers(); + + this.settings = getServer().getSettings(); + this.sessionManagementSetting = settings.getSessionManagement(); + this.unloggableCommands = settings.getLogger().getIgnoredCommands().getCommands(); + this.maxRequestPerSecond = sessionManagementSetting.getSessionMaxRequestPerSecond(); + } + + protected void setActive(boolean value) { + this.active = value; + } + + protected void setDisconnectReason(EzyConstant reason) { + this.disconnectReason = reason; + } + + protected Object mapRequestParams(EzyConstant cmd, EzyData data) { + return requestMappers.toObject(cmd, data); + } + + protected EzyServer getServer() { + return context.getServer(); + } + + protected EzyManagers getManagers() { + return getServer().getManagers(); + } + + @SuppressWarnings("unchecked") + protected EzySessionManager getSessionManager() { + return getManagers().getManager(EzySessionManager.class); + } + + protected EzyServerUserManager getUserManager() { + return getManagers().getManager(EzyServerUserManager.class); + } + + protected void response(EzyResponse response) { + if(context != null) + context.get(EzySendResponse.class).sender(session).response(response).execute(); + } + + protected void responseError(EzyIError error) { + response(EzyErrorResponse.builder().error(error).build()); + } + + @Override + public void destroy() { + this.user = null; + this.session = null; + this.context = null; + this.controllers = null; + this.userManager = null; + this.requestMappers = null; + this.sessionManager = null; + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyRequestFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyRequestFactory.java new file mode 100644 index 00000000..44d96b1b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyRequestFactory.java @@ -0,0 +1,90 @@ +package com.tvd12.ezyfoxserver.handler; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleAccessAppRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleLoginRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimplePingRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestPluginRequest; + +public class EzyRequestFactory { + + protected Supplier sessionSupplier; + + @SuppressWarnings("rawtypes") + protected Map> suppliers; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public Object newRequest(EzyConstant cmd, Object params) { + EzySimpleRequest.Builder builder = suppliers.get(cmd).get(); + EzySession session = sessionSupplier.get(); + return builder.params(params).session(session).build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + implements EzyBuilder { + + protected Supplier userSupplier; + protected Supplier sessionSupplier; + + public Builder userSupplier(Supplier userSupplier) { + this.userSupplier = userSupplier; + return this; + } + + public Builder sessionSupplier(Supplier sessionSupplier) { + this.sessionSupplier = sessionSupplier; + return this; + } + + @Override + public EzyRequestFactory build() { + EzyRequestFactory answer = new EzyRequestFactory(); + answer.sessionSupplier = sessionSupplier; + answer.suppliers = newSuppliers(); + return answer; + } + + protected EzyUser getUser() { + return userSupplier.get(); + } + + @SuppressWarnings("rawtypes") + protected Map> newSuppliers() { + Map> answer = new ConcurrentHashMap<>(); + answer.put(EzyCommand.PING, () -> + EzySimplePingRequest.builder() + ); + answer.put(EzyCommand.HANDSHAKE, () -> + EzySimpleHandShakeRequest.builder() + ); + answer.put(EzyCommand.LOGIN, ()-> + EzySimpleLoginRequest.builder() + ); + answer.put(EzyCommand.APP_ACCESS, () -> + EzySimpleAccessAppRequest.builder().user(getUser()) + ); + answer.put(EzyCommand.APP_REQUEST, () -> + EzySimpleRequestAppRequest.builder().user(getUser()) + ); + answer.put(EzyCommand.PLUGIN_REQUEST, () -> + EzySimpleRequestPluginRequest.builder().user(getUser()) + ); + return answer; + } + } +} \ No newline at end of file diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionDataHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionDataHandler.java new file mode 100644 index 00000000..b3ffd3d8 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionDataHandler.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.handler; + +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzyHasSessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public abstract class EzySessionDataHandler + extends EzyAbstractDataHandler + implements EzySessionDelegate { + + protected void borrowSession(Supplier sessionSupplier) { + doBorrowSession(sessionSupplier); + updateSession(); + } + + protected void doBorrowSession(Supplier sessionSupplier) { + session = sessionSupplier.get(); + } + + protected void updateSession() { + session.setMaxIdleTime(sessionManagementSetting.getSessionMaxIdleTime()); + session.setMaxWaitingTime(sessionManagementSetting.getSessionMaxWaitingTime()); + ((EzyHasSessionDelegate)session).setDelegate(this); + } + + @Override + public void onSessionLoggedIn(EzyUser user) { + this.user = user; + this.sessionManager.addLoggedInSession(session); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleDataHandler.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleDataHandler.java new file mode 100644 index 00000000..6406eda8 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzySimpleDataHandler.java @@ -0,0 +1,208 @@ +package com.tvd12.ezyfoxserver.handler; + +import static com.tvd12.ezyfoxserver.constant.EzyMaxRequestPerSecondAction.DISCONNECT_SESSION; +import static com.tvd12.ezyfoxserver.context.EzyContexts.containsUser; + +import com.tvd12.ezyfoxserver.command.EzyFireAppEvent; +import com.tvd12.ezyfoxserver.command.EzyFirePluginEvent; +import com.tvd12.ezyfoxserver.command.EzyRunWorker; +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.constant.EzyError; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.constant.EzySessionRemoveReason; +import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzySessionRemovedEventImpl; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.exception.EzyRequestHandleException; +import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; +import static com.tvd12.ezyfoxserver.constant.EzyCommand.*; + +public abstract class EzySimpleDataHandler + extends EzyUserDataHandler { + + public void sessionActive() { + active = true; + getLogger().debug("active session: {}, reconnectToken: {}", + session.getClientAddress(), session.getReconnectToken()); + } + + public void channelInactive() throws Exception { + if(disconnectReason == null) + sessionManager.returnSession(session, EzyDisconnectReason.UNKNOWN); + } + + public void channelInactive(EzyDisconnectReason reason) throws Exception { + sessionManager.returnSession(session, reason); + } + + public void dataReceived(EzyArray msg) throws Exception { + int cmdId = msg.get(0, int.class); + EzyConstant cmd = EzyCommand.valueOf(cmdId); + if(!validateState()) return; + if(!validateSession()) return; + if(cmd != PING && checkMaxRequestPerSecond()) return; + handleReceivedData(cmd, msg); + } + + protected boolean validateState() { + return active; + } + + protected boolean validateSession() { + return session != null && session.isActivated(); + } + + protected boolean checkMaxRequestPerSecond() { + long current = System.currentTimeMillis(); + long offset = current - milestoneRequestTime; + int count = requestInSecondCount.incrementAndGet(); + int max = maxRequestPerSecond.getValue(); + if(offset > 1000) { + requestInSecondCount.set(0); + milestoneRequestTime = current; + } + else if(count > max) { + setActive(false); + processMaxRequestPerSecond(count, max); + return true; + } + return false; + } + + protected void processMaxRequestPerSecond(int nrequests, int max) { + responseError(EzyError.MAX_REQUEST_PER_SECOND); + if(maxRequestPerSecond.getAction() == DISCONNECT_SESSION) { + if(sessionManager != null) { + sessionManager.returnSession(session, EzySessionRemoveReason.MAX_REQUEST_PER_SECOND); + } + } + } + + protected void handleReceivedData(EzyConstant cmd, EzyArray msg) throws Exception { + EzyArray data = msg.get(1, EzyArray.class); + debugLogReceivedData(cmd, data); + session.addReadRequests(1); + session.setLastReadTime(System.currentTimeMillis()); + session.setLastActivityTime(System.currentTimeMillis()); + handleRequest(cmd, data); + } + + protected void debugLogReceivedData(EzyConstant cmd, EzyArray data) { + if(!unloggableCommands.contains(cmd)) + getLogger().debug("command {}, data {}", cmd, data); + } + + protected void handleRequest(EzyConstant cmd, EzyArray data) { + context.get(EzyRunWorker.class).run(() -> + doHandleRequest(cmd, data) + ); + } + + protected void doHandleRequest(EzyConstant cmd, EzyArray data) { + try { + tryHandleRequest(cmd, data); + } + catch(Exception e) { + throw new EzyRequestHandleException(newHandleRequestErrorMessage(cmd, data), e); + } + } + + protected void tryHandleRequest(EzyConstant cmd, EzyArray data) throws Exception { + Object requestParams = mapRequestParams(cmd, data); + Object request = newRequest(cmd, requestParams); + interceptRequest(controllers.getInterceptor(cmd), request); + handleRequest(controllers.getController(cmd), request); + } + + @SuppressWarnings("rawtypes") + protected void interceptRequest( + EzyInterceptor interceptor, Object request) throws Exception { + interceptServerRequest(interceptor, request); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected void interceptServerRequest( + EzyInterceptor interceptor, Object request) throws Exception { + interceptor.intercept(context, request); + } + + @SuppressWarnings("rawtypes") + protected void handleRequest(EzyController controller, Object request) { + handleServerRequest(controller, request); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected void handleServerRequest(EzyController controller, Object request) { + controller.handle(context, request); + } + + protected void exceptionCaught(Throwable cause) throws Exception { + if(cause instanceof EzyMaxRequestSizeException) + exceptionCaught((EzyMaxRequestSizeException)cause); + } + + private void exceptionCaught(EzyMaxRequestSizeException cause) throws Exception { + if(sessionManager != null) + sessionManager.returnSession(session, EzySessionRemoveReason.MAX_REQUEST_SIZE); + } + + @Override + public void onSessionReturned(EzyConstant reason) { + notifySessionRemoved(reason); + setDisconnectReason(reason); + chechToUnmapUser(); + disconnectSession(reason); + destroy(); + } + + protected void notifySessionRemoved(EzyConstant reason) { + if(context == null) return; + EzyEvent event = newSessionRemovedEvent(reason); + if(user != null) + notifyAppsSessionRemoved(event); + notifyPluginsSessionRemoved(event); + } + + protected void notifyAppsSessionRemoved(EzyEvent event) { + try { + context.get(EzyFireAppEvent.class) + .filter(appCtxt -> containsUser(appCtxt, user)) + .fire(EzyEventType.SESSION_REMOVED, event); + } + catch(Exception e) { + getLogger().error("notify session removed to apps error", e); + } + } + + protected void notifyPluginsSessionRemoved(EzyEvent event) { + try { + context.get(EzyFirePluginEvent.class) + .fire(EzyEventType.SESSION_REMOVED, event); + } + catch(Exception e) { + getLogger().error("notify session removed to apps error", e); + } + } + + protected void disconnectSession(EzyConstant reason) { + newDisconnectSession(reason).execute(); + } + + protected EzyEvent newSessionRemovedEvent(EzyConstant reason) { + return EzySessionRemovedEventImpl.builder() + .user(user) + .session(session) + .reason(reason) + .build(); + } + + protected String newHandleRequestErrorMessage(EzyConstant cmd, EzyData data) { + return "error when handle request command: " + cmd + ", data: " + data; + } +} 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 new file mode 100644 index 00000000..2b2be264 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserDataHandler.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.handler; + +import com.tvd12.ezyfoxserver.command.EzyDisconnectSession; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.util.EzyIfElse; + +public abstract class EzyUserDataHandler + extends EzySessionDataHandler { + + private EzyRequestFactory requestFactory = newRequestFactory(); + + protected void unmapUser() { + userManager.unmapSessionUser(session); + user.removeSession(session); + } + + protected void chechToUnmapUser() { + EzyIfElse.withIf(user != null, this::unmapUser); + } + + protected Object newRequest(EzyConstant cmd, Object params) { + return requestFactory.newRequest(cmd, params); + } + + protected EzyDisconnectSession newDisconnectSession(EzyConstant reason) { + return context.get(EzyDisconnectSession.class) + .reason(reason) + .session(session); + } + + private EzyRequestFactory newRequestFactory() { + return EzyRequestFactory.builder() + .userSupplier(() -> user) + .sessionSupplier(() -> session) + .build(); + } + +} \ 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 684096be..9bd776f5 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 @@ -2,8 +2,8 @@ import com.tvd12.ezyfoxserver.util.EzyLoggable; -public abstract class EzyAbstractServerInterceptor +public abstract class EzyAbstractServerInterceptor extends EzyLoggable - implements EzyServerInterceptor { + 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 f0c0e391..078c28b7 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 @@ -5,11 +5,11 @@ * @author tavandung12 * */ -public interface EzyInterceptor { +public interface EzyInterceptor { @SuppressWarnings("rawtypes") - EzyInterceptor EMPTY = (ctx, rev, data) -> {}; + EzyInterceptor ALWAYS_PASS = (ctx, request) -> {}; - void intercept(C ctx, Object rev, D data) throws Exception; + void intercept(C ctx, R request) throws Exception; } \ No newline at end of file diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerInterceptor.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerInterceptor.java index 1d1ce7ba..3bc7cb29 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerInterceptor.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/interceptor/EzyServerInterceptor.java @@ -2,6 +2,6 @@ import com.tvd12.ezyfoxserver.context.EzyServerContext; -public interface EzyServerInterceptor extends EzyInterceptor { +public interface EzyServerInterceptor extends EzyInterceptor { } 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 bbf32c71..19e13341 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 @@ -1,16 +1,16 @@ package com.tvd12.ezyfoxserver.interceptor; import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyUser; import com.tvd12.ezyfoxserver.exception.NotAuthorizedException; +import com.tvd12.ezyfoxserver.request.EzyUserRequest; -public class EzyServerUserInterceptor extends EzyAbstractServerInterceptor { +@SuppressWarnings("rawtypes") +public class EzyServerUserInterceptor extends EzyAbstractServerInterceptor { @Override - public void intercept(EzyServerContext ctx, Object rev, D data) throws Exception { - getLogger().debug("intercept user request"); - if(!(rev instanceof EzyUser)) - throw new NotAuthorizedException(rev + " is not an user"); + public void intercept(EzyServerContext ctx, EzyUserRequest request) throws Exception { + if(request.getUser() == null) + throw new NotAuthorizedException("user has not logged in"); } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/EzyConfigLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/EzyConfigLoader.java deleted file mode 100644 index 26351137..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/EzyConfigLoader.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.tvd12.ezyfoxserver.loader; - -import com.tvd12.ezyfoxserver.config.EzyConfig; - -public interface EzyConfigLoader { - - EzyConfig load(); - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/impl/EzyConfigLoaderImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/impl/EzyConfigLoaderImpl.java deleted file mode 100644 index 365f5fdd..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/loader/impl/EzyConfigLoaderImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.tvd12.ezyfoxserver.loader.impl; - -import org.apache.commons.lang3.StringUtils; - -import com.tvd12.ezyfoxserver.config.EzyConfig; -import com.tvd12.ezyfoxserver.loader.EzyConfigLoader; -import com.tvd12.properties.file.mapping.PropertiesMapper; -import com.tvd12.properties.file.reader.BaseFileReader; - -public class EzyConfigLoaderImpl implements EzyConfigLoader { - - private String filePath; - - private EzyConfigLoaderImpl() { - } - - public static EzyConfigLoaderImpl newInstance() { - return new EzyConfigLoaderImpl(); - } - - public EzyConfigLoaderImpl filePath(final String filePath) { - this.filePath = filePath; - return this; - } - - @Override - public EzyConfig load() { - validateFilePath(filePath); - return doLoad(); - } - - private EzyConfig doLoad() { - return new PropertiesMapper() - .context(getClass()) - .clazz(EzyConfig.class) - .file(filePath) - .reader(new BaseFileReader()) - .map(); - } - - private void validateFilePath(final String filePath) { - if(StringUtils.isEmpty(filePath)) - throw new IllegalArgumentException("config file path can't be null"); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java deleted file mode 100644 index 2350db7a..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/pattern/EzyObjectPool.java +++ /dev/null @@ -1,242 +0,0 @@ -package com.tvd12.ezyfoxserver.pattern; - -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.builder.EzyBuilder; -import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; -import com.tvd12.ezyfoxserver.entity.EzyDestroyable; -import com.tvd12.ezyfoxserver.entity.EzyStartable; -import com.tvd12.ezyfoxserver.util.EzyLoggable; -import com.tvd12.ezyfoxserver.util.EzyReturner; - -public abstract class EzyObjectPool - extends EzyLoggable - implements EzyStartable, EzyDestroyable { - - protected Queue pool; - protected int minObjects; - protected int maxObjects; - protected long validationInterval; - protected List borrowedObjects; - protected EzyObjectFactory objectFactory; - protected ScheduledExecutorService validationService; - - @SuppressWarnings({ "rawtypes"}) - protected EzyObjectPool(AbstractBuilder builder) { - initialize(builder); - } - - @SuppressWarnings("rawtypes") - private final void initialize(AbstractBuilder builder) { - initComponents(builder); - initializeObjects(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected void initComponents(AbstractBuilder builder) { - this.logger = newLogger(); - this.pool = builder.pool; - this.minObjects = builder.minObjects; - this.maxObjects = builder.maxObjects; - this.objectFactory = builder.objectFactory; - this.borrowedObjects = builder.newBorrowedObjects(); - this.validationService = builder.validationService; - this.validationInterval = builder.validationInterval; - } - - protected final void initializeObjects() { - for(int i = 0 ; i < minObjects ; i++) - pool.add(createObject()); - } - - protected T createObject() { - return objectFactory.newProduct(); - } - - protected void removeObject(T object) { - } - - @Override - public void start() throws Exception { - validationService.scheduleWithFixedDelay(newValidationTask(), - validationInterval, validationInterval, TimeUnit.MILLISECONDS); - } - - protected Runnable newValidationTask() { - return new Runnable() { - - @Override - public void run() { - try { - addOrRemoveObjects(pool.size()); - removeStaleObjects(); - } - catch(Exception e) { - getLogger().error("object poll validation error", e); - } - } - - private void addOrRemoveObjects(int poolSize) { - if(poolSize < minObjects) - addObjects(poolSize); - else if(poolSize > maxObjects) - removeObjects(poolSize); - } - - private void addObjects(int poolSize) { - if(poolSize < minObjects) - addNewObjects(minObjects - poolSize); - } - - private void addNewObjects(int size) { - for(int i = 0 ; i < size ; i++) - pool.add(createObject()); - } - - private void removeObjects(int poolSize) { - if(poolSize > maxObjects) - removeUnusedObjects(poolSize - maxObjects); - } - - private void removeUnusedObjects(int size) { - for(int i = 0 ; i < size ; i++) - removeObject(pool.poll()); - } - }; - } - - protected void removeStaleObjects() { - } - - protected final T borrowObject() { - T obj = borrowOrNewObject(); - borrowedObjects.add(obj); - return obj; - } - - private final T borrowOrNewObject() { - return EzyReturner.returnNotNull(pool.poll(), createObject()); - } - - protected final boolean returnObject(T object) { - return object != null ? doReturnObject(object) : false; - } - - private final boolean doReturnObject(T object) { - borrowedObjects.remove(object); - return pool.offer(object); - } - - @Override - public void destroy() { - try { - validationService.shutdown(); - } - catch(Exception e) { - getLogger().error(getClass().getSimpleName() + " error", e); - } - } - - protected Logger getLogger() { - return this.logger; - } - - private Logger newLogger() { - return LoggerFactory.getLogger(getClass()); - } - - @SuppressWarnings("rawtypes") - public static abstract class AbstractBuilder - implements EzyBuilder> { - - private Queue pool; - private int minObjects; - private int maxObjects; - private long validationInterval; - protected EzyObjectFactory objectFactory; - private ScheduledExecutorService validationService; - - public B pool(Queue pool) { - this.pool = pool; - return getThis(); - } - - public B minObjects(int minObjects) { - this.minObjects = minObjects; - return getThis(); - } - - public B maxObjects(int maxObjects) { - this.maxObjects = maxObjects; - return getThis(); - } - - public B objectFactory(EzyObjectFactory objectFactory) { - this.objectFactory = objectFactory; - return getThis(); - } - - public B validationInterval(long validationInterval) { - this.validationInterval = validationInterval; - return getThis(); - } - - public B validationService(ScheduledExecutorService validationService) { - this.validationService = validationService; - return getThis(); - } - - @Override - public EzyObjectPool build() { - this.prepare(); - return newProduct(); - } - - protected abstract String getProductName(); - protected abstract EzyObjectPool newProduct(); - - protected void prepare() { - initPool(); - initSimpleValue(); - initValidationService(); - } - - protected void initSimpleValue() { - this.minObjects = 300; - this.maxObjects = 5000; - this.validationInterval = 3 * 1000; - } - - protected void initPool() { - if(pool == null) - pool = new ConcurrentLinkedQueue<>(); - } - - protected void initValidationService() { - if(validationService == null) - validationService = newValidationService(); - } - - protected ScheduledExecutorService newValidationService() { - return EzyExecutors.newSingleThreadScheduledExecutor(getProductName()); - } - - protected List newBorrowedObjects() { - return new CopyOnWriteArrayList<>(); - } - - @SuppressWarnings("unchecked") - private B getThis() { - return (B)this; - } - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyServerReadyController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyServerReadyController.java new file mode 100644 index 00000000..ae71a5b6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyServerReadyController.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.plugincontroller; + +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.controller.EzyAbstractPluginEventController; +import com.tvd12.ezyfoxserver.event.EzyServerReadyEvent; + +public class EzyServerReadyController + extends EzyAbstractPluginEventController { + + @Override + public void handle(EzyPluginContext ctx, EzyServerReadyEvent event) { + getLogger().info("plugin: server ready controller"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyUserRequestPluginController.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyUserRequestPluginController.java new file mode 100644 index 00000000..123f5f66 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/plugincontroller/EzyUserRequestPluginController.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.plugincontroller; + +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.controller.EzyAbstractPluginEventController; +import com.tvd12.ezyfoxserver.event.EzyUserRequestPluginEvent; + +public class EzyUserRequestPluginController + extends EzyAbstractPluginEventController { + + @Override + public void handle(EzyPluginContext ctx, EzyUserRequestPluginEvent event) { + getLogger().info("plugin: user {} request", event.getUser().getName()); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppParams.java new file mode 100644 index 00000000..f53b1584 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppParams.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyAccessAppParams { + + String getAppName(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppRequest.java new file mode 100644 index 00000000..a393aba2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyAccessAppRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyAccessAppRequest extends EzyUserRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeParams.java new file mode 100644 index 00000000..373f545a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeParams.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyHandShakeParams { + + String getClientId(); + + String getClientKey(); + + String getClientType(); + + String getClientVersion(); + + String getReconnectToken(); +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeRequest.java new file mode 100644 index 00000000..7b8b46d6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyHandShakeRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyHandShakeRequest extends EzyRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginParams.java new file mode 100644 index 00000000..3be46ec0 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginParams.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyLoginParams { + + String getUsername(); + + String getPassword(); + + EzyArray getData(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginRequest.java new file mode 100644 index 00000000..99dcd55c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyLoginRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyLoginRequest extends EzyRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingParams.java new file mode 100644 index 00000000..81b5b285 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingParams.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyPingParams { + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingRequest.java new file mode 100644 index 00000000..e0fce310 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyPingRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyPingRequest extends EzyRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectParams.java new file mode 100644 index 00000000..af4eef1b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectParams.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyReconnectParams { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectRequest.java new file mode 100644 index 00000000..3ace8b65 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyReconnectRequest.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzySession; + +public interface EzyReconnectRequest extends EzyRequest { + + EzySession getOldSession(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequest.java new file mode 100644 index 00000000..828d8b48 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequest.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzySession; + +public interface EzyRequest

{ + + P getParams(); + + EzySession getSession(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppParams.java new file mode 100644 index 00000000..22b9171b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppParams.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyRequestAppParams { + + int getAppId(); + + EzyArray getData(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppRequest.java new file mode 100644 index 00000000..da24af7a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestAppRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyRequestAppRequest extends EzyUserRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginParams.java new file mode 100644 index 00000000..90985efc --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginParams.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyRequestPluginParams { + + EzyArray getData(); + + String getPluginName(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginRequest.java new file mode 100644 index 00000000..5582aae0 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyRequestPluginRequest.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.request; + +public interface EzyRequestPluginRequest extends EzyUserRequest { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyUserRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyUserRequest.java new file mode 100644 index 00000000..168c8eec --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/EzyUserRequest.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.request; + +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzyUserRequest

extends EzyRequest

{ + + EzyUser getUser(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppParams.java new file mode 100644 index 00000000..17f26146 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppParams.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.request.EzyAccessAppParams; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleAccessAppParams implements EzyAccessAppParams { + + private String appName; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private String appName; + + public Builder appName(String appName) { + this.appName = appName; + return this; + } + + @Override + public EzyAccessAppParams build() { + EzySimpleAccessAppParams answer = new EzySimpleAccessAppParams(); + answer.setAppName(appName); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppRequest.java new file mode 100644 index 00000000..ea1b2d18 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleAccessAppRequest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyAccessAppParams; +import com.tvd12.ezyfoxserver.request.EzyAccessAppRequest; + +public class EzySimpleAccessAppRequest + extends EzySimpleUserRequest + implements EzyAccessAppRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleUserRequest.Builder { + @Override + protected EzySimpleAccessAppRequest newProduct() { + return new EzySimpleAccessAppRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeParams.java new file mode 100644 index 00000000..b6f8843a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeParams.java @@ -0,0 +1,70 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.request.EzyHandShakeParams; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleHandShakeParams implements EzyHandShakeParams { + + protected String clientId; + protected String clientKey; + protected String clientType; + protected String clientVersion; + protected String reconnectToken; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected String clientId; + protected String clientKey; + protected String clientType; + protected String clientVersion; + protected String reconnectToken; + + public Builder clientId(String clientId) { + this.clientId = clientId; + return this; + } + + public Builder clientKey(String clientKey) { + this.clientKey = clientKey; + return this; + } + + public Builder clientType(String clientType) { + this.clientType = clientType; + return this; + } + + public Builder clientVersion(String clientVersion) { + this.clientVersion = clientVersion; + return this; + } + + public Builder reconnectToken(String reconnectToken) { + this.reconnectToken = reconnectToken; + return this; + } + + @Override + public EzyHandShakeParams build() { + EzySimpleHandShakeParams answer = new EzySimpleHandShakeParams(); + answer.setClientId(clientId); + answer.setClientKey(clientKey); + answer.setClientType(clientType); + answer.setClientVersion(clientVersion); + answer.setReconnectToken(reconnectToken); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeRequest.java new file mode 100644 index 00000000..0a683ef7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleHandShakeRequest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyHandShakeParams; +import com.tvd12.ezyfoxserver.request.EzyHandShakeRequest; + +public class EzySimpleHandShakeRequest + extends EzySimpleRequest + implements EzyHandShakeRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleRequest.Builder { + + @Override + public EzyHandShakeRequest build() { + return (EzyHandShakeRequest) super.build(); + } + + @Override + protected EzySimpleHandShakeRequest newProduct() { + return new EzySimpleHandShakeRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginParams.java new file mode 100644 index 00000000..6a46bd94 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginParams.java @@ -0,0 +1,55 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.request.EzyLoginParams; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleLoginParams implements EzyLoginParams { + + private EzyArray data; + private String username; + private String password; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzyArray data; + private String username; + private String password; + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + public Builder username(String username) { + this.username = username; + return this; + } + + public Builder password(String password) { + this.password = password; + return this; + } + + @Override + public EzyLoginParams build() { + EzySimpleLoginParams answer = new EzySimpleLoginParams(); + answer.setData(data); + answer.setUsername(username); + answer.setPassword(password); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginRequest.java new file mode 100644 index 00000000..871fb806 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleLoginRequest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyLoginParams; +import com.tvd12.ezyfoxserver.request.EzyLoginRequest; + +public class EzySimpleLoginRequest + extends EzySimpleRequest + implements EzyLoginRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleRequest.Builder { + + @Override + public EzyLoginRequest build() { + return (EzyLoginRequest) super.build(); + } + + @Override + protected EzySimpleLoginRequest newProduct() { + return new EzySimpleLoginRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingParams.java new file mode 100644 index 00000000..88abef6d --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingParams.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.request.EzyPingParams; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimplePingParams implements EzyPingParams { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + @Override + public EzyPingParams build() { + return new EzySimplePingParams(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingRequest.java new file mode 100644 index 00000000..71dcd2c7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimplePingRequest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyPingParams; +import com.tvd12.ezyfoxserver.request.EzyPingRequest; + +public class EzySimplePingRequest + extends EzySimpleRequest + implements EzyPingRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleRequest.Builder { + + @Override + public EzyPingRequest build() { + return (EzyPingRequest) super.build(); + } + + @Override + protected EzySimplePingRequest newProduct() { + return new EzySimplePingRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectParams.java new file mode 100644 index 00000000..979b7f1b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectParams.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.request.EzyReconnectParams; + +public class EzySimpleReconnectParams implements EzyReconnectParams { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + @Override + public EzyReconnectParams build() { + return new EzySimpleReconnectParams(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectRequest.java new file mode 100644 index 00000000..61e4e604 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleReconnectRequest.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyReconnectParams; +import com.tvd12.ezyfoxserver.request.EzyReconnectRequest; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleReconnectRequest + extends EzySimpleRequest + implements EzyReconnectRequest { + + protected EzySession oldSession; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleRequest.Builder { + + protected EzySession oldSession; + + public Builder oldSession(EzySession oldSession) { + this.oldSession = oldSession; + return this; + } + + @Override + public EzyReconnectRequest build() { + return (EzyReconnectRequest) super.build(); + } + + @Override + protected EzySimpleReconnectRequest newProduct() { + EzySimpleReconnectRequest answer = new EzySimpleReconnectRequest(); + answer.setOldSession(oldSession); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequest.java new file mode 100644 index 00000000..b2499a92 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequest.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyRequest; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleRequest

implements EzyRequest

{ + + protected P params; + protected EzySession session; + + public abstract static class Builder> + implements EzyBuilder> { + protected P params; + protected EzySession session; + + @SuppressWarnings("unchecked") + public B params(P params) { + this.params = params; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B session(EzySession session) { + this.session = session; + return (B)this; + } + + @Override + public EzyRequest

build() { + EzySimpleRequest

answer = newProduct(); + answer.setParams(params); + answer.setSession(session); + return answer; + } + + protected abstract EzySimpleRequest

newProduct(); + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppParams.java new file mode 100644 index 00000000..892c5f96 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppParams.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleRequestAppParams implements EzyRequestAppParams { + + protected int appId; + protected EzyArray data; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private int appId; + private EzyArray data; + + public Builder appId(int appId) { + this.appId = appId; + return this; + } + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + @Override + public EzyRequestAppParams build() { + EzySimpleRequestAppParams answer = new EzySimpleRequestAppParams(); + answer.setData(data); + answer.setAppId(appId); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppRequest.java new file mode 100644 index 00000000..35049f8f --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestAppRequest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; +import com.tvd12.ezyfoxserver.request.EzyRequestAppRequest; + +public class EzySimpleRequestAppRequest + extends EzySimpleUserRequest + implements EzyRequestAppRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleUserRequest.Builder { + + @Override + public EzyRequestAppRequest build() { + return (EzyRequestAppRequest) super.build(); + } + + @Override + protected EzySimpleRequestAppRequest newProduct() { + return new EzySimpleRequestAppRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginParams.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginParams.java new file mode 100644 index 00000000..b4f1ba69 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginParams.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.request.EzyRequestPluginParams; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +public class EzySimpleRequestPluginParams implements EzyRequestPluginParams { + + protected EzyArray data; + protected String pluginName; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzyArray data; + protected String pluginName; + + public Builder data(EzyArray data) { + this.data = data; + return this; + } + + public Builder pluginName(String pluginName) { + this.pluginName = pluginName; + return this; + } + + @Override + public EzyRequestPluginParams build() { + EzySimpleRequestPluginParams answer = new EzySimpleRequestPluginParams(); + answer.setData(data); + answer.setPluginName(pluginName); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginRequest.java new file mode 100644 index 00000000..771a6ddb --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleRequestPluginRequest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.request.EzyRequestPluginParams; +import com.tvd12.ezyfoxserver.request.EzyRequestPluginRequest; + +public class EzySimpleRequestPluginRequest + extends EzySimpleUserRequest + implements EzyRequestPluginRequest { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzySimpleUserRequest.Builder { + + @Override + public EzyRequestPluginRequest build() { + return (EzyRequestPluginRequest) super.build(); + } + + @Override + protected EzySimpleRequestPluginRequest newProduct() { + return new EzySimpleRequestPluginRequest(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleUserRequest.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleUserRequest.java new file mode 100644 index 00000000..2f9aa308 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/request/impl/EzySimpleUserRequest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.request.impl; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.request.EzyUserRequest; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleUserRequest

+ extends EzySimpleRequest

+ implements EzyUserRequest

{ + + protected EzyUser user; + + public abstract static class Builder> + extends EzySimpleRequest.Builder { + + protected EzyUser user; + + @SuppressWarnings("unchecked") + public B user(EzyUser user) { + this.user = user; + return (B)this; + } + + @Override + public EzyUserRequest

build() { + EzySimpleUserRequest

answer = (EzySimpleUserRequest

) super.build(); + answer.setUser(user); + return answer; + } + + @Override + protected abstract EzySimpleUserRequest

newProduct(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAbstractResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAbstractResponse.java index ed930855..13a899b3 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAbstractResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyAbstractResponse.java @@ -9,7 +9,7 @@ @Setter public abstract class EzyAbstractResponse extends EzyFixedCommandResponse { - private int appId; - private EzyConstant command; + protected int appId; + protected EzyConstant command; } 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 ed09cbfd..ef1907cc 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 @@ -3,26 +3,26 @@ import com.tvd12.ezyfoxserver.constant.EzyCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import lombok.Setter; + +@Setter public class EzyAccessAppResponse extends EzyBaseResponse implements EzyResponse { - private int appId; - private EzyData data; - - protected EzyAccessAppResponse(Builder builder) { - this.data = builder.data; - this.appId = builder.appId; - } + protected EzyData data; + protected EzyAppSetting app; @Override public EzyConstant getCommand() { - return EzyCommand.ACCESS_APP; + return EzyCommand.APP_ACCESS; } @Override public Object getData() { return newArrayBuilder() - .append(appId) + .append(app.getId()) + .append(app.getName()) .append(data) .build(); } @@ -31,23 +31,28 @@ public static Builder builder() { return new Builder(); } - public static class Builder { - private int appId; - private EzyData data; - - public Builder appId(int appId) { - this.appId = appId; - return this; - } + public static class Builder implements EzyResponse.Builder { + protected EzyData data; + protected EzyAppSetting app; public Builder data(EzyData data) { this.data = data; return this; } + public Builder app(EzyAppSetting app) { + this.app = app; + return this; + } + + @Override public EzyAccessAppResponse build() { - return new EzyAccessAppResponse(this); + EzyAccessAppResponse answer = new EzyAccessAppResponse(); + answer.setApp(app); + answer.setData(data); + return answer; } + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyBaseResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyBaseResponse.java index 383e9497..4a3a8d3b 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyBaseResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyBaseResponse.java @@ -1,18 +1,6 @@ package com.tvd12.ezyfoxserver.response; -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; -import com.tvd12.ezyfoxserver.factory.EzyFactory; -import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; -public class EzyBaseResponse extends EzyLoggable { - - protected EzyArrayBuilder newArrayBuilder() { - return EzyFactory.create(EzyArrayBuilder.class); - } - - protected EzyObjectBuilder newObjectBuilder() { - return EzyFactory.create(EzyObjectBuilder.class); - } - +public class EzyBaseResponse extends EzyEntityBuilders { } 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 66679ade..1643e870 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 @@ -3,13 +3,12 @@ import com.tvd12.ezyfoxserver.constant.EzyCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; +import lombok.Setter; + +@Setter public class EzyDisconnectResponse extends EzyBaseResponse implements EzyResponse { - private EzyConstant reason; - - protected EzyDisconnectResponse(Builder builder) { - this.reason = builder.reason; - } + protected EzyConstant reason; @Override public EzyConstant getCommand() { @@ -27,8 +26,8 @@ public static Builder builder() { return new Builder(); } - public static class Builder { - private EzyConstant reason; + public static class Builder implements EzyResponse.Builder { + protected EzyConstant reason; public Builder reason(EzyConstant reason) { this.reason = reason; @@ -36,7 +35,9 @@ public Builder reason(EzyConstant reason) { } public EzyDisconnectResponse build() { - return new EzyDisconnectResponse(this); + EzyDisconnectResponse answer = new EzyDisconnectResponse(); + answer.setReason(reason); + return answer; } } 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 new file mode 100644 index 00000000..48668d58 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyErrorResponse.java @@ -0,0 +1,71 @@ +package com.tvd12.ezyfoxserver.response; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyIError; + +import lombok.Setter; + +@Setter +public class EzyErrorResponse + extends EzyBaseResponse implements EzyResponse { + + protected int code; + protected String message; + + @Override + public Object getData() { + return newArrayBuilder() + .append(code) + .append(message) + .build(); + } + + @Override + public EzyConstant getCommand() { + return EzyCommand.ERROR; + } + + public static Builder builder() { + return new Builder<>(); + } + + public static class Builder> + implements EzyResponse.Builder { + protected int code; + protected String message; + + @SuppressWarnings("unchecked") + public B code(int code) { + this.code = code; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B message(String message) { + this.message = message; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B error(EzyIError error) { + this.code = error.getId(); + this.message = error.getMessage(); + return (B)this; + } + + @Override + public EzyResponse build() { + EzyErrorResponse answer = newProduct(); + answer.setCode(code); + answer.setMessage(message); + return answer; + } + + protected EzyErrorResponse newProduct() { + return new EzyErrorResponse(); + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyFixedCommandResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyFixedCommandResponse.java index dbdad77f..17992ff4 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyFixedCommandResponse.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyFixedCommandResponse.java @@ -9,6 +9,6 @@ public abstract class EzyFixedCommandResponse extends EzyBaseResponse implements EzyResponse { - private Object data; + protected Object data; } 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 7140beda..4c223446 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 @@ -2,27 +2,30 @@ import com.tvd12.ezyfoxserver.constant.EzyCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.sercurity.EzyAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.util.EzyReturner; +import lombok.Setter; + +@Setter public class EzyHandShakeResponse extends EzyBaseResponse implements EzyResponse { - private String publicKey; - private String reconnectToken; - - protected EzyHandShakeResponse(Builder builder) { - this.publicKey = builder.publicKey; - this.reconnectToken = builder.reconnectToken; - } + protected boolean reconnect; + protected String reconnectToken; + protected String serverPublicKey; @Override public EzyConstant getCommand() { - return EzyCommand.HAND_SHAKE; + return EzyCommand.HANDSHAKE; } @Override public Object getData() { return newArrayBuilder() - .append(publicKey) + .append(serverPublicKey) .append(reconnectToken) + .append(reconnect) .build(); } @@ -30,13 +33,20 @@ public static Builder builder() { return new Builder(); } - public static class Builder { - private String publicKey; - private String reconnectToken; + public static class Builder implements EzyResponse.Builder { + protected byte[] clientKey; + protected boolean reconnect; + protected String reconnectToken; + protected byte[] serverPublicKey; + + public Builder clientKey(byte[] clientKey) { + this.clientKey = clientKey; + return this; + } - public Builder publicKey(String publicKey) { - this.publicKey = publicKey; - return this; + public Builder reconnect(boolean value) { + this.reconnect = value; + return this; } public Builder reconnectToken(String reconnectToken) { @@ -44,9 +54,41 @@ public Builder reconnectToken(String reconnectToken) { return this; } - public EzyHandShakeResponse build() { - return new EzyHandShakeResponse(this); + public Builder serverPublicKey(byte[] serverPublicKey) { + this.serverPublicKey = serverPublicKey; + return this; + } + + @Override + public EzyResponse build() { + EzyHandShakeResponse answer = new EzyHandShakeResponse(); + answer.setReconnect(reconnect); + answer.setReconnectToken(encryptReconnectToken()); + answer.setServerPublicKey(encryptServerPublicKey()); + return answer; } + + protected String encryptServerPublicKey() { + return EzyBase64.encode2utf(serverPublicKey); + } + + protected String encryptReconnectToken() { + return encryptReconnectToken(clientKey, reconnectToken); + } + + protected String encryptReconnectToken(byte[] key, String token) { + return EzyReturner.returnWithException( + () -> tryEncryptReconnectToken(key, token), + (e) -> new IllegalArgumentException(e)); + } + + protected String tryEncryptReconnectToken(byte[] key, String token) + throws Exception { + return EzyAsyCrypt.builder() + .algorithm("RSA") + .publicKey(key) + .build().encrypt(token, String.class); + } } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginErrorResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginErrorResponse.java new file mode 100644 index 00000000..a79d7d2a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyLoginErrorResponse.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.response; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public class EzyLoginErrorResponse extends EzyErrorResponse { + + @Override + public EzyConstant getCommand() { + return EzyCommand.LOGIN_ERROR; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyErrorResponse.Builder { + @Override + public EzyLoginErrorResponse build() { + return (EzyLoginErrorResponse) super.build(); + } + + @Override + protected EzyLoginErrorResponse newProduct() { + return new EzyLoginErrorResponse(); + } + } + +} 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 cbbc35c2..c917602d 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 @@ -2,18 +2,17 @@ import com.tvd12.ezyfoxserver.constant.EzyCommand; import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import lombok.Setter; + +@Setter public class EzyLoginResponse extends EzyBaseResponse implements EzyResponse { - private long userId; - private Object data; - private String username; - - protected EzyLoginResponse(Builder builder) { - this.data = builder.data; - this.userId = builder.userId; - this.username = builder.username; - } + protected long userId; + protected Object data; + protected String username; + protected EzyArray joinedApps; @Override public EzyConstant getCommand() { @@ -25,6 +24,7 @@ public Object getData() { return newArrayBuilder() .append(userId) .append(username) + .append(joinedApps) .append(data) .build(); } @@ -33,10 +33,11 @@ public static Builder builder() { return new Builder(); } - public static class Builder { - private long userId; - private Object data; - private String username; + public static class Builder implements EzyResponse.Builder { + protected long userId; + protected Object data; + protected String username; + protected EzyArray joinedApps; public Builder userId(long userId) { this.userId = userId; @@ -53,9 +54,21 @@ public Builder username(String username) { return this; } - public EzyLoginResponse build() { - return new EzyLoginResponse(this); + public Builder joinedApps(EzyArray joinedApps) { + this.joinedApps = joinedApps; + return this; + } + + @Override + public EzyResponse build() { + EzyLoginResponse answer = new EzyLoginResponse(); + answer.setData(data); + answer.setUserId(userId); + answer.setUsername(username); + answer.setJoinedApps(joinedApps); + return answer; } + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPongResponse.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPongResponse.java new file mode 100644 index 00000000..e0d643a6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyPongResponse.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.response; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public class EzyPongResponse extends EzyBaseResponse implements EzyResponse { + + @Override + public Object getData() { + return newArrayBuilder().build(); + } + + @Override + public EzyConstant getCommand() { + return EzyCommand.PONG; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyResponse.Builder { + @Override + public EzyResponse build() { + return new EzyPongResponse(); + } + } + +} 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 new file mode 100644 index 00000000..1a6685ac --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestAppResponse.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.response; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyData; + +import lombok.Setter; + +@Setter +public class EzyRequestAppResponse extends EzyBaseResponse implements EzyResponse { + + protected int appId; + protected EzyData data; + + @Override + public EzyConstant getCommand() { + return EzyCommand.APP_REQUEST; + } + + @Override + public Object getData() { + return newArrayBuilder() + .append(appId) + .append(data) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyResponse.Builder { + protected int appId; + protected EzyData data; + + public Builder appId(int appId) { + this.appId = appId; + return this; + } + + public Builder data(EzyData data) { + this.data = data; + return this; + } + + @Override + public EzyResponse build() { + EzyRequestAppResponse answer = new EzyRequestAppResponse(); + answer.setData(data); + answer.setAppId(appId); + return answer; + } + + } + +} 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 new file mode 100644 index 00000000..9d6407ff --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/response/EzyRequestPluginResponse.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.response; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyData; + +import lombok.Setter; + +@Setter +public class EzyRequestPluginResponse extends EzyBaseResponse implements EzyResponse { + + protected EzyData data; + protected String pluginName; + + @Override + public EzyConstant getCommand() { + return EzyCommand.APP_REQUEST; + } + + @Override + public Object getData() { + return newArrayBuilder() + .append(pluginName) + .append(data) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyResponse.Builder { + protected EzyData data; + protected String pluginName; + + public Builder data(EzyData data) { + this.data = data; + return this; + } + + public Builder pluginName(String pluginName) { + this.pluginName = pluginName; + return this; + } + + @Override + public EzyResponse build() { + EzyRequestPluginResponse answer = new EzyRequestPluginResponse(); + answer.setData(data); + answer.setPluginName(pluginName); + return answer; + } + + } + +} 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 cfa11da9..0e90d75d 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 @@ -1,5 +1,6 @@ package com.tvd12.ezyfoxserver.response; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; import com.tvd12.ezyfoxserver.constant.EzyConstant; public interface EzyResponse { @@ -8,4 +9,6 @@ public interface EzyResponse { EzyConstant getCommand(); + interface Builder extends EzyBuilder { + } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonMapping.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonMapping.java deleted file mode 100644 index 1f81f202..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonMapping.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.tvd12.ezyfoxserver.service; - -public interface EzyJsonMapping extends EzyJsonWriting { -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonWriting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonWriting.java deleted file mode 100644 index cbf3bb78..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyJsonWriting.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.service; - -public interface EzyJsonWriting { - - String writeAsString(Object object); - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGeneration.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGeneration.java deleted file mode 100644 index 638def63..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGeneration.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.tvd12.ezyfoxserver.service; - -public interface EzySessionTokenGeneration { - - String generate(); - -} 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 new file mode 100644 index 00000000..ec8d665b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzySessionTokenGenerator.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.service; + +public interface EzySessionTokenGenerator { + + String generate(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyXmlReading.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyXmlReading.java deleted file mode 100644 index cc69b754..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/EzyXmlReading.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.tvd12.ezyfoxserver.service; - -import java.io.File; - -public interface EzyXmlReading { - - T read(final File xmlFile, final Class outputType); - - default T read(final String filePath, final Class outputType) { - return read(new File(filePath), outputType); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyJsonMappingImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyJsonMappingImpl.java deleted file mode 100644 index 5059d8ce..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyJsonMappingImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.tvd12.ezyfoxserver.service.impl; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.tvd12.ezyfoxserver.service.EzyJsonMapping; - -public class EzyJsonMappingImpl implements EzyJsonMapping { - - private final ObjectMapper mapper; - - protected EzyJsonMappingImpl(Builder builder) { - this.mapper = new ObjectMapper(); - this.mapper.enable(SerializationFeature.INDENT_OUTPUT); - } - - @Override - public String writeAsString(Object object) { - try { - return mapper.writeValueAsString(object); - } catch (JsonProcessingException e) { - getLogger().error("can not read object " + object, e); - return null; - } - } - - private Logger getLogger() { - return LoggerFactory.getLogger(getClass()); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - public EzyJsonMappingImpl build() { - return new EzyJsonMappingImpl(this); - } - - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyResponseSerializerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyResponseSerializerImpl.java deleted file mode 100644 index af625c4a..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyResponseSerializerImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.tvd12.ezyfoxserver.service.impl; - -import java.util.HashMap; -import java.util.Map; - -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.factory.EzyFactory; -import com.tvd12.ezyfoxserver.response.EzyResponse; -import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; - -import lombok.Builder; - -@Builder -public class EzyResponseSerializerImpl implements EzyResponseSerializer { - - @SuppressWarnings("rawtypes") - private static final Map SERIALIZERS; - - static { - SERIALIZERS = defaultSerializers(); - } - - @SuppressWarnings("unchecked") - @Override - public T serialize(EzyResponse request, Class outType) { - return (T) SERIALIZERS.get(outType).serialize(request); - } - - @SuppressWarnings("rawtypes") - private static Map defaultSerializers() { - Map answer = new HashMap<>(); - answer.put(EzyArray.class, new Serializer() { - @Override - public EzyArray serialize(EzyResponse request) { - return EzyFactory.create(EzyArrayBuilder.class) - .append(request.getCommand().getId()) - .append(request.getData()) - .build(); - } - }); - return answer; - } - -} - -interface Serializer { - O serialize(I request); -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySessionTokenGenerationImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySessionTokenGenerationImpl.java deleted file mode 100644 index 48e8fb9f..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySessionTokenGenerationImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.tvd12.ezyfoxserver.service.impl; - -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; - -import com.tvd12.ezyfoxserver.sercurity.EzyBase64; -import com.tvd12.ezyfoxserver.sercurity.EzyUuid; -import com.tvd12.ezyfoxserver.service.EzySessionTokenGeneration; - -public class EzySessionTokenGenerationImpl implements EzySessionTokenGeneration { - - private AtomicLong counter; - - { - counter = new AtomicLong(); - } - - @Override - public String generate() { - return EzyBase64.encodeUTF(getRawString()); - } - - private String getRawString() { - return getCurrentTime() + "-" + randomUuid() + "-" + getCount(); - } - - private UUID randomUuid() { - return EzyUuid.random(); - } - - private long getCurrentTime() { - return System.currentTimeMillis(); - } - - private long getCount() { - return counter.incrementAndGet(); - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleResponseSerializer.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleResponseSerializer.java new file mode 100644 index 00000000..9183dfa6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleResponseSerializer.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.service.impl; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.function.EzySerializer; +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleResponseSerializer + extends EzyLoggable implements EzyResponseSerializer { + + @SuppressWarnings("rawtypes") + private final Map serializers; + + protected EzySimpleResponseSerializer(Builder builder) { + this.serializers = builder.newSerializers(); + } + + @SuppressWarnings("unchecked") + @Override + public T serialize(EzyResponse response, Class outType) { + Object answer = serializers.get(outType).serialize(response); + return (T)answer; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + extends EzyEntityBuilders + implements EzyBuilder { + + @Override + public EzyResponseSerializer build() { + return new EzySimpleResponseSerializer(this); + } + + @SuppressWarnings("rawtypes") + protected Map newSerializers() { + Map answer = new HashMap<>(); + answer.put(EzyArray.class, new EzySerializer() { + @Override + public EzyArray serialize(EzyResponse response) { + return newArrayBuilder() + .append(response.getCommand().getId()) + .append(response.getData()) + .build(); + } + }); + return answer; + } + + } + +} \ No newline at end of file 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 new file mode 100644 index 00000000..8b992381 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzySimpleSessionTokenGenerator.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.service.impl; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyUuid; +import com.tvd12.ezyfoxserver.service.EzySessionTokenGenerator; + +public class EzySimpleSessionTokenGenerator implements EzySessionTokenGenerator { + + private AtomicLong counter = new AtomicLong(); + + @Override + public String generate() { + return EzyBase64.encodeUtf(getRawString()); + } + + private String getRawString() { + return getCurrentTime() + "-" + randomUuid() + "-" + getCount(); + } + + private UUID randomUuid() { + return EzyUuid.random(); + } + + private long getCurrentTime() { + return System.currentTimeMillis(); + } + + private long getCount() { + return counter.incrementAndGet(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyXmlReadingImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyXmlReadingImpl.java deleted file mode 100644 index 97d82bba..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/service/impl/EzyXmlReadingImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.tvd12.ezyfoxserver.service.impl; - -import java.io.File; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; - -import com.tvd12.ezyfoxserver.exception.EzyReadingXmlException; -import com.tvd12.ezyfoxserver.service.EzyXmlReading; - -public class EzyXmlReadingImpl implements EzyXmlReading { - - private Unmarshaller unmarshaller; - - private EzyXmlReadingImpl(final Builder builder) { - this.unmarshaller = builder.newUnmarshaller(); - } - - @Override - public T read(final File xmlFile, final Class outputType) { - try { - return unmarshaller.unmarshal(new StreamSource(xmlFile), outputType).getValue(); - } catch (JAXBException e) { - throw new EzyReadingXmlException("Can not read xml file " + xmlFile + " with " + outputType, e); - } - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String contextPath; - private ClassLoader classLoader; - - public Builder contextPath(final String contextPath) { - this.contextPath = contextPath; - return this; - } - - public Builder classLoader(final ClassLoader classLoader) { - this.classLoader = classLoader; - return this; - } - - public Unmarshaller newUnmarshaller() { - try { - return newJAXBContext().createUnmarshaller(); - } catch (JAXBException e) { - throw new EzyReadingXmlException(e); - } - } - - public EzyXmlReadingImpl build() { - return new EzyXmlReadingImpl(this); - } - - private JAXBContext newJAXBContext() { - try { - return JAXBContext.newInstance(contextPath, classLoader); - } catch (JAXBException e) { - throw new EzyReadingXmlException(e); - } - } - } - -} 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 new file mode 100644 index 00000000..961eff54 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSetting.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.controller.EzyEventController; +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@XmlAccessorType(XmlAccessType.NONE) +public abstract class EzyAbstractSetting + implements EzyBaseSetting, EzyHomePathAware { + + protected final int id = newId(); + + @XmlElement(name = "name") + protected String name; + + @XmlElement(name = "entry-loader") + protected String entryLoader; + + @XmlElement(name = "worker-pool-size") + protected int workerPoolSize = 16; + + @XmlElement(name = "config-file") + protected String configFile = "config.properties"; + + @JsonIgnore + protected String homePath = ""; + + @JsonIgnore + protected String location = ""; + + @JsonIgnore + protected final EzyEventControllers eventControllers = newEventControllers(); + + protected int newId() { + return getIdCounter().incrementAndGet(); + } + + @Override + public String getConfigFile() { + return Paths.get(getLocation(), configFile).toString(); + } + + @SuppressWarnings("rawtypes") + @Override + public void addEventController(EzyConstant eventType, EzyEventController ctrl) { + eventControllers.addController(eventType, ctrl); + } + + protected abstract AtomicInteger getIdCounter(); + protected abstract EzyEventControllers newEventControllers(); + +} 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 new file mode 100644 index 00000000..3e15fa64 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAbstractSocketSetting.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@XmlAccessorType(XmlAccessType.NONE) +public abstract class EzyAbstractSocketSetting implements EzyBaseSocketSetting { + + @XmlElement(name = "port") + protected int port; + + @XmlElement(name = "address") + protected String address; + + @XmlElement(name = "codec-creator") + protected String codecCreator; + + public EzyAbstractSocketSetting() { + setAddress("0.0.0.0"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminSetting.java new file mode 100644 index 00000000..79355f0f --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminSetting.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyAdminSetting { + + String getUsername(); + + String getPassword(); + + String getApiAccessToken(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminsSetting.java new file mode 100644 index 00000000..16b62b44 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAdminsSetting.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.List; + +public interface EzyAdminsSetting { + + List getAdmins(); + + EzyAdminSetting getAdminByName(String username); + + EzyAdminSetting getAdminByApiAccessToken(String token); + + boolean containsAdminByName(String username); + + boolean containsAdminByApiAccessToken(String token); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppSetting.java new file mode 100644 index 00000000..adc40adc --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppSetting.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyAppSetting extends EzyBaseSetting { + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppsSetting.java new file mode 100644 index 00000000..577b9949 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyAppsSetting.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.List; +import java.util.Set; + +public interface EzyAppsSetting { + + int getSize(); + + List getApps(); + + Set getAppIds(); + + Set getAppNames(); + + EzyAppSetting getAppById(Integer id); + + EzyAppSetting getAppByName(String name); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSetting.java new file mode 100644 index 00000000..078f7f96 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSetting.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.setting; + +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; + +public interface EzyBaseSetting extends EzyEventControllerAdder { + + int getId(); + + String getName(); + + String getLocation(); + + String getEntryLoader(); + + int getWorkerPoolSize(); + + String getConfigFile(); + + EzyEventControllers getEventControllers(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSocketSetting.java new file mode 100644 index 00000000..107966bc --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyBaseSocketSetting.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyBaseSocketSetting { + + int getPort(); + + String getAddress(); + + String getCodecCreator(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyEventControllerAdder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerAdder.java similarity index 87% rename from ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyEventControllerAdder.java rename to ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerAdder.java index 9a8b77a0..61d4d7fe 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/config/EzyEventControllerAdder.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyEventControllerAdder.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.config; +package com.tvd12.ezyfoxserver.setting; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.controller.EzyEventController; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFileNames.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFileNames.java new file mode 100644 index 00000000..12f19cd8 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFileNames.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.setting; + +public final class EzyFileNames { + + public static final String SETTINGS = "ezy-settings.xml"; + + private EzyFileNames() { + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFolderNamesSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFolderNamesSetting.java new file mode 100644 index 00000000..114230e6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyFolderNamesSetting.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.setting; + +public final class EzyFolderNamesSetting { + + public static final String APPS = "apps"; + public static final String DATA = "data"; + public static final String LIB = "lib"; + public static final String LOGS = "logs"; + public static final String SETTINGS = "settings"; + public static final String PLUGINS = "plugins"; + public static final String ENTRIES = "entries"; + + private EzyFolderNamesSetting() { + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHomePathAware.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHomePathAware.java new file mode 100644 index 00000000..45df2c62 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHomePathAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyHomePathAware { + + void setHomePath(String homePath); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHttpSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHttpSetting.java new file mode 100644 index 00000000..6d6edd77 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyHttpSetting.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyHttpSetting { + + int getPort(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyLoggerSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyLoggerSetting.java new file mode 100644 index 00000000..e96cd6eb --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyLoggerSetting.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyLoggerSetting { + + EzyIgnoredCommandsSetting getIgnoredCommands(); + + interface EzyIgnoredCommandsSetting { + + Set getCommands(); + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSetting.java new file mode 100644 index 00000000..3f4a44e2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginSetting.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +public interface EzyPluginSetting extends EzyBaseSetting { + + int getPriority(); + + EzyListenEvents getListenEvents(); + + interface EzyListenEvents { + + Set getEvents(); + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginsSetting.java new file mode 100644 index 00000000..88748885 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyPluginsSetting.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.List; +import java.util.Set; + +public interface EzyPluginsSetting { + + int getSize(); + + List getPlugins(); + + Set getPluginIds(); + + Set getPluginNames(); + + EzyPluginSetting getPluginById(Integer id); + + EzyPluginSetting getPluginByName(String name); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySessionManagementSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySessionManagementSetting.java new file mode 100644 index 00000000..5a982370 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySessionManagementSetting.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.setting; + +import com.tvd12.ezyfoxserver.constant.EzyMaxRequestPerSecondAction; + +public interface EzySessionManagementSetting { + + long getSessionMaxIdleTime(); + + long getSessionMaxWaitingTime(); + + boolean isSessionAllowReconnect(); + + EzyMaxRequestPerSecond getSessionMaxRequestPerSecond(); + + interface EzyMaxRequestPerSecond { + + int getValue(); + + EzyMaxRequestPerSecondAction getAction(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettings.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettings.java new file mode 100644 index 00000000..82b6d673 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettings.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.Set; + +public interface EzySettings { + + int getWorkerPoolSize(); + + EzyHttpSetting getHttp(); + + EzySocketSetting getSocket(); + + EzyWebSocketSetting getWebsocket(); + + EzyAdminsSetting getAdmins(); + + EzyLoggerSetting getLogger(); + + EzyUserManagementSetting getUserManagement(); + + EzySessionManagementSetting getSessionManagement(); + + EzyPluginsSetting getPlugins(); + + EzyAppsSetting getApplications(); + + Set getAppIds(); + + Set getAppNames(); + + EzyAppSetting getAppById(Integer id); + + EzyAppSetting getAppByName(String name); + + Set getPluginIds(); + + Set getPluginNames(); + + EzyPluginSetting getPluginById(Integer id); + + EzyPluginSetting getPluginByName(String name); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettingsReader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettingsReader.java new file mode 100644 index 00000000..2c590c3b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySettingsReader.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzySettingsReader { + + EzySettings read(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminSetting.java new file mode 100644 index 00000000..e3f2aee5 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminSetting.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "administrator") +public class EzySimpleAdminSetting implements EzyAdminSetting { + + @XmlElement(name = "username") + protected String username; + + @XmlElement(name = "password") + protected String password; + + @XmlElement(name = "api-access-token") + protected String apiAccessToken; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminsSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminsSetting.java new file mode 100644 index 00000000..2062b1b2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAdminsSetting.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "administrators") +@JsonIgnoreProperties({"adminsByName", "adminsByApiAccessToken"}) +public class EzySimpleAdminsSetting implements EzyAdminsSetting { + + protected Map adminsByName = new ConcurrentHashMap<>(); + protected Map adminsByApiAccessToken = new ConcurrentHashMap<>(); + + @XmlElement(name = "administrator") + public void setItem(EzySimpleAdminSetting item) { + adminsByName.put(item.getUsername(), item); + adminsByApiAccessToken.put(item.getApiAccessToken(), item); + } + + @Override + public List getAdmins() { + return new ArrayList<>(adminsByName.values()); + } + + @Override + public EzyAdminSetting getAdminByName(String username) { + return adminsByName.get(username); + } + + @Override + public EzyAdminSetting getAdminByApiAccessToken(String token) { + return adminsByApiAccessToken.get(token); + } + + @Override + public boolean containsAdminByName(String username) { + return adminsByName.containsKey(username); + } + + @Override + public boolean containsAdminByApiAccessToken(String token) { + return adminsByApiAccessToken.containsKey(token); + } + +} 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 new file mode 100644 index 00000000..6cda4108 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppSetting.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.setting; + +import static com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting.APPS; +import static com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting.ENTRIES; + +import java.nio.file.Paths; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyEventAppControllersImpl; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "application") +@JsonPropertyOrder({"id", "name", "entryLoader"}) +public class EzySimpleAppSetting extends EzyAbstractSetting implements EzyAppSetting { + + private static final AtomicInteger COUNTER = new AtomicInteger(0); + + protected EzyEventControllers newEventControllers() { + return EzyEventAppControllersImpl.builder().build(); + } + + @Override + protected AtomicInteger getIdCounter() { + return COUNTER; + } + + @Override + public String getLocation() { + return Paths.get(homePath, APPS, ENTRIES, name).toString(); + } +} 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 new file mode 100644 index 00000000..ffb8c8c5 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleAppsSetting.java @@ -0,0 +1,71 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "applications") +@JsonIgnoreProperties({"appsByIds", "appsByNames", "appNames", "appIds"}) +@JsonPropertyOrder({"size", "apps"}) +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) { + if(appsByNames.containsKey(name)) + return appsByNames.get(name); + throw new IllegalArgumentException("has no app with name: " + name); + } + + @Override + public EzySimpleAppSetting getAppById(Integer id) { + if(appsByIds.containsKey(id)) + return appsByIds.get(id); + throw new IllegalArgumentException("has no app with id: " + id); + } + + @Override + public int getSize() { + return apps.size(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleHttpSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleHttpSetting.java new file mode 100644 index 00000000..6a31eb8c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleHttpSetting.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "http") +public class EzySimpleHttpSetting implements EzyHttpSetting { + + @XmlElement(name = "port") + protected int port = 8080; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleLoggerSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleLoggerSetting.java new file mode 100644 index 00000000..539f3493 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleLoggerSetting.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.Set; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "logger") +public class EzySimpleLoggerSetting implements EzyLoggerSetting { + + @XmlElement(name = "ignored-commands") + protected EzySimpleIgnoredCommandsSetting ignoredCommands + = new EzySimpleIgnoredCommandsSetting(); + + @Getter + @ToString + @XmlAccessorType(XmlAccessType.NONE) + @XmlRootElement(name = "ignored-commands") + public static class EzySimpleIgnoredCommandsSetting implements EzyIgnoredCommandsSetting { + + protected Set commands = + Sets.newHashSet(EzyCommand.PING, EzyCommand.PONG); + + @XmlElement(name="command") + public void setCommand(String string) { + commands.add(EzyCommand.valueOf(string)); + } + } + +} 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 new file mode 100644 index 00000000..7891ab38 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginSetting.java @@ -0,0 +1,70 @@ +package com.tvd12.ezyfoxserver.setting; + +import static com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting.*; + +import java.nio.file.Paths; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyEventPluginControllersImpl; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "plugin") +@JsonPropertyOrder({"id", "name", "entryLoader", "priority", "listenEvents"}) +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 EzyEventControllers newEventControllers() { + return EzyEventPluginControllersImpl.builder().build(); + } + + @Override + protected AtomicInteger getIdCounter() { + return COUNTER; + } + + @Override + public String getLocation() { + return Paths.get(homePath, PLUGINS, name).toString(); + } + + @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 new file mode 100644 index 00000000..fcf7f572 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimplePluginsSetting.java @@ -0,0 +1,70 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "plugins") +@JsonIgnoreProperties({"pluginsByIds", "pluginsByNames", "pluginNames", "pluginIds"}) +@JsonPropertyOrder({"size", "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) { + if(pluginsByNames.containsKey(name)) + return pluginsByNames.get(name); + throw new IllegalArgumentException("has no plugin with name: " + name); + } + + @Override + public EzySimplePluginSetting getPluginById(Integer id) { + if(pluginsByIds.containsKey(id)) + return pluginsByIds.get(id); + throw new IllegalArgumentException("has no plugin with id: " + id); + } + + @Override + public int getSize() { + return plugins.size(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSessionManagementSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSessionManagementSetting.java new file mode 100644 index 00000000..ab36822c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSessionManagementSetting.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.tvd12.ezyfoxserver.constant.EzyMaxRequestPerSecondAction; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "session-management") +public class EzySimpleSessionManagementSetting implements EzySessionManagementSetting { + + @XmlElement(name = "session-max-idle-time") + protected long sessionMaxIdleTime = 30 * 1000; + + @XmlElement(name = "session-max-waiting-time") + protected long sessionMaxWaitingTime = 30 * 1000; + + @XmlElement(name = "session-allow-reconnect") + protected boolean sessionAllowReconnect = true; + + @XmlElement(name = "session-max-request-per-second") + protected EzySimpleEzyMaxRequestPerSecond sessionMaxRequestPerSecond = new EzySimpleEzyMaxRequestPerSecond(); + + @Getter + @ToString + @XmlAccessorType(XmlAccessType.NONE) + @XmlRootElement(name = "session-max-request-per-second") + public static class EzySimpleEzyMaxRequestPerSecond implements EzyMaxRequestPerSecond { + + @XmlElement(name = "value") + protected int value = 15; + + @XmlElement(name = "action") + protected EzyMaxRequestPerSecondAction action = EzyMaxRequestPerSecondAction.DROP_REQUEST; + } + +} 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 new file mode 100644 index 00000000..5a1a70f7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettings.java @@ -0,0 +1,95 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.util.Set; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "settings") +@JsonIgnoreProperties(ignoreUnknown = true) +public class EzySimpleSettings implements EzySettings { + + @XmlElement(name = "worker-pool-size") + protected int workerPoolSize = 30; + + @XmlElement(name = "http") + protected EzySimpleHttpSetting http = new EzySimpleHttpSetting(); + + @XmlElement(name = "socket") + protected EzySimpleSocketSetting socket = new EzySimpleSocketSetting(); + + @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 = "user-management") + protected EzySimpleUserManagementSetting userManagement = new EzySimpleUserManagementSetting(); + + @XmlElement(name = "session-management") + protected EzySimpleSessionManagementSetting sessionManagement = new EzySimpleSessionManagementSetting(); + + @XmlElement(name = "plugins") + protected EzySimplePluginsSetting plugins = new EzySimplePluginsSetting(); + + @XmlElement(name = "applications") + protected EzySimpleAppsSetting applications = new EzySimpleAppsSetting(); + + //==================== apps ================// + @JsonIgnore + public Set getAppNames() { + return applications.getAppNames(); + } + + @JsonIgnore + 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 ================// + @JsonIgnore + public Set getPluginNames() { + return plugins.getPluginNames(); + } + + @JsonIgnore + public Set getPluginIds() { + return plugins.getPluginIds(); + } + + public EzySimplePluginSetting getPluginByName(String name) { + return plugins.getPluginByName(name); + } + + public EzySimplePluginSetting getPluginById(Integer id) { + return plugins.getPluginById(id); + } + //=============================================// + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettingsReader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettingsReader.java new file mode 100644 index 00000000..172680b2 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSettingsReader.java @@ -0,0 +1,98 @@ +package com.tvd12.ezyfoxserver.setting; + +import java.nio.file.Paths; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzySimplXmlMapper; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzyXmlReader; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@Setter +public class EzySimpleSettingsReader + extends EzyLoggable + implements EzySettingsReader { + + protected String homePath; + protected ClassLoader classLoader; + + @Override + public EzySettings read() { + EzySettings settings = readSettings(); + postReadSettings(settings); + return settings; + } + + protected EzySettings readSettings() { + getLogger().info("read setting file: " + getSettingsFilePath()); + return newXmlReader().read(getSettingsFilePath(), EzySimpleSettings.class); + } + + protected void postReadSettings(EzySettings settings) { + updatePluginsSetting(settings.getPlugins()); + updateAppsSetting(settings.getApplications()); + } + + protected void updateAppsSetting(EzyAppsSetting apps) { + for(EzyAppSetting app : apps.getApps()) + ((EzyHomePathAware)app).setHomePath(homePath); + } + + protected void updatePluginsSetting(EzyPluginsSetting plugins) { + for(EzyPluginSetting plugin : plugins.getPlugins()) + ((EzyHomePathAware)plugin).setHomePath(homePath); + } + + protected EzyXmlReader newXmlReader() { + return EzySimplXmlMapper.builder() + .classLoader(classLoader) + .contextPath("com.tvd12.ezyfoxserver") + .build(); + } + + protected String getSettingsPath() { + return getPath(homePath, EzyFolderNamesSetting.SETTINGS); + } + + protected String getSettingsFilePath() { + return getPath(getSettingsPath(), EzyFileNames.SETTINGS); + } + + protected String getPath(String first, String... more) { + return Paths.get(first, more).toString(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected String homePath; + protected ClassLoader classLoader; + + public Builder homePath(String homePath) { + this.homePath = homePath; + return this; + } + + public Builder classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + @Override + public EzySettingsReader build() { + EzySimpleSettingsReader reader = newProduct(); + reader.setHomePath(homePath); + reader.setClassLoader(classLoader); + return reader; + } + + protected EzySimpleSettingsReader newProduct() { + return new EzySimpleSettingsReader(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSocketSetting.java new file mode 100644 index 00000000..d1ae5064 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSocketSetting.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "socket") +public class EzySimpleSocketSetting extends EzyAbstractSocketSetting implements EzySocketSetting { + + @XmlElement(name = "max-request-size") + protected int maxRequestSize; + + public EzySimpleSocketSetting() { + super(); + setPort(3005); + setMaxRequestSize(32768); + setCodecCreator("com.tvd12.ezyfoxserver.mapping.codec.MsgPackCodecCreator"); + } +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSslConfigSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSslConfigSetting.java new file mode 100644 index 00000000..15df5567 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleSslConfigSetting.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "ssl-config") +public class EzySimpleSslConfigSetting implements EzySslConfigSetting { + + @XmlElement(name = "file") + protected String file = "ssl-config.properties"; + + @XmlElement(name = "loader") + protected String loader = "com.tvd12.ezyfoxserver.mapping.ssl.EzySimpleSslConfigLoader"; + + @XmlElement(name = "context-factory-builder") + protected String contextFactoryBuilder = "com.tvd12.ezyfoxserver.mapping.ssl.EzySimpleSslContextFactoryBuilder"; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleUserManagementSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleUserManagementSetting.java new file mode 100644 index 00000000..904cd7c8 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleUserManagementSetting.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "user-management") +public class EzySimpleUserManagementSetting implements EzyUserManagementSetting { + + @XmlElement(name = "user-max-idle-time") + protected long userMaxIdleTime = 30 * 1000; + + @XmlElement(name = "max-session-per-user") + protected int maxSessionPerUser = 5; + + @XmlElement(name = "allow-guest-login") + protected boolean allowGuestLogin = true; + + @XmlElement(name = "guest-name-prefix") + protected String guestNamePrefix = "Guest#"; + + @XmlElement(name = "user-name-pattern") + protected String userNamePattern = "^[a-z0-9_.]{3,36}$"; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleWebSocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleWebSocketSetting.java new file mode 100644 index 00000000..888fd091 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySimpleWebSocketSetting.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement(name = "web-socket") +public class EzySimpleWebSocketSetting extends EzyAbstractSocketSetting implements EzyWebSocketSetting { + + @XmlElement(name = "ssl-port") + protected int sslPort; + + @XmlElement(name = "max-frame-size") + protected int maxFrameSize; + + @XmlElement(name = "ssl-active") + protected boolean sslActive; + + @XmlElement(name = "ssl-config") + protected EzySimpleSslConfigSetting sslConfig; + + public EzySimpleWebSocketSetting() { + super(); + setPort(2208); + setSslPort(2812); + setSslActive(false); + setMaxFrameSize(32678); + setSslConfig(new EzySimpleSslConfigSetting()); + setCodecCreator("com.tvd12.ezyfoxserver.mapping.codec.JacksonCodecCreator"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySocketSetting.java new file mode 100644 index 00000000..abcd9a60 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySocketSetting.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzySocketSetting extends EzyBaseSocketSetting { + + int getMaxRequestSize(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSetting.java new file mode 100644 index 00000000..67878d0a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzySslConfigSetting.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzySslConfigSetting { + + String getFile(); + + String getLoader(); + + String getContextFactoryBuilder(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyUserManagementSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyUserManagementSetting.java new file mode 100644 index 00000000..f2685111 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyUserManagementSetting.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyUserManagementSetting { + + long getUserMaxIdleTime(); + + int getMaxSessionPerUser(); + + boolean isAllowGuestLogin(); + + String getGuestNamePrefix(); + + String getUserNamePattern(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyWebSocketSetting.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyWebSocketSetting.java new file mode 100644 index 00000000..41bddaf6 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/EzyWebSocketSetting.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.setting; + +public interface EzyWebSocketSetting extends EzyBaseSocketSetting { + + int getSslPort(); + + int getMaxFrameSize(); + + boolean isSslActive(); + + EzySslConfigSetting getSslConfig(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/package-info.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/package-info.java new file mode 100644 index 00000000..ced29521 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/setting/package-info.java @@ -0,0 +1,16 @@ +@XmlSchema( + namespace = "http://www.tvd12.com/schema/ezyfox/settings", + elementFormDefault = XmlNsForm.QUALIFIED, + attributeFormDefault = XmlNsForm.UNQUALIFIED, + xmlns = { + @javax.xml.bind.annotation.XmlNs(prefix = "", namespaceURI = "http://www.tvd12.com/schema/ezyfox/settings") + } +) +/** + * @author tavandung12 + * + */ +package com.tvd12.ezyfoxserver.setting; + +import javax.xml.bind.annotation.XmlNsForm; +import javax.xml.bind.annotation.XmlSchema; diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfig.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfig.java new file mode 100644 index 00000000..d1794699 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfig.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.ssl; + +import com.tvd12.properties.file.annotation.Property; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimpleSslConfig implements EzySslConfig { + + @Property("ssl.keystore") + protected String keyStoreFile = "ssl/ssl-keystore.txt"; + + @Property("ssl.keystore_password") + protected String keyStorePasswordFile = "ssl/ssl-keystore-password.txt"; + + @Property("ssl.certificate_password") + protected String certificatePasswordFile = "ssl/ssl-certificate-password.txt"; + +} 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 new file mode 100644 index 00000000..3eab6e7b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslConfigLoader.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.ssl; + +import java.nio.file.Paths; + +import com.tvd12.ezyfoxserver.mapping.properties.EzyPropertiesFileReader; +import com.tvd12.ezyfoxserver.mapping.properties.EzySimplePropertiesFileMapper; + +public class EzySimpleSslConfigLoader implements EzySslConfigLoader { + + @Override + public EzySslConfig load(String filePath) { + EzySimpleSslConfig answer = readConfig(filePath); + String parent = getParentFolder(filePath); + answer.setKeyStoreFile(getPath(parent, answer.getKeyStoreFile())); + answer.setKeyStorePasswordFile(getPath(parent, answer.getKeyStorePasswordFile())); + answer.setCertificatePasswordFile(getPath(parent, answer.getCertificatePasswordFile())); + return answer; + } + + protected EzySimpleSslConfig readConfig(String filePath) { + return newPropertiesReader().read(filePath, EzySimpleSslConfig.class); + } + + protected EzyPropertiesFileReader newPropertiesReader() { + return EzySimplePropertiesFileMapper.builder() + .context(getClass()) + .build(); + } + + 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 new file mode 100644 index 00000000..686e4376 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactory.java @@ -0,0 +1,112 @@ +package com.tvd12.ezyfoxserver.ssl; + +import java.io.InputStream; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.SecureRandom; +import java.security.Security; + +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; + +import com.tvd12.ezyfoxserver.stream.EzyAnywayInputStreamLoader; +import com.tvd12.ezyfoxserver.stream.EzyInputStreamLoader; +import com.tvd12.ezyfoxserver.stream.EzyInputStreamReader; +import com.tvd12.ezyfoxserver.stream.EzySimpleInputStreamReader; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@Setter +public class EzySimpleSslContextFactory + extends EzyLoggable + implements EzySslContextFactory { + + protected SecureRandom secureRandom; + protected TrustManager[] trustManagers; + + private static final String SUNX509 = "SunX509"; + private static final String PROTOCOL = "TLS"; + private static final String JKS_KEYSTORE = "JKS"; + private static final String ALGORITHM_PROPERTY = "ssl.KeyManagerFactory.algorithm"; + + @Override + public SSLContext newSslContext(EzySslConfig config) throws Exception { + return tryNewSslContext(config); + } + + protected SSLContext tryNewSslContext(EzySslConfig config) throws Exception { + InputStream keyStoreStream = loadKeyStoreStream(config.getKeyStoreFile()); + char[] keyStorePassword = getPassword(config.getKeyStorePasswordFile()); + char[] certificatePassword = getPassword(config.getCertificatePasswordFile()); + KeyStore keyStore = newKeyStore(config); + loadKeyStore(keyStore, keyStoreStream, keyStorePassword); + + // Set up key manager factory to use our key store + KeyManagerFactory keyManagerFactory = newKeyManagerFactory(config); + initKeyManagerFactory(keyManagerFactory, keyStore, certificatePassword); + + // Initialize the SSLContext to work with our key managers. + SSLContext context = SSLContext.getInstance(getProtocol()); + context.init(keyManagerFactory.getKeyManagers(), trustManagers, secureRandom); + return context; + } + + protected void initKeyManagerFactory( + KeyManagerFactory factory, KeyStore keyStore, char[] password) + throws Exception { + factory.init(keyStore, password); + } + + protected KeyManagerFactory newKeyManagerFactory(EzySslConfig config) + throws Exception { + return KeyManagerFactory.getInstance(getAlgorithm(config)); + } + + protected void loadKeyStore(KeyStore keyStore, InputStream stream, char[] password) + throws Exception { + keyStore.load(stream, password); + } + + protected char[] getPassword(String file) { + InputStream stream = newInputStreamLoader().load(file); + return newInputStreamReader().readChars(stream, "UTF-8"); + } + + protected InputStream loadKeyStoreStream(String file) { + return newInputStreamLoader().load(file); + } + + protected KeyStore newKeyStore(EzySslConfig config) throws KeyStoreException { + return KeyStore.getInstance(getKeyStoreType()); + } + + protected String getKeyStoreType() { + return JKS_KEYSTORE; + } + + protected String getProtocol() { + return PROTOCOL; + } + + protected String getAlgorithm(EzySslConfig config) { + String algorithm = Security.getProperty(getAlgorithmProperty()); + return algorithm != null ? algorithm : SUNX509; + } + + protected String getAlgorithmProperty() { + return ALGORITHM_PROPERTY; + } + + protected EzyInputStreamLoader newInputStreamLoader() { + return EzyAnywayInputStreamLoader.builder() + .context(getClass()) + .build(); + } + + protected EzyInputStreamReader newInputStreamReader() { + return EzySimpleInputStreamReader.builder() + .build(); + } +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactoryBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactoryBuilder.java new file mode 100644 index 00000000..99ffd5de --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySimpleSslContextFactoryBuilder.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.ssl; + +import java.security.SecureRandom; + +import javax.net.ssl.TrustManager; + +public class EzySimpleSslContextFactoryBuilder + implements EzySslContextFactoryBuilder { + + @Override + public EzySslContextFactory build() { + EzySimpleSslContextFactory factory = new EzySimpleSslContextFactory(); + factory.setSecureRandom(getSecureRandom()); + factory.setTrustManagers(getTrustManagers()); + return factory; + } + + protected TrustManager[] getTrustManagers() { + return new EzySslTrustManagerFactory().engineGetTrustManagers(); + } + + protected SecureRandom getSecureRandom() { + return new SecureRandom(); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfig.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfig.java new file mode 100644 index 00000000..3caee29c --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfig.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.ssl; + +public interface EzySslConfig { + + String getKeyStoreFile(); + + String getKeyStorePasswordFile(); + + String getCertificatePasswordFile(); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfigLoader.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfigLoader.java new file mode 100644 index 00000000..00b66ec4 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslConfigLoader.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.ssl; + +import com.tvd12.ezyfoxserver.function.EzyLoader; + +public interface EzySslConfigLoader extends EzyLoader { + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactory.java new file mode 100644 index 00000000..05852610 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactory.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.ssl; + +import javax.net.ssl.SSLContext; + +public interface EzySslContextFactory { + + SSLContext newSslContext(EzySslConfig config) throws Exception; + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactoryBuilder.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactoryBuilder.java new file mode 100644 index 00000000..1841bc6a --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextFactoryBuilder.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.ssl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public interface EzySslContextFactoryBuilder + extends EzyBuilder { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextInitializer.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextInitializer.java new file mode 100644 index 00000000..bcf82a5b --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslContextInitializer.java @@ -0,0 +1,80 @@ +package com.tvd12.ezyfoxserver.ssl; + +import java.nio.file.Paths; + +import javax.net.ssl.SSLContext; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting; +import com.tvd12.ezyfoxserver.setting.EzySslConfigSetting; +import com.tvd12.ezyfoxserver.util.EzyReturner; + +public class EzySslContextInitializer { + + protected String homeFolderPath; + protected EzySslConfigSetting sslConfig; + + protected EzySslContextInitializer(Builder builder) { + this.sslConfig = builder.sslConfig; + this.homeFolderPath = builder.homeFolderPath; + } + + public SSLContext init() { + return newSslContext(); + } + + protected SSLContext newSslContext() { + EzySslConfig config = loadSslConfig(); + EzySslContextFactoryBuilder builder = newSslContextFactoryBuilder(); + EzySslContextFactory factory = builder.build(); + return EzyReturner.returnWithException(() -> factory.newSslContext(config)); + } + + protected EzySslConfig loadSslConfig() { + String file = getSslConfigFile(); + EzySslConfigLoader loader = newSslConfigLoader(); + return loader.load(file); + } + + protected EzySslContextFactoryBuilder newSslContextFactoryBuilder() { + return EzyClasses.newInstance(sslConfig.getContextFactoryBuilder()); + } + + protected EzySslConfigLoader newSslConfigLoader() { + return EzyClasses.newInstance(sslConfig.getLoader()); + } + + protected String getSslConfigFile() { + return getPath(homeFolderPath, EzyFolderNamesSetting.SETTINGS, sslConfig.getFile()); + } + + protected String getPath(String first, String... more) { + return Paths.get(first, more).toString(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected String homeFolderPath; + protected EzySslConfigSetting sslConfig; + + public Builder homeFolderPath(String homeFolderPath) { + this.homeFolderPath = homeFolderPath; + return this; + } + + public Builder sslConfig(EzySslConfigSetting sslConfig) { + this.sslConfig = sslConfig; + return this; + } + + @Override + public EzySslContextInitializer build() { + return new EzySslContextInitializer(this); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslTrustManagerFactory.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslTrustManagerFactory.java new file mode 100644 index 00000000..5780eb51 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/ssl/EzySslTrustManagerFactory.java @@ -0,0 +1,69 @@ +package com.tvd12.ezyfoxserver.ssl; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509TrustManager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EzySslTrustManagerFactory extends TrustManagerFactorySpi { + + private Logger logger = LoggerFactory.getLogger(getClass()); + + private static final TrustManager TRUST_MANAGER = new X509TrustManager() { + + private Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public X509Certificate[] getAcceptedIssuers() { + getLogger().debug("ssl: get accepted issuers"); + return new X509Certificate[0]; + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + getLogger().debug("ssl: check client trusted, chain = {}, authType = {}", chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) + throws CertificateException { + getLogger().debug("ssl: check server trusted, chain = {}, authType = {}", chain, authType); + } + + protected Logger getLogger() { + return logger; + } + }; + + @Override + protected TrustManager[] engineGetTrustManagers() { + getLogger().debug("ssl: engine get trust managers"); + return new TrustManager[]{TRUST_MANAGER}; + } + + @Override + protected void engineInit(KeyStore keystore) + throws KeyStoreException { + getLogger().debug("ssl: engine init, keystore = {}", keystore); + } + + @Override + protected void engineInit(ManagerFactoryParameters managerFactoryParameters) + throws InvalidAlgorithmParameterException { + getLogger().debug("ssl: engine init, parameters = {}", managerFactoryParameters); + } + + protected Logger getLogger() { + return logger; + } +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/util/EzyBannerPrinter.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/util/EzyBannerPrinter.java new file mode 100644 index 00000000..5fa2ffc4 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/util/EzyBannerPrinter.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.util; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.io.IOUtils; + +import com.tvd12.ezyfoxserver.stream.EzyClassPathInputStreamLoader; + +public class EzyBannerPrinter { + + public String getBannerString() { + return new String(getBannerBytes()); + } + + protected byte[] getBannerBytes() { + return getBannerBytes(getBannerInputStream()); + } + + protected byte[] getBannerBytes(InputStream stream) { + try { + return IOUtils.toByteArray(stream); + } catch (IOException e) { + return new byte[0]; + } + } + + protected InputStream getBannerInputStream() { + return EzyClassPathInputStreamLoader.builder() + .context(getClass()) + .build() + .load("ezyfox-banner.txt"); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAbstractEventControllers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAbstractEventControllers.java index 91dac7dd..8f720aef 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAbstractEventControllers.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAbstractEventControllers.java @@ -3,9 +3,7 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.tvd12.ezyfoxserver.appcontroller.EzyServerReadyController; import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.constant.EzyEventType; import com.tvd12.ezyfoxserver.controller.EzyEventController; public abstract class EzyAbstractEventControllers implements EzyEventControllers { @@ -40,7 +38,7 @@ protected Map newControllers() { @SuppressWarnings("rawtypes") protected void addControllers(Map answer) { - answer.put(EzyEventType.SERVER_READY, new EzyServerReadyController()); + // add some controllers } public abstract EzyEventControllers build(); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAppUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAppUserManager.java new file mode 100644 index 00000000..452618d7 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyAppUserManager.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.wrapper; + +public interface EzyAppUserManager extends EzyUserAddableManager { +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyControllers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyControllers.java deleted file mode 100644 index a6c32948..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyControllers.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.tvd12.ezyfoxserver.wrapper; - -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.controller.EzyController; -import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; - -public interface EzyControllers { - - @SuppressWarnings("rawtypes") - EzyController getController(EzyConstant cmd); - - @SuppressWarnings("rawtypes") - EzyInterceptor getInterceptor(EzyConstant cmd); -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventPluginsMapper.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventPluginsMapper.java new file mode 100644 index 00000000..c7596e3d --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyEventPluginsMapper.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; + +public interface EzyEventPluginsMapper { + + Set getPlugins(EzyConstant eventType); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyManagers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyManagers.java index 29da71d2..b2081fe2 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyManagers.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyManagers.java @@ -2,8 +2,13 @@ public interface EzyManagers { + /** + * Stop destroyable managers + */ + void stopManagers(); + /** - * Start start able managers + * Start startable managers */ void startManagers(); @@ -21,6 +26,7 @@ public interface EzyManagers { * @param clazz the manager interface clazz * @param instance the manager instance */ - void addManager(Class clazz, T instance); + @SuppressWarnings("rawtypes") + void addManager(Class clazz, Object instance); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyRequestMappers.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyRequestMappers.java new file mode 100644 index 00000000..4d34b36f --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyRequestMappers.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyData; + +public interface EzyRequestMappers { + + T toObject(EzyConstant cmd, EzyData data); + +} 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 new file mode 100644 index 00000000..7af4546d --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerControllers.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; + +public interface EzyServerControllers { + + @SuppressWarnings("rawtypes") + EzyController getController(EzyConstant cmd); + + @SuppressWarnings("rawtypes") + EzyInterceptor getInterceptor(EzyConstant cmd); +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerUserManager.java new file mode 100644 index 00000000..ce38bf51 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyServerUserManager.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyUserRemoveReason; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzyServerUserManager 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 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); + + /** + * Remove user + * + * @param user the user + * @param reason the reason + */ + void removeUser(EzyUser user, EzyUserRemoveReason reason); + + /** + * + * Find user by the old session and update user to new session + * + * @param user the user + * @param newSession the new session + * @return the updated user + */ + EzyUser findAndUpdateUser(EzySession current, EzySession update); + +} 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 117306a1..267b182c 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 @@ -1,10 +1,20 @@ package com.tvd12.ezyfoxserver.wrapper; +import java.util.List; +import java.util.Set; + import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.entity.EzySession; public interface EzySessionManager { + /** + * Recognize that the session has logged in + * + * @param session the session + */ + void addLoggedInSession(S session); + /** * Check contains session mapped to token or not * @@ -36,4 +46,25 @@ public interface EzySessionManager { */ void returnSession(S session, EzyConstant reason); + /** + * Get all sessions + * + * @return all sessions + */ + Set getAllSessions(); + + /** + * Get all alive sessions + * + * @return all alive sessions + */ + List getAliveSessions(); + + /** + * Get logged in sessions + * + * @return all logged in sessions + */ + List getLoggedInSessions(); + } 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 c4abf135..1c088b17 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 @@ -2,41 +2,58 @@ import java.security.KeyPair; import java.util.ArrayList; -import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyLockName; import com.tvd12.ezyfoxserver.constant.EzySessionRemoveReason; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyHasSessionDelegate; import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.factory.EzySessionFactory; +import com.tvd12.ezyfoxserver.io.EzyLists; import com.tvd12.ezyfoxserver.pattern.EzyObjectPool; import com.tvd12.ezyfoxserver.sercurity.EzyKeysGenerator; -import com.tvd12.ezyfoxserver.service.EzySessionTokenGeneration; -import com.tvd12.ezyfoxserver.service.impl.EzySessionTokenGenerationImpl; +import com.tvd12.ezyfoxserver.service.EzySessionTokenGenerator; +import com.tvd12.ezyfoxserver.service.impl.EzySimpleSessionTokenGenerator; +import com.tvd12.ezyfoxserver.util.EzyIfElse; +import com.tvd12.ezyfoxserver.util.EzyProcessor; import com.tvd12.ezyfoxserver.util.EzyTimes; public class EzySimpleSessionManager extends EzyObjectPool implements EzySessionManager { - protected EzySessionTokenGeneration tokenGeneration; - protected ConcurrentHashMap sessionsByToken; + protected final EzySessionTokenGenerator tokenGenerator; + protected final ScheduledExecutorService idleValidationService; + protected final ConcurrentHashMap loggedInSession = new ConcurrentHashMap<>(); + protected final ConcurrentHashMap sessionsByToken = new ConcurrentHashMap<>(); + + protected static final AtomicInteger COUNTER = new AtomicInteger(0); protected EzySimpleSessionManager(Builder builder) { super(builder); + this.initializeObjects(); + this.tokenGenerator = builder.getSessionTokenGenerator(); + this.idleValidationService = EzyExecutors.newScheduledThreadPool(3, "session-manager"); } - @SuppressWarnings("rawtypes") @Override - protected void initComponents(AbstractBuilder builder) { - super.initComponents(builder); - sessionsByToken = new ConcurrentHashMap<>(); - tokenGeneration = new EzySessionTokenGenerationImpl(); + public void addLoggedInSession(S session) { + loggedInSession.put(session.getReconnectToken(), session); } @Override public boolean containsSession(String token) { - return sessionsByToken.contains(token); + return sessionsByToken.containsKey(token); } @Override @@ -46,84 +63,141 @@ public void returnSession(S session) { @Override public void returnSession(S session, EzyConstant reason) { - unmapSession(session); - returnObject(session); - notifySessionReturned(session, reason); - clearSession(session); - getLogger().info("return session {}, remain = {}", session, borrowedObjects.size()); + checkToReturnSession(session, reason); + } + + protected void doReturnSession(S session, EzyConstant reason) { + unmapSession(session); + notifySessionReturned(session, reason); + clearSession(session); + returnObject(session); + getLogger().debug("return session, remain sessions = {}", borrowedObjects.size()); + } + + protected void checkToReturnSession(S session, EzyConstant reason) { + if(shouldReturnSession(session)) + returnSessionWithLock(session, reason); + } + + protected void returnSessionWithLock(S session, EzyConstant reason) { + Lock lock = session.getLock(EzyLockName.REMOVE); + EzyProcessor.processWithTryLock(() -> doReturnSession(session, reason), lock); + } + + protected boolean shouldReturnSession(S session) { + return session != null && containsSession(session.getReconnectToken()); } protected void unmapSession(S session) { sessionsByToken.remove(session.getReconnectToken()); + loggedInSession.remove(session.getReconnectToken()); } protected void clearSession(S session) { - session.setDelegate(null); - session.setActivated(false); - session.setLoggedIn(false); + getLogger().info("session {} inactive", session.getClientAddress()); + session.destroy(); } protected void notifySessionReturned(S session, EzyConstant reason) { - if(reason != null) - tryNotifySessionReturned(session, reason); + EzyIfElse.withIf(reason != null, () -> tryNotifySessionReturned(session, reason)); } protected void tryNotifySessionReturned(S session, EzyConstant reason) { try { - session.getDelegate().onSessionReturned(reason); + EzyHasSessionDelegate hasDelegate = (EzyHasSessionDelegate)session; + hasDelegate.getDelegate().onSessionReturned(reason); } catch(Exception e) { getLogger().debug("notify session returned error", e); } } - protected S borrowSession() { + @SuppressWarnings("unchecked") + protected S borrowSession(EzyConnectionType type) { KeyPair keyPair = newKeyPair(); - S session = borrowObject(); - session.setActivated(true); - session.setReconnectToken(newTokenSession()); + EzyAbstractSession session = (EzyAbstractSession)borrowObject(); + session.setLoggedIn(false); + session.setName("Session#" + COUNTER.incrementAndGet()); + session.setConnectionType(type); + session.setReconnectToken(newSessionToken()); session.setCreationTime(System.currentTimeMillis()); session.setPublicKey(keyPair.getPublic().getEncoded()); session.setPrivateKey(keyPair.getPrivate().getEncoded()); - sessionsByToken.putIfAbsent(session.getReconnectToken(), session); - getLogger().info("borrow session {}, sessions size = {}", session, borrowedObjects.size()); - return session; + + session.setCreationTime(System.currentTimeMillis()); + session.setLastActivityTime(System.currentTimeMillis()); + session.setLastReadTime(System.currentTimeMillis()); + session.setLastWriteTime(System.currentTimeMillis()); + session.setActivated(true); + S complete = (S)session; + sessionsByToken.put(complete.getReconnectToken(), complete); + getLogger().debug("borrow session, sessions size = {}", borrowedObjects.size()); + return complete; } @Override public S getSession(String token) { return sessionsByToken.get(token); } - + @Override - protected void removeStaleObjects() { - removeUnloggedInSessions(); + public Set getAllSessions() { + Set all = new HashSet<>(); + all.addAll(getRemainObjects()); + all.addAll(getBorrowedObjects()); + return all; } + @Override + public List getAliveSessions() { + return new ArrayList<>(sessionsByToken.values()); + }; + + @Override + public List getLoggedInSessions() { + return new ArrayList<>(loggedInSession.values()); + } + @Override public void start() throws Exception { super.start(); + startIdleValidationService(); getLogger().debug("start session manager"); } - protected void removeUnloggedInSessions() { - removeUnloggedInSessions(new ArrayList<>(borrowedObjects)); + protected void startIdleValidationService() { + idleValidationService.scheduleAtFixedRate( + this::validateIdleSessions, 3000, 1000, TimeUnit.MILLISECONDS); } - protected void removeUnloggedInSessions(Collection sessions) { - sessions.forEach(this::removeUnloggedInSession); + protected void validateIdleSessions() { + for(S session : getLoggedInSessions()) + if(isIdleSession(session)) + returnSession(session, EzySessionRemoveReason.IDLE); } - protected void removeUnloggedInSession(S session) { - if(isUnloggedInSession(session)) - returnSession(session, EzySessionRemoveReason.NOT_LOGGED_IN); - + protected boolean isIdleSession(S session) { + return session.getMaxIdleTime() + < (System.currentTimeMillis() - session.getLastReadTime()); + } + + @Override + protected boolean isStaleObject(S session) { + return session.isActivated() && isUnloggedInSession(session); + } + + @Override + protected void removeStaleObject(S session) { + returnSession(session, EzySessionRemoveReason.NOT_LOGGED_IN); + } + + @Override + protected List getCanBeStaleObjects() { + return EzyLists.newArrayList(getBorrowedObjects(), getLoggedInSessions()); } protected boolean isUnloggedInSession(EzySession session) { - if(session.isLoggedIn()) - return false; - return getSessionRemainWaitingTime(session) <= 0; + return session.isLoggedIn() ? false : getSessionRemainWaitingTime(session) <= 0; } protected long getSessionRemainWaitingTime(EzySession session) { @@ -131,42 +205,43 @@ protected long getSessionRemainWaitingTime(EzySession session) { session.getMaxWaitingTime(), session.getCreationTime()); } - protected String newTokenSession() { - return tokenGeneration.generate(); + protected String newSessionToken() { + return tokenGenerator.generate(); } protected KeyPair newKeyPair() { return EzyKeysGenerator.builder() - .keyLength(512) + .keysize(512) .algorithm("RSA") .build().generate(); } + + @Override + protected void tryShutdown() { + super.tryShutdown(); + this.idleValidationService.shutdown(); + } public abstract static class Builder - extends AbstractBuilder> { + extends EzyObjectPool.Builder> { - protected abstract EzySessionFactory newSessionFactory(); - + protected EzySessionTokenGenerator tokenGenerator; + @Override protected String getProductName() { - return EzySessionManager.class.getSimpleName(); + return "session-manager"; } - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected EzySimpleSessionManager newProduct() { - return new EzySimpleSessionManager(this); + public Builder tokenGenerator(EzySessionTokenGenerator generator) { + this.tokenGenerator = generator; + return this; } - @Override - protected void prepare() { - super.prepare(); - this.objectFactory = newSessionFactory(); + protected EzySessionTokenGenerator getSessionTokenGenerator() { + return tokenGenerator != null ? tokenGenerator : new EzySimpleSessionTokenGenerator(); } - @Override - public EzySimpleSessionManager build() { - return (EzySimpleSessionManager) super.build(); - } + public abstract EzySimpleSessionManager build(); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserAddableManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserAddableManager.java new file mode 100644 index 00000000..868d3131 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserAddableManager.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public class EzySimpleUserAddableManager + extends EzySimpleUserManager + implements EzyUserAddable { + + @Override + public EzyUser addUser(EzyUser user) { + // put user if absent + EzyUser old = usersByName.putIfAbsent(user.getName(), user); + + // check if user added then return added user + if(old != null) return old; + + getLogger().info("add user {}, user count = {}", user.getName(), usersByName.size()); + + // map user with id + return usersById.putIfAbsent(user.getId(), user); + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserManager.java new file mode 100644 index 00000000..ed219771 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzySimpleUserManager.java @@ -0,0 +1,63 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleUserManager extends EzyLoggable implements EzyUserManager { + + protected final ConcurrentHashMap locks = new ConcurrentHashMap<>(); + protected final ConcurrentHashMap usersById = new ConcurrentHashMap<>(); + protected final ConcurrentHashMap usersByName = new ConcurrentHashMap<>(); + + @Override + public EzyUser getUser(long userId) { + return usersById.get(userId); + } + + @Override + public EzyUser getUser(String username) { + return usersByName.get(username); + } + + @Override + public List getUserList() { + return new ArrayList<>(usersById.values()); + } + + @Override + public boolean containsUser(long userId) { + return usersById.containsKey(userId); + } + + @Override + public boolean containsUser(String username) { + return usersByName.containsKey(username); + } + + @Override + public EzyUser removeUser(EzyUser user) { + if(user != null) { + locks.remove(user.getName()); + usersById.remove(user.getId()); + usersByName.remove(user.getName()); + getLogger().info("remove user {}, remain users = {}", user.getName(), usersById.size()); + } + return user; + } + + @Override + public Lock getLock(String username) { + return locks.computeIfAbsent(username, k -> new ReentrantLock()); + } + + @Override + public void removeLock(String username) { + locks.remove(username); + } +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddable.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddable.java new file mode 100644 index 00000000..4dfce655 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddable.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.wrapper; + +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public interface EzyUserAddable { + + EzyUser addUser(EzyUser user); + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddableManager.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddableManager.java new file mode 100644 index 00000000..7fc23161 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyUserAddableManager.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.wrapper; + +public interface EzyUserAddableManager extends EzyUserManager, EzyUserAddable { + +} 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 535659aa..93f82056 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 @@ -1,17 +1,12 @@ package com.tvd12.ezyfoxserver.wrapper; -import com.tvd12.ezyfoxserver.entity.EzySession; +import java.util.List; +import java.util.concurrent.locks.Lock; + import com.tvd12.ezyfoxserver.entity.EzyUser; public interface EzyUserManager { - - /** - * Add user - * - * @param user the user - */ - void addUser(EzyUser user); - + /** * Get user by id * @@ -29,12 +24,11 @@ public interface EzyUserManager { EzyUser getUser(String username); /** - * Get user by id + * Get users as list * - * @param session the user session - * @return the user + * @return The users as list */ - EzyUser getUser(EzySession session); + List getUserList(); /** * Check whether contains user or not @@ -53,19 +47,26 @@ public interface EzyUserManager { boolean containsUser(String username); /** - * Check whether contains user or not + * Remove user * - * @param session the user session - * @return true or false + * @param user the user */ - boolean containsUser(EzySession session); + EzyUser removeUser(EzyUser user); /** - * Remove user + * Get lock mapped to username * - * @param user the user + * @param username the username + * @return the lock */ - void removeUser(EzyUser user); + Lock getLock(String username); + + /** + * Remove lock mapped to username + * + * @param username the username + */ + void removeLock(String username); /** * Check whether contains user or not @@ -82,8 +83,8 @@ default boolean containsUser(EzyUser user) { * * @param userId the user id */ - default void removeUser(long userId) { - removeUser(getUser(userId)); + default EzyUser removeUser(long userId) { + return removeUser(getUser(userId)); } /** @@ -91,16 +92,8 @@ default void removeUser(long userId) { * * @param username the user name */ - default void removeUser(String username) { - removeUser(getUser(username)); + default EzyUser removeUser(String username) { + return removeUser(getUser(username)); } - /** - * Remove user by session - * - * @param session the user session - */ - default void removeUser(EzySession session) { - removeUser(getUser(session)); - } } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyAppUserManagerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyAppUserManagerImpl.java new file mode 100644 index 00000000..7120c91d --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyAppUserManagerImpl.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.wrapper.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzySimpleUserAddableManager; + +public class EzyAppUserManagerImpl + extends EzySimpleUserAddableManager + implements EzyAppUserManager { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + @Override + public EzyAppUserManager build() { + return new EzyAppUserManagerImpl(); + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyControllersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyControllersImpl.java deleted file mode 100644 index 9ab53bfd..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyControllersImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.tvd12.ezyfoxserver.wrapper.impl; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.tvd12.ezyfoxserver.constant.EzyCommand; -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.controller.EzyAccessAppController; -import com.tvd12.ezyfoxserver.controller.EzyController; -import com.tvd12.ezyfoxserver.controller.EzyHandShakeController; -import com.tvd12.ezyfoxserver.controller.EzyLoginController; -import com.tvd12.ezyfoxserver.controller.EzyRequestAppController; -import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; -import com.tvd12.ezyfoxserver.interceptor.EzyServerUserInterceptor; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; - -public class EzyControllersImpl implements EzyControllers { - - @SuppressWarnings("rawtypes") - protected Map controllers; - - @SuppressWarnings("rawtypes") - protected Map interceptors; - - protected EzyControllersImpl(Builder builder) { - this.controllers = builder.newControllers(); - this.interceptors = builder.newInterceptors(); - } - - @SuppressWarnings("rawtypes") - @Override - public EzyController getController(EzyConstant cmd) { - return controllers.get(cmd); - } - - @SuppressWarnings("rawtypes") - @Override - public EzyInterceptor getInterceptor(EzyConstant cmd) { - return interceptors.get(cmd); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - @SuppressWarnings("rawtypes") - protected Map newControllers() { - Map answer = new ConcurrentHashMap<>(); - answer.put(EzyCommand.HAND_SHAKE, new EzyHandShakeController()); - answer.put(EzyCommand.LOGIN, new EzyLoginController()); - answer.put(EzyCommand.ACCESS_APP, new EzyAccessAppController()); - answer.put(EzyCommand.REQUEST_APP, new EzyRequestAppController()); - return answer; - } - - @SuppressWarnings("rawtypes") - protected Map newInterceptors() { - Map answer = new ConcurrentHashMap<>(); - answer.put(EzyCommand.HAND_SHAKE, EzyInterceptor.EMPTY); - answer.put(EzyCommand.LOGIN, EzyInterceptor.EMPTY); - answer.put(EzyCommand.ACCESS_APP, new EzyServerUserInterceptor<>()); - answer.put(EzyCommand.REQUEST_APP, new EzyServerUserInterceptor<>()); - return answer; - } - - public EzyControllers build() { - return new EzyControllersImpl(this); - } - } - -} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventAppControllersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventAppControllersImpl.java index 932cfcab..2b8d5304 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventAppControllersImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventAppControllersImpl.java @@ -2,8 +2,10 @@ import java.util.Map; +import com.tvd12.ezyfoxserver.appcontroller.EzyServerReadyController; import com.tvd12.ezyfoxserver.appcontroller.EzyUserDisconnectController; -import com.tvd12.ezyfoxserver.appcontroller.EzyUserRequestController; +import com.tvd12.ezyfoxserver.appcontroller.EzyUserReconnectController; +import com.tvd12.ezyfoxserver.appcontroller.EzyUserRequestAppController; import com.tvd12.ezyfoxserver.constant.EzyConstant; import com.tvd12.ezyfoxserver.constant.EzyEventType; import com.tvd12.ezyfoxserver.controller.EzyEventController; @@ -26,7 +28,9 @@ public static class Builder extends EzyAbstractEventControllers.Builder { @Override protected void addControllers(Map answer) { super.addControllers(answer); - answer.put(EzyEventType.USER_REQUEST, new EzyUserRequestController()); + answer.put(EzyEventType.SERVER_READY, new EzyServerReadyController()); + answer.put(EzyEventType.USER_REQUEST, new EzyUserRequestAppController()); + answer.put(EzyEventType.USER_RECONNECT, new EzyUserReconnectController()); answer.put(EzyEventType.USER_DISCONNECT, new EzyUserDisconnectController()); } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginControllersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginControllersImpl.java index f94f9ace..000273ff 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginControllersImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginControllersImpl.java @@ -1,5 +1,12 @@ package com.tvd12.ezyfoxserver.wrapper.impl; +import java.util.Map; + +import com.tvd12.ezyfoxserver.plugincontroller.EzyServerReadyController; +import com.tvd12.ezyfoxserver.plugincontroller.EzyUserRequestPluginController; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.controller.EzyEventController; import com.tvd12.ezyfoxserver.wrapper.EzyAbstractEventControllers; import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; @@ -15,6 +22,14 @@ public static Builder builder() { public static class Builder extends EzyAbstractEventControllers.Builder { + @SuppressWarnings("rawtypes") + @Override + protected void addControllers(Map answer) { + super.addControllers(answer); + answer.put(EzyEventType.SERVER_READY, new EzyServerReadyController()); + answer.put(EzyEventType.USER_REQUEST, new EzyUserRequestPluginController()); + } + @Override public EzyEventControllers build() { return new EzyEventPluginControllersImpl(this); diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginsMapperImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginsMapperImpl.java new file mode 100644 index 00000000..9af46a76 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyEventPluginsMapperImpl.java @@ -0,0 +1,54 @@ +package com.tvd12.ezyfoxserver.wrapper.impl; + +import java.util.Set; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.setting.EzyPluginsSetting; +import com.tvd12.ezyfoxserver.util.EzyHashMapSet; +import com.tvd12.ezyfoxserver.util.EzyMapSet; +import com.tvd12.ezyfoxserver.wrapper.EzyEventPluginsMapper; + +public class EzyEventPluginsMapperImpl implements EzyEventPluginsMapper { + + protected final EzyMapSet eventsPluginss; + + public EzyEventPluginsMapperImpl() { + this.eventsPluginss = new EzyHashMapSet<>(); + } + + @Override + public Set getPlugins(EzyConstant eventType) { + return eventsPluginss.getItems(eventType); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected EzyPluginsSetting plugins; + + public Builder plugins(EzyPluginsSetting plugins) { + this.plugins = plugins; + return this; + } + + @Override + public EzyEventPluginsMapper build() { + EzyEventPluginsMapperImpl answer = new EzyEventPluginsMapperImpl(); + for(EzyPluginSetting p : plugins.getPlugins()) { + for(EzyConstant e : p.getListenEvents().getEvents()) { + answer.eventsPluginss.addItems(e, p); + } + answer.eventsPluginss.addItems(EzyEventType.SERVER_READY, p); + answer.eventsPluginss.addItems(EzyEventType.USER_REQUEST, p); + } + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyManagersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyManagersImpl.java index be3d4f11..a066c410 100644 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyManagersImpl.java +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyManagersImpl.java @@ -3,10 +3,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.tvd12.ezyfoxserver.entity.EzyStartable; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; import com.tvd12.ezyfoxserver.wrapper.EzyManagers; -import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; public class EzyManagersImpl extends EzyLoggable implements EzyManagers { @@ -18,7 +19,7 @@ protected EzyManagersImpl(Builder builder) { /* * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyManagers#getManager(java.lang.Class) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyManagers#getManager(java.lang.Class) */ @SuppressWarnings("unchecked") @Override @@ -28,22 +29,37 @@ public T getManager(Class clazz) { /* * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyManagers#addManager(java.lang.Class, java.lang.Object) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyManagers#addManager(java.lang.Class, java.lang.Object) */ - @Override - public void addManager(Class clazz, T instance) { + @SuppressWarnings("rawtypes") + @Override + public void addManager(Class clazz, Object instance) { managers.put(clazz, instance); } + @Override + public void stopManagers() { + managers.values().forEach(this::stopManager); + } + /* * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyManagers#startManagers() + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyManagers#startManagers() */ @Override public void startManagers() { managers.values().forEach(this::startManager); } + protected void stopManager(Object manager) { + try { + if(manager instanceof EzyDestroyable) + ((EzyDestroyable) manager).destroy(); + } catch (Exception e) { + getLogger().error("can not stop manager " + manager, e); + } + } + protected void startManager(Object manager) { try { if(manager instanceof EzyStartable) @@ -61,7 +77,7 @@ public static class Builder { protected Map newManagers() { Map answer = new ConcurrentHashMap<>(); - answer.put(EzyUserManager.class, EzyUserManagerImpl.builder().build()); + answer.put(EzyServerUserManager.class, EzyServerUserManagerImpl.builder().build()); return answer; } diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyRequestMappersImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyRequestMappersImpl.java new file mode 100644 index 00000000..0849a59e --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyRequestMappersImpl.java @@ -0,0 +1,108 @@ +package com.tvd12.ezyfoxserver.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleAccessAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleLoginParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimplePingParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestPluginParams; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; + +public class EzyRequestMappersImpl implements EzyRequestMappers { + + @SuppressWarnings("rawtypes") + private final Map appliers; + + protected EzyRequestMappersImpl(Builder builder) { + this.appliers = builder.newAppliers(); + } + + @SuppressWarnings("unchecked") + @Override + public T toObject(EzyConstant cmd, EzyData data) { + return (T) appliers.get(cmd).apply(data); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyRequestMappers build() { + return new EzyRequestMappersImpl(this); + } + + @SuppressWarnings("rawtypes") + protected Map newAppliers() { + Map answer = new ConcurrentHashMap<>(); + answer.put(EzyCommand.PING, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimplePingParams.builder().build(); + }; + }); + answer.put(EzyCommand.HANDSHAKE, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimpleHandShakeParams.builder() + .clientId(t.get(0, String.class)) + .clientKey(t.get(1, String.class)) + .reconnectToken(t.get(2, String.class)) + .clientType(t.get(3, String.class)) + .clientVersion(t.get(4, String.class)) + .build(); + } + }); + answer.put(EzyCommand.LOGIN, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimpleLoginParams.builder() + .username(t.get(0, String.class)) + .password(t.get(1, String.class)) + .data(t.get(2, EzyArray.class)) + .build(); + } + }); + answer.put(EzyCommand.APP_ACCESS, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimpleAccessAppParams.builder() + .appName(t.get(0, String.class)) + .build(); + } + }); + answer.put(EzyCommand.APP_REQUEST, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimpleRequestAppParams.builder() + .appId(t.get(0, int.class)) + .data(t.get(1, EzyArray.class)) + .build(); + } + }); + answer.put(EzyCommand.PLUGIN_REQUEST, new Function() { + @Override + public Object apply(EzyArray t) { + return EzySimpleRequestPluginParams.builder() + .pluginName(t.get(0, String.class)) + .data(t.get(1, EzyArray.class)) + .build(); + } + }); + return answer; + } + + } + +} 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 new file mode 100644 index 00000000..85cc0015 --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerControllersImpl.java @@ -0,0 +1,80 @@ +package com.tvd12.ezyfoxserver.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.controller.EzyAccessAppController; +import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.controller.EzyHandShakeController; +import com.tvd12.ezyfoxserver.controller.EzyLoginController; +import com.tvd12.ezyfoxserver.controller.EzyPingController; +import com.tvd12.ezyfoxserver.controller.EzyRequestAppController; +import com.tvd12.ezyfoxserver.controller.EzyRequestPluginController; +import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; +import com.tvd12.ezyfoxserver.interceptor.EzyServerUserInterceptor; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; + +import lombok.Setter; + +@Setter +public class EzyServerControllersImpl implements EzyServerControllers { + + @SuppressWarnings("rawtypes") + protected Map controllers; + + @SuppressWarnings("rawtypes") + protected Map interceptors; + + @SuppressWarnings("rawtypes") + @Override + public EzyController getController(EzyConstant cmd) { + return controllers.get(cmd); + } + + @SuppressWarnings("rawtypes") + @Override + public EzyInterceptor getInterceptor(EzyConstant cmd) { + return interceptors.get(cmd); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + @SuppressWarnings("rawtypes") + 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.PLUGIN_REQUEST, new EzyRequestPluginController()); + return answer; + } + + @SuppressWarnings("rawtypes") + 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.PLUGIN_REQUEST, new EzyServerUserInterceptor<>()); + return answer; + } + + public EzyServerControllers build() { + EzyServerControllersImpl answer = new EzyServerControllersImpl(); + answer.setControllers(newControllers()); + answer.setInterceptors(newInterceptors()); + return answer; + } + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerUserManagerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerUserManagerImpl.java new file mode 100644 index 00000000..42a3d2aa --- /dev/null +++ b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyServerUserManagerImpl.java @@ -0,0 +1,158 @@ +package com.tvd12.ezyfoxserver.wrapper.impl; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.constant.EzyUserRemoveReason; +import com.tvd12.ezyfoxserver.delegate.EzyUserRemoveDelegate; +import com.tvd12.ezyfoxserver.entity.EzyHasUserRemoveDelegate; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.util.EzyStartable; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzySimpleUserManager; + +public class EzyServerUserManagerImpl + extends EzySimpleUserManager + implements EzyServerUserManager, EzyStartable { + + protected final ScheduledExecutorService idleValidationService; + protected final ConcurrentHashMap usersBySession = new ConcurrentHashMap<>(); + + public EzyServerUserManagerImpl() { + this.idleValidationService = EzyExecutors.newScheduledThreadPool(3, "user-manager"); + Runtime.getRuntime().addShutdownHook(new Thread(() -> idleValidationService.shutdown())); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#addUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser) + */ + @Override + public void addUser(EzySession session, EzyUser user) { + usersById.put(user.getId(), user); + usersByName.put(user.getName(), user); + usersBySession.put(session, user); + getLogger().info("add user {}, user count = {}", user.getName(), usersById.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) { + usersBySession.remove(session); + } + + /* + * (non-Javadoc) + * @see com.tvd12.ezyfoxserver.mapping.wrapper.EzyUserManager#removeUser(com.tvd12.ezyfoxserver.mapping.entity.EzyUser) + */ + @Override + public EzyUser removeUser(EzyUser user) { + if(user != null) { + super.removeUser(user); + removeUserSessions(user); + } + return user; + } + + /* + * (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, EzyUserRemoveReason reason) { + EzyProcessor.processWithLock( + () -> tryRemoveUser(user, reason), getLock(user.getName())); + } + + public void tryRemoveUser(EzyUser user, EzyUserRemoveReason reason) { + removeUser(user); + delegateUserRemove(user, reason); + } + + @Override + public EzyUser findAndUpdateUser(EzySession current, EzySession update) { + EzyUser user = usersBySession.remove(current); + if(user == null) return null; + user.addSession(update); + user.removeSession(current); + return usersBySession.computeIfAbsent(update, k -> user); + } + + @Override + public void start() throws Exception { + getLogger().debug("start user manager"); + startIdleValidationService(); + } + + protected void startIdleValidationService() { + idleValidationService.scheduleAtFixedRate( + this::validateIdleUsers, 3000, 1000, TimeUnit.MILLISECONDS); + } + + protected void validateIdleUsers() { + for(EzyUser user : getUserList()) + if(isIdleUser(user)) + removeUser(user, EzyUserRemoveReason.IDLE); + } + + protected boolean isIdleUser(EzyUser user) { + return user.getSessionCount() == 0 && + user.getMaxIdleTime() < System.currentTimeMillis() - user.getStartIdleTime(); + } + + protected void removeUserSessions(EzyUser user) { + for(EzySession session : user.getSessions()) + usersBySession.remove(session); + } + + protected void delegateUserRemove(EzyUser user, EzyUserRemoveReason reason) { + EzyHasUserRemoveDelegate hasDelegate = (EzyHasUserRemoveDelegate)user; + EzyUserRemoveDelegate delegate = hasDelegate.getRemoveDelegate(); + delegate.onUserRemoved(reason); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyServerUserManager build() { + return new EzyServerUserManagerImpl(); + } + + } + +} diff --git a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyUserManagerImpl.java b/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyUserManagerImpl.java deleted file mode 100644 index eae5e9b7..00000000 --- a/ezyfox-server-core/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyUserManagerImpl.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.tvd12.ezyfoxserver.wrapper.impl; - -import java.util.concurrent.ConcurrentHashMap; - -import com.tvd12.ezyfoxserver.builder.EzyBuilder; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.entity.EzyUser; -import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; - -public class EzyUserManagerImpl implements EzyUserManager { - - private ConcurrentHashMap usersById; - private ConcurrentHashMap usersByName; - private ConcurrentHashMap usersBySession; - - public EzyUserManagerImpl(Builder builder) { - this.usersById = new ConcurrentHashMap<>(); - this.usersByName = new ConcurrentHashMap<>(); - this.usersBySession = new ConcurrentHashMap<>(); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#addUser(com.tvd12.ezyfoxserver.entity.EzyUser) - */ - @Override - public void addUser(EzyUser user) { - usersById.putIfAbsent(user.getId(), user); - usersByName.putIfAbsent(user.getName(), user); - usersBySession.putIfAbsent(user.getSession(), user); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#getUser(long) - */ - @Override - public EzyUser getUser(long userId) { - return usersById.get(userId); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#getUser(java.lang.String) - */ - @Override - public EzyUser getUser(String username) { - return usersByName.get(username); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#getUser(com.tvd12.ezyfoxserver.entity.EzySession) - */ - @Override - public EzyUser getUser(EzySession session) { - return usersBySession.get(session); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#containsUser(long) - */ - @Override - public boolean containsUser(long userId) { - return usersById.containsKey(userId); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#containsUser(java.lang.String) - */ - @Override - public boolean containsUser(String username) { - return usersByName.containsKey(username); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#containsUser(com.tvd12.ezyfoxserver.entity.EzySession) - */ - @Override - public boolean containsUser(EzySession session) { - return usersBySession.containsKey(session); - } - - /* - * (non-Javadoc) - * @see com.tvd12.ezyfoxserver.wrapper.EzyUserManager#removeUser(com.tvd12.ezyfoxserver.entity.EzyUser) - */ - @Override - public void removeUser(EzyUser user) { - if(user != null) { - usersById.remove(user.getId()); - usersByName.remove(user.getName()); - usersBySession.remove(user.getSession()); - } - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder implements EzyBuilder { - - @Override - public EzyUserManagerImpl build() { - return new EzyUserManagerImpl(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 new file mode 100644 index 00000000..cc4370ab --- /dev/null +++ b/ezyfox-server-core/src/main/resources/com/tvd12/ezyfoxserver/jaxb.index @@ -0,0 +1 @@ +setting.EzySimpleSettings \ No newline at end of file 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 new file mode 100644 index 00000000..74eb0dff --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ezy-settings-1.0.0.xsd @@ -0,0 +1,186 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-core/src/main/resources/ezy-settings.xml b/ezyfox-server-core/src/main/resources/ezy-settings.xml new file mode 100644 index 00000000..74592d5d --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ezy-settings.xml @@ -0,0 +1,86 @@ + + + + 36 + + + 8080 + + + + 3005 +

0.0.0.0
+ 65536 + com.tvd12.ezyfoxserver.netty.codec.MsgPackCodecCreator + + + + 2208 +
0.0.0.0
+ 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 + Guest# + 15000 + 15 + ^[a-z0-9_.]{3,36}$ + + + + true + 15000 + 30000 + + 20 + DISCONNECT_SESSION + + + + + + ezyfox-chat + com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader + 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/main/resources/ezyfox-banner.txt b/ezyfox-server-core/src/main/resources/ezyfox-banner.txt new file mode 100644 index 00000000..75325853 --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ezyfox-banner.txt @@ -0,0 +1,9 @@ + + ______ ________ ________ ______ __ _____ ______ _______ __ + | ____|___ /\ \ / / ____/ __ \ \ / / | __ \| ____| /\ | __ \ \ / / + | |__ / / \ \_/ /| |__ | | | \ V / ______ | |__) | |__ / \ | | | \ \_/ / + | __| / / \ / | __|| | | |> < |______| | _ /| __| / /\ \ | | | |\ / + | |____ / /__ | | | | | |__| / . \ | | \ \| |____ / ____ \| |__| | | | + |______/_____| |_| |_| \____/_/ \_\ |_| \_\______/_/ \_\_____/ |_| + + diff --git a/ezyfox-server-core/src/main/resources/html/ws-index.html b/ezyfox-server-core/src/main/resources/html/ws-index.html new file mode 100644 index 00000000..67c9278d --- /dev/null +++ b/ezyfox-server-core/src/main/resources/html/ws-index.html @@ -0,0 +1,122 @@ + + + + + + + + WebSocket ChatServer + + + + + + + + + + + + + + +
+
Enter a message below to send
+ + +
+ + + +
+
+


Instructions:

+ + + + + + + + + +
Step 1:  Press the Connect button.
Step 2:  Once connected, enter a message and press the Send button. The server's + response will + appear in the Log section. You can send as many messages as you like +
+
+ + + \ No newline at end of file diff --git a/ezyfox-server-core/src/main/resources/html/wss-index.html b/ezyfox-server-core/src/main/resources/html/wss-index.html new file mode 100644 index 00000000..c2093cbc --- /dev/null +++ b/ezyfox-server-core/src/main/resources/html/wss-index.html @@ -0,0 +1,110 @@ + + + + + + + + WebSocket ChatServer + + + + + + + + + + + + + + +
+
Enter a message below to send
+ + +
+ + + +
+
+


Instructions:

+ + + + + + + + + +
Step 1:  Press the Connect button.
Step 2:  Once connected, enter a message and press the Send button. The server's + response will + appear in the Log section. You can send as many messages as you like +
+
+ + + \ No newline at end of file diff --git a/ezyfox-server-core/src/main/resources/ssl-config.properties b/ezyfox-server-core/src/main/resources/ssl-config.properties new file mode 100644 index 00000000..914e17bf --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ssl-config.properties @@ -0,0 +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 diff --git a/ezyfox-server-core/src/main/resources/ssl/ssl-certificate-password.txt b/ezyfox-server-core/src/main/resources/ssl/ssl-certificate-password.txt new file mode 100644 index 00000000..536aca34 --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ssl/ssl-certificate-password.txt @@ -0,0 +1 @@ +secret \ No newline at end of file diff --git a/ezyfox-server-core/src/main/resources/ssl/ssl-key-store.txt b/ezyfox-server-core/src/main/resources/ssl/ssl-key-store.txt new file mode 100644 index 00000000..439ef0da Binary files /dev/null and b/ezyfox-server-core/src/main/resources/ssl/ssl-key-store.txt differ diff --git a/ezyfox-server-core/src/main/resources/ssl/ssl-keystore-password.txt b/ezyfox-server-core/src/main/resources/ssl/ssl-keystore-password.txt new file mode 100644 index 00000000..536aca34 --- /dev/null +++ b/ezyfox-server-core/src/main/resources/ssl/ssl-keystore-password.txt @@ -0,0 +1 @@ +secret \ No newline at end of file diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreContextTest.java new file mode 100644 index 00000000..643c32d4 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreContextTest.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; + +public class BaseCoreContextTest extends BaseCoreTest { + + protected EzyServerContext context; + + public BaseCoreContextTest() { + super(); + context = newServerContext(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreTest.java new file mode 100644 index 00000000..7ee5d819 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/BaseCoreTest.java @@ -0,0 +1,140 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.security.KeyPair; + +import com.tvd12.ezyfoxserver.EzyLoader; +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.builder.EzyServerContextBuilder; +import com.tvd12.ezyfoxserver.config.EzyConfig; +import com.tvd12.ezyfoxserver.config.EzyConfigLoader; +import com.tvd12.ezyfoxserver.config.EzySimpleConfigLoader; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.mapping.jackson.EzyJsonMapper; +import com.tvd12.ezyfoxserver.mapping.jackson.EzySimpleJsonMapper; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzySimplXmlMapper; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzyXmlReader; +import com.tvd12.ezyfoxserver.sercurity.EzyKeysGenerator; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyManagersImpl; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyRequestMappersImpl; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyServerControllersImpl; +import com.tvd12.test.base.BaseTest; + +public class BaseCoreTest extends BaseTest { + + protected EzyServerContext newServerContext() { + return newServerContextBuilder().build(); + } + + protected EzyServerContextBuilder newServerContextBuilder() { + return new MyTestServerContextBuilder() + .server(newServer()); + } + + protected EzySimpleServer newServer() { + try { + EzySimpleServer answer = (EzySimpleServer) loadEzyFox(readConfig("test-data/settings/config.properties")); + answer.setRequestMappers(EzyRequestMappersImpl.builder().build()); + answer.getManagers().addManager(EzySessionManager.class, MyTestSessionManager.builder().build()); + answer.getManagers().addManager(EzyServerUserManager.class, MyTestUserManager.builder().build()); + return answer; + } + catch(Exception e) { + throw new RuntimeException(e); + } + } + + protected EzyConfig readConfig(String configFile) throws Exception { + return getConfigLoader().load(configFile); + } + + protected EzyConfigLoader getConfigLoader() { + return new EzySimpleConfigLoader(); + } + + protected EzyServer loadEzyFox(EzyConfig config) { + return new EzyLoader() + .config(config) + .classLoader(getClassLoader()) + .load(); + } + + protected EzyXmlReader getXmlReader() { + return EzySimplXmlMapper.builder() + .classLoader(getClassLoader()) + .contextPath("com.tvd12.ezyfoxserver.mapping") + .build(); + } + + protected EzyJsonMapper getJsonMapper() { + return EzySimpleJsonMapper.builder().build(); + } + + public EzyManagers newManagers() { + return EzyManagersImpl.builder().build(); + } + + public EzyServerControllers newControllers() { + return EzyServerControllersImpl.builder().build(); + } + + protected ClassLoader getClassLoader() { + return EzySimpleServer.class.getClassLoader(); + } + + protected EzySession newSession() { + MyTestSession session = new MyTestSession(); + session.setDelegate(new SessionDelegate()); + return session; + } + + protected KeyPair newRSAKeys() { + return EzyKeysGenerator.builder() + .build() + .generate(); + } + + protected EzySession newSessionHasKey(String reconnectToken) { + KeyPair keyPair = newRSAKeys(); + EzySession session = newSession(); + session.setReconnectToken(reconnectToken); + session.setPublicKey(keyPair.getPublic().getEncoded()); + return session; + } + + protected EzySimpleUser newUser() { + return new EzySimpleUser(); + } + + protected EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + + protected EzyObjectBuilder newObjectBuilder() { + return EzyEntityFactory.create(EzyObjectBuilder.class); + } + + public static class SessionDelegate implements EzySessionDelegate { + + @Override + public void onSessionReturned(EzyConstant reason) { + } + + @Override + public void onSessionLoggedIn(EzyUser user) { + } + + } +} 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 new file mode 100644 index 00000000..91ceab24 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyAppsStarterTest.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.EzyAppsStarter; +import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; +import com.tvd12.ezyfoxserver.ext.EzyAppEntryLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyAppsStarterTest extends BaseTest { + + @Test + public void test1() { + Map loaders = new ConcurrentHashMap<>(); + EzyAppsStarter starter = new EzyAppsStarter.Builder() { + @Override + public EzyAppsStarter build() { + return new EzyAppsStarter(this) { + @Override + protected void startApp(String appName, EzyAppEntryLoader loader) throws Exception { + throw new RuntimeException(); + } + + public EzyAppEntryLoader newAppEntryLoader(String appName) throws Exception { + throw new RuntimeException(); + }; + + public java.util.Set getAppNames() { + return Sets.newHashSet("test"); + }; + }; + } + } + .appClassLoaders(loaders) + .build(); + starter.start(); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + Map loaders = new ConcurrentHashMap<>(); + EzyAppsStarter starter = new EzyAppsStarter.Builder() + .appClassLoaders(loaders) + .build(); + starter.getClassLoader("zzz"); + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyBootstrapTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyBootstrapTest.java new file mode 100644 index 00000000..bdecf8ad --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyBootstrapTest.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +public class EzyBootstrapTest extends BaseCoreTest { + + @Test + public void test() { +// EzyBootstrap bootstrap = EzyBootstrap.builder() +// .context(newServerContext()) +// .build(); +// bootstrap.destroy(); +// MethodInvoker.create() +// .object(bootstrap) +// .method(getMethod("startApp")) +// .param("abc") +// .invoke(); +// MethodInvoker.create() +// .object(bootstrap) +// .method(getMethod("startPlugin")) +// .param("abc") +// .invoke(); + } + +// private Method getMethod(String name) { +// return MethodBuilder.create() +// .method(name) +// .clazz(EzyBootstrap.class) +// .argument(String.class) +// .build(); +// } + +} 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 new file mode 100644 index 00000000..7f025b57 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyLoaderTest.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.testing; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.config.EzyConfig; +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.ezyfoxserver.setting.EzyAppSetting; +import com.tvd12.ezyfoxserver.setting.EzyPluginSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; + +public class EzyLoaderTest extends BaseCoreTest { + + @Test + public void test() throws Exception { + EzySimpleServer server = newServer(); + + EzyConfig config = server.getConfig(); + assertEquals(config.getEzyfoxHome(), "test-data"); + assertEquals(config.getEzyfoxVersion(), "1.0.0"); + assertEquals(config.getLoggerConfigFile(), "logback.groovy"); + + EzySettings settings = server.getSettings(); + EzyAppSetting app = settings.getAppByName("ezyfox-chat"); + app = settings.getAppById(app.getId()); + assertEquals(app.getName(), "ezyfox-chat"); + assertEquals(app.getId() > 0, true); + assertEquals(app.getWorkerPoolSize() > 0, true); + assertEquals(app.getEntryLoader(), "com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader"); + assertEquals(app.getEventControllers().getController(EzyEventType.SERVER_READY) != null, true); + + EzyPluginSetting plugin = settings.getPluginByName("ezyfox-auth-plugin"); + plugin = settings.getPluginById(plugin.getId()); + assertEquals(plugin.getId() > 0, true); + assertEquals(plugin.getWorkerPoolSize() > 0, true); + assertEquals(plugin.getPriority(), -1); + assertEquals(plugin.getName(), "ezyfox-auth-plugin"); + assertEquals(plugin.getEventControllers().getController(EzyEventType.SERVER_READY) != null, true); + +// Class chatEntryLoaderClass = server.getAppEntryLoaderClass("ezyfox-chat"); +// assertEquals(chatEntryLoaderClass.getName(), "com.tvd12.ezyfoxserver.mapping.chat.EzyChatEntryLoader"); +// Class authEntryLoaderClass = server.getPluginEntryLoaderClass("ezyfox-auth-plugin"); +// assertEquals(authEntryLoaderClass.getName(), "com.tvd12.ezyfoxserver.mapping.plugin.auth.EzyAuthPluginEntryLoader"); + } + + +} 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 new file mode 100644 index 00000000..c0fb9c56 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyPluginsStarterTest.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.EzyAppsStarter; +import com.tvd12.ezyfoxserver.EzyPluginsStarter; +import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; +import com.tvd12.ezyfoxserver.ext.EzyPluginEntryLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyPluginsStarterTest extends BaseTest { + + @Test + public void test1() { + EzyPluginsStarter starter = new EzyPluginsStarter.Builder() { + @Override + public EzyPluginsStarter build() { + return new EzyPluginsStarter(this) { + public java.util.Set getPluginNames() { + return Sets.newHashSet("test"); + }; + + public EzyPluginEntryLoader newPluginEntryLoader(String pluginName) + throws Exception { + throw new Exception(); + }; + }; + } + } + .build(); + starter.start(); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + Map loaders = new ConcurrentHashMap<>(); + EzyAppsStarter starter = new EzyAppsStarter.Builder() + .appClassLoaders(loaders) + .build(); + starter.getClassLoader("zzz"); + } +} 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 new file mode 100644 index 00000000..95e6ca11 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyRunnerTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzyRunner; +import com.tvd12.test.base.BaseTest; + +public class EzyRunnerTest extends BaseTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() throws Exception { + EzyRunner runner = new MyTestRunner(); + runner.run(new String[0]); + } + + @Test + public void test1() throws Exception { + EzyRunner runner = new MyTestRunner(); + runner.run(new String[] {"test-data/settings/config.properties"}); + } + +} 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 new file mode 100644 index 00000000..d593a37a --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerBootstrapTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzyServerBootstrap; + +public class EzyServerBootstrapTest extends BaseCoreTest { + + @Test + public void test() { + EzyServerBootstrap bt = new MyTestServerBootstrapBuilder() + .server(newServer()) + .build(); + bt.destroy(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerTest.java new file mode 100644 index 00000000..a562bbd8 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzyServerTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import static org.testng.Assert.*; + +public class EzyServerTest extends BaseCoreTest { + + private EzySimpleServer server; + + public EzyServerTest() { + super(); + server = newServer(); + } + + @Test + public void test() { + assertEquals(server.getClassLoader(), EzySimpleServer.class.getClassLoader()); + assertEquals(server.getJsonMapper() != null, true); + assertEquals(server.getControllers() != null, true); + assertEquals(server.getRequestMappers() != null, true); + assertEquals(server.getAppClassLoaders().containsKey("ezyfox-chat"), true); + } + +} 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 a81f9489..8bd5add0 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 @@ -8,7 +8,7 @@ import org.testng.annotations.Test; -import com.tvd12.ezyfoxserver.config.EzySettings; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettings; public class EzySettingsReaderTest { @@ -17,8 +17,8 @@ public void test() throws Exception { // JAXBContext jaxbContext = JAXBContext.newInstance(EzyFoxSettings.class); JAXBContext jaxbContext = JAXBContext.newInstance("com.tvd12.ezyfoxserver", getClass().getClassLoader()); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - EzySettings settings = jaxbUnmarshaller - .unmarshal(new StreamSource(inputStream()), EzySettings.class).getValue(); + EzySimpleSettings settings = jaxbUnmarshaller + .unmarshal(new StreamSource(inputStream()), EzySimpleSettings.class).getValue(); System.out.println(settings); } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySystemTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySystemTest.java new file mode 100644 index 00000000..ece1c384 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/EzySystemTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySystem; +import com.tvd12.test.base.BaseTest; + +public class EzySystemTest extends BaseTest { + + @Test + public void test() { + EzySystem.getEnv().setProperty("1", "a"); + assert EzySystem.getEnv().getProperty("1").equals("a"); + } + + @Override + public Class getTestClass() { + return EzySystem.class; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestDataHandler.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestDataHandler.java new file mode 100644 index 00000000..8dce4384 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestDataHandler.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.handler.EzySimpleDataHandler; + +public class MyTestDataHandler extends EzySimpleDataHandler { + + public MyTestDataHandler() { + } + + public MyTestDataHandler(MyTestSession session) { + this.session = session; + } + + public MyTestDataHandler(EzySession session) { + this((MyTestSession)session); + } + + public void borrowSession() { + MyTestSession session1 = session != null ? session : new MyTestSession(); + session1.setReconnectToken("abc"); + borrowSession(() -> session1); + } + + @Override + public EzyAppContext getAppContext(int appId) { + return super.getAppContext(appId); + } +} 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 new file mode 100644 index 00000000..a1ccd986 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestRunner.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.EzyRunner; +import com.tvd12.ezyfoxserver.EzyStarter.Builder; + +public class MyTestRunner extends EzyRunner { + + @Override + protected Builder newStarterBuilder() { + return MyTestStarter.builder(); + } + +} \ No newline at end of file diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrap.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrap.java new file mode 100644 index 00000000..4c5e0891 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrap.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.EzyServerBootstrap; + +public class MyTestServerBootstrap extends EzyServerBootstrap { + + @Override + protected void startOtherBootstraps(Runnable callback) throws Exception { + callback.run(); + } + +} 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 new file mode 100644 index 00000000..4eefaa13 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerBootstrapBuilder.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.EzyHttpBootstrap; +import com.tvd12.ezyfoxserver.EzyServerBootstrap; +import com.tvd12.ezyfoxserver.builder.EzyAbtractServerBootstrapBuilder; + +public class MyTestServerBootstrapBuilder extends EzyAbtractServerBootstrapBuilder { + + @Override + protected EzyServerBootstrap newServerBootstrap() { + return new MyTestServerBootstrap(); + } + + @Override + public String getCodecCreatorClassName() { + return super.getCodecCreatorClassName(); + } + + @Override + public String getWsCodecCreatorClassName() { + return super.getWsCodecCreatorClassName(); + } + + @Override + protected EzyHttpBootstrap newHttpBottstrap() { + return new EzyHttpBootstrap() { + + @Override + public void destroy() { + + } + + @Override + public void start() throws Exception { + + } + }; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerContextBuilder.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerContextBuilder.java new file mode 100644 index 00000000..01f9c789 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestServerContextBuilder.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.builder.EzySimpleServerContextBuilder; + +public class MyTestServerContextBuilder + extends EzySimpleServerContextBuilder { + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSession.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSession.java new file mode 100644 index 00000000..db4f7f6e --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSession.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.net.InetSocketAddress; +import java.net.SocketAddress; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzyUser; + +public class MyTestSession extends EzyAbstractSession { + private static final long serialVersionUID = -1980181361152627223L; + + @Override + public SocketAddress getClientAddress() { + return new InetSocketAddress("123.123.123.123", 8080); + } + + @Override + public SocketAddress getServerAddress() { + return new InetSocketAddress("localhost", 8080); + } + + @Override + public void close() { + } + + @Override + public void disconnect() { + } + + @Override + protected void sendData(EzyData data, EzyTransportType type) { + } + + @Override + public EzySessionDelegate getDelegate() { + return new EzySessionDelegate() { + + @Override + public void onSessionLoggedIn(EzyUser user) { + + } + + @Override + public void onSessionReturned(EzyConstant reason) { + + } + }; + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionFactory.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionFactory.java new file mode 100644 index 00000000..73e1d70b --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionFactory.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.factory.EzyAbstractSessionFactory; + +public class MyTestSessionFactory + extends EzyAbstractSessionFactory { + + @Override + protected MyTestSession newSession() { + return new MyTestSession(); + } + +} 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 new file mode 100644 index 00000000..732b981a --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestSessionManager.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.util.List; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.factory.EzyAbstractSessionFactory; +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.wrapper.EzySimpleSessionManager; + +public class MyTestSessionManager extends EzySimpleSessionManager { + + protected MyTestSessionManager(Builder builder) { + super(builder); + } + + @Override + public List getBorrowedObjects() { + return super.getBorrowedObjects(); + } + + @Override + public MyTestSession borrowSession(EzyConnectionType type) { + return super.borrowSession(type); + } + + @Override + public boolean isStaleObject(MyTestSession session) { + return super.isStaleObject(session); + } + + @Override + public void removeStaleObject(MyTestSession session) { + super.removeStaleObject(session); + } + + @Override + public List getCanBeStaleObjects() { + return super.getCanBeStaleObjects(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleSessionManager.Builder { + + @Override + public MyTestSessionManager build() { + return new MyTestSessionManager(this); + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyAbstractSessionFactory() { + @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 new file mode 100644 index 00000000..8b1ed3a5 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestStarter.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.EzyStarter; +import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; + +public class MyTestStarter extends EzyStarter { + + protected MyTestStarter(Builder builder) { + super(builder); + } + + @Override + protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { + return new MyTestServerBootstrapBuilder(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyStarter.Builder { + @Override + public EzyStarter build() { + return new MyTestStarter(this); + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUser.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUser.java new file mode 100644 index 00000000..6d98fd34 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUser.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.delegate.EzyUserRemoveDelegate; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; + +public class MyTestUser extends EzySimpleUser { + private static final long serialVersionUID = 9150382549072410382L; + + @Override + public EzyUserRemoveDelegate getRemoveDelegate() { + return new EzyUserRemoveDelegate() { + + @Override + public void onUserRemoved(EzyConstant reason) { + } + }; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUserManager.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUserManager.java new file mode 100644 index 00000000..30d516c9 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/MyTestUserManager.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing; + +import com.tvd12.ezyfoxserver.wrapper.impl.EzyServerUserManagerImpl; + +public class MyTestUserManager extends EzyServerUserManagerImpl { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyServerUserManagerImpl.Builder { + @Override + public MyTestUserManager build() { + return new MyTestUserManager(); + } + } + +} 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 21015b82..3a351bc2 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 @@ -2,14 +2,14 @@ import java.util.concurrent.ConcurrentHashMap; -import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.EzySimpleServer; import com.tvd12.ezyfoxserver.command.EzyCommand; import com.tvd12.ezyfoxserver.command.EzyRunWorker; import com.tvd12.ezyfoxserver.command.EzySendMessage; -import com.tvd12.ezyfoxserver.config.EzyApp; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.reflect.EzyClassUtil; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; import com.tvd12.ezyfoxserver.util.EzyLoggable; import com.tvd12.test.base.BaseTest; @@ -25,10 +25,10 @@ public static void main(String args[]) { strs.put(EzySendMessage.class, EzyObject.class); strs.put(EzyObject.class, EzyObject.class); strs.put(EzyArray.class, EzyObject.class); - strs.put(EzyApp.class, EzyObject.class); - strs.put(EzyServer.class, EzyObject.class); + strs.put(EzySimpleAppSetting.class, EzyObject.class); + strs.put(EzySimpleServer.class, EzyObject.class); strs.put(EzyLoggable.class, EzyObject.class); - strs.put(EzyClassUtil.class, EzyObject.class); + strs.put(EzyClasses.class, EzyObject.class); for(int i = 0 ; i < 10000000 ; i++) { Object abc = strs.get(EzyLoggable.class); } diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/UsernamePatternTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/UsernamePatternTest.java new file mode 100644 index 00000000..29837c67 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/UsernamePatternTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.testing; + +import java.util.List; + +import com.google.common.collect.Lists; + +public class UsernamePatternTest { + + public static void main(String[] args) { + String pattern = "^[a-z0-9_.]{3,36}$"; + List names = Lists.newArrayList( + "_tavandung", + "dungtv-hehe", + "dung@name", + "dung123", + "dung.tvd", + "dung.tvd.", + "dung--tvd", + "dũng" + ); + for(String name : names) { + System.out.println("name: " + name + ", valid = " + name.matches(pattern)); + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyServerReadyControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyServerReadyControllerTest.java new file mode 100644 index 00000000..34b6dcc9 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyServerReadyControllerTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.appcontroller; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.appcontroller.EzyServerReadyController; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.event.EzyServerReadyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyServerReadyEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyServerReadyControllerTest extends BaseCoreTest { + + @Test + public void test() { + EzyServerReadyController ctrl = new EzyServerReadyController(); + EzyServerContext ctx = newServerContext(); + EzyServerReadyEvent event = EzyServerReadyEventImpl.builder() + .build(); + ctrl.handle(ctx.getAppContext("ezyfox-chat"), event); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserDisconnectControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserDisconnectControllerTest.java new file mode 100644 index 00000000..51cf6d97 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserDisconnectControllerTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.appcontroller; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.appcontroller.EzyUserDisconnectController; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.event.EzyUserDisconnectEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserDisconnectEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyUserDisconnectControllerTest extends BaseCoreTest { + + @Test + public void test() { + EzyUserDisconnectController ctrl = new EzyUserDisconnectController(); + EzyServerContext ctx = newServerContext(); + EzyUserDisconnectEvent event = (EzyUserDisconnectEvent) EzyUserDisconnectEventImpl.builder() + .reason(EzyDisconnectReason.IDLE) + .user(newUser()) + .build(); + ctrl.handle(ctx.getAppContext("ezyfox-chat"), event); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserRequestAppControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserRequestAppControllerTest.java new file mode 100644 index 00000000..ede687ca --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/appcontroller/EzyUserRequestAppControllerTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.appcontroller; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.appcontroller.EzyUserRequestAppController; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserRequestAppEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyUserRequestAppControllerTest extends BaseCoreTest { + + @Test + public void test() { + EzyUserRequestAppController ctrl = new EzyUserRequestAppController(); + EzyServerContext ctx = newServerContext(); + EzyUserRequestAppEvent event = (EzyUserRequestAppEvent) EzyUserRequestAppEventImpl.builder() + .data(newArrayBuilder().build()) + .user(newUser()) + .build(); + ctrl.handle(ctx.getAppContext("ezyfox-chat"), event); + } + +} 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 new file mode 100644 index 00000000..417b71eb --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/builder/EzyAbtractServerBootstrapBuilderTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing.builder; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestServerBootstrapBuilder; + +public class EzyAbtractServerBootstrapBuilderTest extends BaseCoreTest { + + @Test + public void test() { + EzySimpleServer server = newServer(); + MyTestServerBootstrapBuilder builder = + (MyTestServerBootstrapBuilder) new MyTestServerBootstrapBuilder() + .server(server); + builder.getCodecCreatorClassName(); + builder.getWsCodecCreatorClassName(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ccl/EzyAppClassLoaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ccl/EzyAppClassLoaderTest.java new file mode 100644 index 00000000..0fe291b6 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ccl/EzyAppClassLoaderTest.java @@ -0,0 +1,71 @@ +package com.tvd12.ezyfoxserver.testing.ccl; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.ccl.EzyAppClassLoader; +import com.tvd12.ezyfoxserver.util.EzyDirectories; +import com.tvd12.test.base.BaseTest; + +public class EzyAppClassLoaderTest extends BaseTest { + + @Test + public void test() { + EzyAppClassLoader loader = new EzyAppClassLoader( + new File("test-data/apps/entries/ezyfox-chat"), + getClass().getClassLoader()); + loader.findResource("ezyfox-chat.jar"); + try { + loader.close(); + } catch (IOException e) { + } + } + + @Test(expectedExceptions = {InvocationTargetException.class}) + public void test1() throws Exception { + Method method = EzyAppClassLoader.class + .getDeclaredMethod("getURLsByPath", EzyDirectories.class); + method.setAccessible(true); + method.invoke(EzyAppClassLoader.class, new EzyDirectories() { + @Override + public URL[] getURLs() throws IOException { + throw new IOException(); + } + }); + } + + @Test + public void test2() throws Exception { + try { + EzyAppClassLoader loader = new EzyAppClassLoader( + new File("test-data/apps/entries/ezyfox-chat"){ + private static final long serialVersionUID = -4357308555875682046L; + + @Override + public boolean isDirectory() { + throw new RuntimeException(); + } + + @Override + public File[] listFiles() { + throw new RuntimeException(); + } + }, + getClass().getClassLoader()); + loader.findResource("ezyfox-chat.jar"); + try { + loader.close(); + } catch (IOException e) { + } + } + catch(Exception e) { + + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppFireEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppFireEventImplTest.java new file mode 100644 index 00000000..f3ab6d00 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppFireEventImplTest.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.command; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleApplication; +import com.tvd12.ezyfoxserver.command.impl.EzyAppFireEventImpl; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; + +public class EzyAppFireEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzySimpleAppSetting app = mock(EzySimpleAppSetting.class); + EzyConstant type = EzyConstant.one(); + EzyEventControllers ctrs = mock(EzyEventControllers.class); + EzyAppContext context = mock(EzyAppContext.class); + when(app.getEventControllers()).thenReturn(ctrs); + + EzySimpleApplication application = new EzySimpleApplication(); + application.setSetting(app); + + when(context.getApp()).thenReturn(application); + EzyAppFireEventImpl event = new EzyAppFireEventImpl(context); + event.fire(type, null); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppResponseImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppResponseImplTest.java new file mode 100644 index 00000000..20db5d1b --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyAppResponseImplTest.java @@ -0,0 +1,225 @@ +package com.tvd12.ezyfoxserver.testing.command; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.net.SocketAddress; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicInteger; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.EzyApplication; +import com.tvd12.ezyfoxserver.command.EzyAppResponse; +import com.tvd12.ezyfoxserver.command.impl.EzyAbstractResponse; +import com.tvd12.ezyfoxserver.command.impl.EzyAppResponseImpl; +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyAppUserManagerImpl; +import com.tvd12.test.base.BaseTest; +import com.tvd12.test.performance.Performance; + +public class EzyAppResponseImplTest extends BaseTest { + + @Test + public void testPerformance() { + EzyAppResponse response = newResponse(); + + EzyUser user1 = new ExUser("user1"); + EzySession session1 = new ExSession(); + EzySession session2 = new ExSession(); + + user1.addSession(session1); + user1.addSession(session2); + + EzyUser user2 = new ExUser("user2"); + EzySession session3 = new ExSession(); + EzySession session4 = new ExSession(); + + user2.addSession(session3); + user2.addSession(session4); + +// List list = new ArrayList<>(); + + + long time = Performance.create() + .loop(1000000) + .test(() -> { + response.users(new EzyUser[] {user1, user2}, false); +// list.add(user1); +// list.add(user2); +// list.add(Arrays.asList(new EzyUser[] {user1, user2})); +// list.addAll(user1.getSessions()); +// list.addAll(user2.getSessions()); +// response.user(user1); +// response.user(user2); + }) + .getTime(); + System.out.println("time = " + time); + } + + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + EzyAppContext context = mock(EzyAppContext.class); + EzyApplication application = mock(EzyApplication.class); + EzyAppUserManager userManager = new EzyAppUserManagerImpl(); + when(context.getApp()).thenReturn(application); + when(application.getUserManager()).thenReturn(userManager); + EzyAppResponse response = new EzyAppResponseImpl(context); + + Field recipients = EzyAbstractResponse.class.getDeclaredField("recipients"); + Field exrecipients = EzyAbstractResponse.class.getDeclaredField("exrecipients"); + recipients.setAccessible(true); + exrecipients.setAccessible(true); + assert ((Collection)recipients.get(response)).size() == 0; + assert ((Collection)exrecipients.get(response)).size() == 0; + + EzyUser user1 = newUser("user1"); + response.user(user1); + assert ((Collection)recipients.get(response)).size() == 2; + assert ((Collection)exrecipients.get(response)).size() == 0; + + EzyUser user2 = newUser("user2"); + response.user(user2); + response.user(user2, true); + assert ((Collection)recipients.get(response)).size() == 4; + assert ((Collection)exrecipients.get(response)).size() == 2; + + EzyUser user3 = newUser("user3"); + EzyUser user4 = newUser("user4"); + response.users(user3, user4); + response.users(new EzyUser[] {user3, null}, true); + assert ((Collection)recipients.get(response)).size() == 8; + assert ((Collection)exrecipients.get(response)).size() == 4; + + EzyUser user5 = newUser("user5"); + EzyUser user6 = newUser("user6"); + response.users(Lists.newArrayList(user5, user6)); + response.users(Lists.newArrayList(user5, null), true); + assert ((Collection)recipients.get(response)).size() == 12; + assert ((Collection)exrecipients.get(response)).size() == 6; + + EzyUser user7 = newUser("user7"); + EzyUser user8 = newUser("user8"); + userManager.addUser(user7); + userManager.addUser(user8); + response.username("user7"); + response.username("user7", true); + assert ((Collection)recipients.get(response)).size() == 14; + assert ((Collection)exrecipients.get(response)).size() == 8; + + EzyUser user9 = newUser("user9"); + EzyUser user10 = newUser("user10"); + EzyUser user11 = newUser("user11"); + userManager.addUser(user9); + userManager.addUser(user10); + userManager.addUser(user11); + response.usernames("user9", "user10"); + response.usernames(new String[] {"user11"}, true); + assert ((Collection)recipients.get(response)).size() == 18; + assert ((Collection)exrecipients.get(response)).size() == 10; + + EzyUser user12 = newUser("user12"); + EzyUser user13 = newUser("user13"); + EzyUser user14 = newUser("user14"); + userManager.addUser(user12); + userManager.addUser(user13); + userManager.addUser(user14); + response.usernames(Lists.newArrayList("user12", "user13")); + response.usernames(Lists.newArrayList("user14"), true); + assert ((Collection)recipients.get(response)).size() == 22; + assert ((Collection)exrecipients.get(response)).size() == 12; + + EzySession session1 = new ExSession(); + response.session(session1); + assert ((Collection)recipients.get(response)).size() == 23; + assert ((Collection)exrecipients.get(response)).size() == 12; + + EzySession session2 = new ExSession(); + EzySession session3 = new ExSession(); + response.sessions(session2, session3); + response.sessions(new EzySession[] {session3}, true); + assert ((Collection)recipients.get(response)).size() == 25; + assert ((Collection)exrecipients.get(response)).size() == 13; + + EzySession session4 = new ExSession(); + EzySession session5 = new ExSession(); + response.sessions(Lists.newArrayList(session4, session5)); + response.sessions(Lists.newArrayList(session4, session5), true); + assert ((Collection)recipients.get(response)).size() == 27; + assert ((Collection)exrecipients.get(response)).size() == 15; + } + + private EzyUser newUser(String name) { + EzyUser user2 = new ExUser(name); + EzySession session3 = new ExSession(); + EzySession session4 = new ExSession(); + user2.addSession(session3); + user2.addSession(session4); + return user2; + } + + private EzyAppResponse newResponse() { + EzyAppContext context = mock(EzyAppContext.class); + EzyApplication application = mock(EzyApplication.class); + EzyAppUserManager userManager = new EzyAppUserManagerImpl(); + when(context.getApp()).thenReturn(application); + when(application.getUserManager()).thenReturn(userManager); + EzyAppResponse response = new EzyAppResponseImpl(context); + return response; + } + + public static class ExUser extends EzySimpleUser { + private static final long serialVersionUID = 5665904607192806625L; + + public ExUser(String name) { + setName(name); + } + + } + + public static class ExSession extends EzyAbstractSession { + private static final long serialVersionUID = 3390787330201950376L; + + public static final AtomicInteger ID_GENTOR = new AtomicInteger(0); + + public ExSession() { + int id = ID_GENTOR.incrementAndGet(); + setId(id); + setReconnectToken(String.valueOf(id)); + } + + @Override + public SocketAddress getClientAddress() { + return null; + } + + @Override + public SocketAddress getServerAddress() { + return null; + } + + @Override + public void close() { + } + + @Override + public void disconnect() { + } + + @Override + protected void sendData(EzyData data, EzyTransportType type) { + } + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyDisconnectUserImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyDisconnectUserImplTest.java new file mode 100644 index 00000000..01954fde --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/command/EzyDisconnectUserImplTest.java @@ -0,0 +1,79 @@ +package com.tvd12.ezyfoxserver.testing.command; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.command.impl.EzyDisconnectUserImpl; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestUser; + +public class EzyDisconnectUserImplTest extends BaseCoreTest { + + @Test + public void test() { + EzySession session = newSession(); + session.setReconnectToken("abc"); + EzySimpleUser user = newUser(); + user.setName("abc"); + user.addSession(session); + EzyServerContext context = newServerContext(); + new EzyDisconnectUserImpl(context) + .user(user) + .fireClientEvent(true) + .fireServerEvent(true) + .reason(EzyDisconnectReason.ANOTHER_SESSION_LOGIN) + .execute(); + } + + @Test + public void test1() { + EzySession session = newSession(); + EzySimpleUser user = newUser(); + session.setReconnectToken("abc"); + user.setName("abc"); + user.addSession(session); + EzyServerContext context = newServerContext(); + new EzyDisconnectUserImpl(context) + .user(user) + .fireClientEvent(false) + .fireServerEvent(true) + .reason(EzyDisconnectReason.ANOTHER_SESSION_LOGIN) + .execute(); + } + + @Test + public void test2() { + MyTestUser user = new MyTestUser(); + user.setName("dungtv"); + EzySession session = newSession(); + session.setReconnectToken("abc"); + user.addSession(session); + EzyServerContext context = newServerContext(); + new EzyDisconnectUserImpl(context) + .user(user) + .fireClientEvent(false) + .fireServerEvent(false) + .reason(EzyDisconnectReason.ANOTHER_SESSION_LOGIN) + .execute(); + } + + @Test + public void test3() { + MyTestUser user = new MyTestUser(); + user.setName("dungtv"); + EzySession session = newSession(); + session.setReconnectToken("abc"); + user.addSession(session); + EzyServerContext context = newServerContext(); + new EzyDisconnectUserImpl(context) + .user(user) + .fireClientEvent(false) + .fireServerEvent(true) + .reason(EzyDisconnectReason.ANOTHER_SESSION_LOGIN) + .execute(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAbstractConfigTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAbstractConfigTest.java new file mode 100644 index 00000000..1bb6d843 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAbstractConfigTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzyAbstractSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.wrapper.EzyEventControllers; + +public class EzyAbstractConfigTest extends BaseCoreTest { + + @Test + public void test() { + Config config = new Config(); + config.setName("config"); + config.setEntryLoader("loader"); + config.setWorkerPoolSize(100); + } + + + public static class Config extends EzyAbstractSetting { + @Override + protected AtomicInteger getIdCounter() { + return new AtomicInteger(0); + } + @Override + protected EzyEventControllers newEventControllers() { + return null; + } + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAppsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAppsTest.java new file mode 100644 index 00000000..7e493fbd --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyAppsTest.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; +import com.tvd12.ezyfoxserver.setting.EzySimpleAppsSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyAppsTest extends BaseCoreTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzySimpleAppSetting app = new EzySimpleAppSetting(); + app.setName("app#1"); + EzySimpleAppsSetting apps = new EzySimpleAppsSetting(); + apps.setItem(app); + apps.getAppById(-1); + } + +} 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 new file mode 100644 index 00000000..05c78710 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyConfigTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.config.EzySimpleConfig; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyConfigTest extends BaseCoreTest { + + @Test + public void test() { + EzySimpleConfig config = new EzySimpleConfig(); + config.setEzyfoxHome("home"); + config.setEzyfoxVersion("1.0.0"); + config.setLoggerConfigFile("abc"); + assert config.toString() != null; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginTest.java new file mode 100644 index 00000000..bc259325 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimplePluginSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyPluginTest extends BaseCoreTest { + + @Test + public void test() { + EzySimplePluginSetting plugin = new EzySimplePluginSetting(); + plugin.setPriority(10); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginsTest.java new file mode 100644 index 00000000..b8694764 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzyPluginsTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimplePluginsSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyPluginsTest extends BaseCoreTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzySimplePluginsSetting plugins = new EzySimplePluginsSetting(); + plugins.getPluginById(-1); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySettingsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySettingsTest.java new file mode 100644 index 00000000..b37ccbc2 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/config/EzySettingsTest.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.testing.config; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimpleAppsSetting; +import com.tvd12.ezyfoxserver.setting.EzySimplePluginsSetting; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettings; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySettingsTest extends BaseCoreTest { + + @Test + public void test() { + EzySimpleSettings settings = new EzySimpleSettings(); + settings.setWorkerPoolSize(100); + settings.setApplications(new EzySimpleAppsSetting()); + settings.setPlugins(new EzySimplePluginsSetting()); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyCommandTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyCommandTest.java new file mode 100644 index 00000000..cd6fbb93 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyCommandTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.test.base.BaseTest; + +public class EzyCommandTest extends BaseTest { + + @Test + public void test() { + EzyCommand value = EzyCommand.APP_ACCESS; + assert value.getId() == EzyCommand.APP_ACCESS.getId(); + assert value == EzyCommand.valueOf(EzyCommand.APP_ACCESS.getId()); + assert value.getName().equals("APP_ACCESS"); + EzyCommand.valueOf("APP_ACCESS"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyDisconnectReasonTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyDisconnectReasonTest.java new file mode 100644 index 00000000..a6466ccd --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyDisconnectReasonTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.test.base.BaseTest; + +public class EzyDisconnectReasonTest extends BaseTest { + + @Test + public void test() { + EzyDisconnectReason value = EzyDisconnectReason.IDLE; + assert value.getId() == 1; + assert value == EzyDisconnectReason.valueOf(1); + assert value.getName().equals("IDLE"); + EzyDisconnectReason.valueOf("IDLE"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyEventTypeTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyEventTypeTest.java new file mode 100644 index 00000000..f3835ca1 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyEventTypeTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyEventType; +import com.tvd12.test.base.BaseTest; + +public class EzyEventTypeTest extends BaseTest { + + @Test + public void test() { + assert EzyEventType.USER_LOGIN.getId() >= 0; + assert EzyEventType.USER_LOGIN.getName().equals("USER_LOGIN"); + assert EzyEventType.valueOf(EzyEventType.USER_LOGIN.getId()) == EzyEventType.USER_LOGIN; + EzyEventType.values(); + EzyEventType.valueOf("USER_LOGIN"); + } + + @Test() + public void test1() { + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyLoginErrorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyLoginErrorTest.java new file mode 100644 index 00000000..c2328c35 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyLoginErrorTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyLoginError; +import com.tvd12.test.base.BaseTest; + +public class EzyLoginErrorTest extends BaseTest { + + @Test + public void test() { + EzyLoginError value = EzyLoginError.ALREADY_LOGIN; + assert value.getId() == 1; + assert value == EzyLoginError.valueOf(1); + assert value.getName().equals("ALREADY_LOGIN"); + EzyLoginError.valueOf("ALREADY_LOGIN"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionRemoveReasonTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionRemoveReasonTest.java new file mode 100644 index 00000000..4d51d019 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzySessionRemoveReasonTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzySessionRemoveReason; +import com.tvd12.test.base.BaseTest; + +public class EzySessionRemoveReasonTest extends BaseTest { + + @Test + public void test() { + EzySessionRemoveReason reason = EzySessionRemoveReason.UNKNOWN; + assert reason.getId() == 0; + assert reason == EzySessionRemoveReason.valueOf(0); + assert reason.getName().equals("UNKNOWN"); + EzySessionRemoveReason.valueOf("UNKNOWN"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleChildContextTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleChildContextTest.java new file mode 100644 index 00000000..362afc13 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleChildContextTest.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.testing.context; + +import java.util.Set; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.context.EzySimpleChildContext; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleChildContextTest extends BaseCoreTest { + + private EzyServerContext context; + private EzySimpleChildContext ctx; + + public EzySimpleChildContextTest() { + super(); + context = newServerContext(); + context.setProperty(Integer.class, 1); + ctx = new ChildContext(); + ctx.setParent(context); + ctx.setProperty(String.class, "a"); + } + + @Test + public void test1() { + assert ctx.getParent() == context; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + ctx.get(UnsafeCommand.class); + } + + @Test + public void test3() { + assert ctx.get(String.class).equals("a"); + assert ctx.get(Integer.class).equals(1); + } + + public static class ChildContext extends EzySimpleChildContext { + + @SuppressWarnings("rawtypes") + @Override + protected void addUnsafeCommands(Set unsafeCommands) { + unsafeCommands.add(UnsafeCommand.class); + } + } + + public static class UnsafeCommand { + + } +} 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 new file mode 100644 index 00000000..e147e3d9 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/context/EzySimpleServerContextTest.java @@ -0,0 +1,72 @@ +package com.tvd12.ezyfoxserver.testing.context; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.context.EzySimpleAppContext; +import com.tvd12.ezyfoxserver.context.EzySimplePluginContext; +import com.tvd12.ezyfoxserver.context.EzySimpleServerContext; +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; +import com.tvd12.ezyfoxserver.setting.EzySimplePluginSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleServerContextTest extends BaseCoreTest { + + private EzyServerContext context; + + public EzySimpleServerContextTest() { + super(); + context = newServerContext(); + EzySimpleServerContext ctx = ((EzySimpleServerContext)context); + EzySimpleAppContext appContext = new EzySimpleAppContext(); + EzySimpleAppSetting appSetting = new EzySimpleAppSetting(); + appSetting.setName("abcxyz"); + ctx.addAppContext(appSetting, appContext); + + context.setProperty("test.1", "abc"); + assert context.getProperty("test.1") != null; + assert appContext.getProperty("test.1") == null; + + appContext.setProperty("test.2", "abc"); + assert context.getProperty("test.2") == null; + assert appContext.getProperty("test.2") != null; + + EzySimplePluginSetting pluginSetting = new EzySimplePluginSetting(); + pluginSetting.setName("plugin.1"); + EzySimplePluginContext pluginContext = new EzySimplePluginContext(); + ctx.addPluginContext(pluginSetting, pluginContext); + + context.setProperty("test.1", "abc"); + assert context.getProperty("test.1") != null; + assert pluginContext.getProperty("test.1") == null; + + pluginContext.setProperty("test.2", "abc"); + assert context.getProperty("test.2") == null; + assert pluginContext.getProperty("test.2") != null; + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + context.get(Class.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + context.getAppContext(-100); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + context.getPluginContext(-1000); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + context.getAppContext("noone"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + context.getPluginContext("noone"); + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerControllerTest.java new file mode 100644 index 00000000..fc737627 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyAbstractServerControllerTest.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyAbstractServerController; +import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; +import static org.mockito.Mockito.*; + +public class EzyAbstractServerControllerTest extends BaseCoreTest { + + @SuppressWarnings("rawtypes") + @Test + public void test() { + EzySimpleServer server = mock(EzySimpleServer.class); + EzyAppContext appContext = mock(EzyAppContext.class); + ServerController controller = new ServerController(); + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getAppContext(1)).thenReturn(appContext); + assertEquals(controller.getAppContext(serverContext, 1), appContext); + when(serverContext.getAppContext("abc")).thenReturn(appContext); + assertEquals(controller.getAppContext(serverContext, "abc"), appContext); + + EzyServerControllers controllers = mock(EzyServerControllers.class); + + when(server.getControllers()).thenReturn(controllers); + when(serverContext.getServer()).thenReturn(server); + + EzyController ctr = mock(EzyController.class); + when(controllers.getController(EzyCommand.APP_ACCESS)).thenReturn(ctr); + assertEquals(controller.getControllers(serverContext), controllers); + assertEquals(controller.getController(serverContext, EzyCommand.APP_ACCESS), ctr); + } + + private static class ServerController extends EzyAbstractServerController { + @Override + public EzyAppContext getAppContext(EzyServerContext ctx, int appId) { + return super.getAppContext(ctx, appId); + } + + @Override + public EzyAppContext getAppContext(EzyServerContext ctx, String appName) { + return super.getAppContext(ctx, appName); + } + + @Override + public EzyServerControllers getControllers(EzyServerContext ctx) { + return super.getControllers(ctx); + } + + @SuppressWarnings("rawtypes") + @Override + public EzyController getController(EzyServerContext ctx, EzyConstant cmd) { + return super.getController(ctx, cmd); + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyBaseControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyBaseControllerTest.java new file mode 100644 index 00000000..3668c912 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyBaseControllerTest.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyController; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestSessionManager; +import com.tvd12.ezyfoxserver.wrapper.EzyServerControllers; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyRequestMappersImpl; + +public abstract class EzyBaseControllerTest extends BaseCoreTest { + + protected EzyRequestMappers requestMappers = + EzyRequestMappersImpl.builder().build(); + + protected static final String RECONNECT_TOKEN_SALT = "$1$reconnectToken"; + + protected T mapDataToRequestParams(EzyData data) { + return requestMappers.toObject(getCommand(), data); + } + + protected EzyServer getServer(EzyServerContext ctx) { + return ctx.getServer(); + } + + protected EzyManagers getManagers(EzyServerContext ctx) { + return getServer(ctx).getManagers(); + } + + protected EzyServerUserManager getUserManager(EzyServerContext ctx) { + return getManagers(ctx).getManager(EzyServerUserManager.class); + } + + protected MyTestSessionManager getSessionManager(EzyServerContext ctx) { + return (MyTestSessionManager) getManagers(ctx).getManager(EzySessionManager.class); + } + + protected EzyAppContext getAppContext(EzyServerContext ctx, int appId) { + return ctx.getAppContext(appId); + } + + protected EzyAppContext getAppContext(EzyServerContext ctx, String appName) { + return ctx.getAppContext(appName); + } + + 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 abstract EzyConstant getCommand(); + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeController2Test.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeController2Test.java new file mode 100644 index 00000000..99644682 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeController2Test.java @@ -0,0 +1,67 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import static org.testng.Assert.assertEquals; + +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyHandShakeController; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyHandShakeParams; +import com.tvd12.ezyfoxserver.request.EzyHandShakeRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeRequest; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; + +public class EzyHandShakeController2Test extends EzyBaseControllerTest { + + @Test + public void test() { + EzyServerContext ctx = newServerContext(); + EzySession first = getSessionManager(ctx).borrowSession(EzyConnectionType.SOCKET); + System.err.println("first.token: " + first); + System.err.println("alive sessions: " + getSessionManager(ctx).getAliveSessions()); + assertEquals(getSessionManager(ctx).containsSession(first.getReconnectToken()), true); + EzySession session = getSessionManager(ctx).borrowSession(EzyConnectionType.SOCKET); + System.err.println("session: " + session); + EzyArray data = newHandShakeData(first.getReconnectToken()); + EzyHandShakeParams requestParams = mapDataToRequestParams(data); + EzyHandShakeRequest request = EzySimpleHandShakeRequest.builder() + .params(requestParams) + .session(session) + .build(); + assertEquals(first.getReconnectToken(), requestParams.getReconnectToken()); + EzyHandShakeController controller = new EzyHandShakeController(); + controller.handle(ctx, request); + } + + private EzyArray newHandShakeData(String reconnectToken) { + KeyPair keyPair = newRSAKeys(); + return newArrayBuilder() + .append("adroid#1") + .append(EzyBase64.encode2utf(keyPair.getPublic().getEncoded())) + .append(reconnectToken) + .append("android") + .append("1.0.0") + .build(); + } + + protected EzySession newSession(String reconnectToken) { + KeyPair keyPair = newRSAKeys(); + EzySession session = super.newSession(); + session.setReconnectToken(reconnectToken); + session.setPublicKey(keyPair.getPublic().getEncoded()); + return session; + } + + @Override + protected EzyConstant getCommand() { + return EzyCommand.HANDSHAKE; + } + +} 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 new file mode 100644 index 00000000..8f91ca31 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyHandShakeControllerTest.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyHandShakeController; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyHandShakeRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeRequest; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; + +public class EzyHandShakeControllerTest extends EzyBaseControllerTest { + + @Test + public void test() { + EzyServerContext ctx = newServerContext(); + EzySession session = newSession(); + EzyArray data = newHandShakeData(); + EzyHandShakeController controller = new EzyHandShakeController(); + EzyHandShakeRequest request = EzySimpleHandShakeRequest.builder() + .params(mapDataToRequestParams(data)) + .session(session) + .build(); + controller.handle(ctx, request); + } + + private EzyArray newHandShakeData() { + KeyPair keyPair = newRSAKeys(); + return newArrayBuilder() + .append("adroid#1") + .append(EzyBase64.encode2utf(keyPair.getPublic().getEncoded())) + .append("reconnectToken#1") + .append("android") + .append("1.0.0") + .build(); + } + + @Override + protected EzySession newSession() { + KeyPair keyPair = newRSAKeys(); + EzySession session = super.newSession(); + session.setReconnectToken("reconnectToken#1"); + session.setPublicKey(keyPair.getPublic().getEncoded()); + return session; + } + + @Override + protected EzyConstant getCommand() { + return EzyCommand.HANDSHAKE; + } + +} 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 new file mode 100644 index 00000000..ec316591 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyLoginControllerTest.java @@ -0,0 +1,92 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyLoginController; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.event.EzyUserLoginEvent; +import com.tvd12.ezyfoxserver.exception.EzyLoginErrorException; +import com.tvd12.ezyfoxserver.request.EzyLoginRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleLoginRequest; + +public class EzyLoginControllerTest extends EzyBaseControllerTest { + + @Test + public void test() { + EzyServerContext ctx = newServerContext(); + EzySession session = newSession(); + session.setReconnectToken("abcdef"); + EzyArray data = newLoginData(); + EzyLoginController controller = new EzyLoginController(); + EzyLoginRequest request = EzySimpleLoginRequest.builder() + .params(mapDataToRequestParams(data)) + .session(session) + .build(); + controller.handle(ctx, request); + } + + @Test(expectedExceptions = {EzyLoginErrorException.class}) + public void test1() { + EzyServerContext ctx = newServerContext(); + EzySession session = newSession(); + session.setReconnectToken("abcdef"); + EzyArray data = newLoginData1(); + EzyLoginController controller = new EzyLoginController() { + @Override + protected void process(EzyServerContext ctx, EzyUserLoginEvent event) { + throw new EzyLoginErrorException(); + } + }; + EzyLoginRequest request = EzySimpleLoginRequest.builder() + .params(mapDataToRequestParams(data)) + .session(session) + .build(); + controller.handle(ctx, request); + } + + @Test(expectedExceptions = {EzyLoginErrorException.class}) + public void test2() { + EzyServerContext ctx = newServerContext(); + EzySession session = newSession(); + session.setReconnectToken("abcdef"); + EzyArray data = newLoginData(); + EzyLoginController controller = new EzyLoginController() { + @Override + protected void firePluginEvent(EzyServerContext ctx, EzyUserLoginEvent event) { + throw new EzyLoginErrorException(); + } + }; + EzyLoginRequest request = EzySimpleLoginRequest.builder() + .params(mapDataToRequestParams(data)) + .session(session) + .build(); + controller.handle(ctx, request); + } + + private EzyArray newLoginData() { + return newArrayBuilder() + .append("dungtv") + .append("123456") + .append(newArrayBuilder() + .append("123456")) + .build(); + } + + private EzyArray newLoginData1() { + return newArrayBuilder() + .append("dungtv") + .append("123456") + .append(newArrayBuilder()) + .build(); + } + + @Override + protected EzyConstant getCommand() { + return EzyCommand.LOGIN; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyMessageControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyMessageControllerTest.java new file mode 100644 index 00000000..b8b72f80 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyMessageControllerTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.controller.EzyMessageController; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyMessageControllerTest extends BaseCoreTest { + + @Test + public void test() { + MyEzyMessageController controller = new MyEzyMessageController(); + controller.newArrayBuilder(); + } + + public class MyEzyMessageController extends EzyMessageController { + @Override + public EzyArrayBuilder newArrayBuilder() { + return super.newArrayBuilder(); + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyReconnectControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyReconnectControllerTest.java new file mode 100644 index 00000000..29ef1292 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyReconnectControllerTest.java @@ -0,0 +1,82 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyReconnectController; +import com.tvd12.ezyfoxserver.delegate.EzyAbstractSessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.request.EzyReconnectRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleReconnectParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleReconnectRequest; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.testing.MyTestUser; + +public class EzyReconnectControllerTest extends EzyBaseControllerTest { + + private EzyServerContext context; + + public EzyReconnectControllerTest() { + super(); + context = newServerContext(); + } + + @Test + public void test1() { + EzyAbstractSession oldSession = getSessionManager(context).borrowSession(EzyConnectionType.SOCKET); + oldSession.setDelegate(new EzyAbstractSessionDelegate() { + }); + EzySession session = newSession(); + EzyReconnectRequest request = EzySimpleReconnectRequest.builder() + .params(EzySimpleReconnectParams.builder().build()) + .session(session) + .oldSession(oldSession) + .build(); + EzyReconnectController controller = new EzyReconnectController(); + controller.handle(context, request); + } + + @Test + public void test2() { + MyTestUser user = new MyTestUser(); + user.setName("dungtv"); + EzyAbstractSession oldSession = getSessionManager(context).borrowSession(EzyConnectionType.SOCKET); + oldSession.setDelegate(new EzyAbstractSessionDelegate() { + }); + user.addSession(oldSession); + getUserManager(context).addUser(oldSession, user); + EzySession session = newSession(); + EzyReconnectController controller = new EzyReconnectController(); + session.setReconnectToken("abcdef"); + EzyReconnectRequest request = EzySimpleReconnectRequest.builder() + .params(EzySimpleReconnectParams.builder().build()) + .session(session) + .oldSession(oldSession) + .build(); + controller.handle(context, request); + } + + @SuppressWarnings("unused") + private EzyArray newHandShakeData(String token) { + KeyPair keyPair = newRSAKeys(); + return newArrayBuilder() + .append("adroid#1") + .append(EzyBase64.encode2utf(keyPair.getPublic().getEncoded())) + .append(token) + .append("android") + .append("1.0.0") + .build(); + } + + @Override + protected EzyConstant getCommand() { + return EzyCommand.HANDSHAKE; + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyRequestAppControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyRequestAppControllerTest.java new file mode 100644 index 00000000..da90badb --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/controller/EzyRequestAppControllerTest.java @@ -0,0 +1,73 @@ +package com.tvd12.ezyfoxserver.testing.controller; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.EzySimpleApplication; +import com.tvd12.ezyfoxserver.command.EzyFireEvent; +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.controller.EzyRequestAppController; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.event.EzyEvent; +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; +import com.tvd12.ezyfoxserver.request.EzyRequestAppRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppRequest; +import com.tvd12.ezyfoxserver.setting.EzySimpleAppSetting; +import com.tvd12.ezyfoxserver.testing.BaseCoreContextTest; +import com.tvd12.ezyfoxserver.testing.MyTestUser; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyAppUserManagerImpl; + +public class EzyRequestAppControllerTest extends BaseCoreContextTest { + + private MyTestUser user; + private EzySession session; + + @Test + public void test() { + EzyRequestAppParams data = EzySimpleRequestAppParams.builder() + .appId(1) + .data(newArrayBuilder().build()) + .build(); + EzyRequestAppController controller = new EzyRequestAppController(); + EzyRequestAppRequest request = EzySimpleRequestAppRequest.builder() + .params(data) + .user(user) + .session(session) + .build(); + EzyServerContext ctx = newServerContext(); + controller.handle(ctx, request); + } + + @Override + protected EzyServerContext newServerContext() { + session = newSession(); + session.setReconnectToken("abc"); + user = new MyTestUser(); + user.setName("dungtv"); + user.addSession(session); + EzyAppContext appContext = mock(EzyAppContext.class); + when(appContext.get(EzyFireEvent.class)).thenReturn(new EzyFireEvent() { + + @Override + public void fire(EzyConstant type, EzyEvent event) { + + } + }); + EzySimpleApplication app = new EzySimpleApplication(); + app.setSetting(new EzySimpleAppSetting()); + app.setUserManager(new EzyAppUserManagerImpl()); + app.getUserManager().addUser(user); + + when(appContext.getApp()).thenReturn(app); + + EzyServerContext serverContext = mock(EzyServerContext.class); + when(serverContext.getAppContext(1)).thenReturn(appContext); + return serverContext; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/delegate/EzySessionAdapterTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/delegate/EzySessionAdapterTest.java new file mode 100644 index 00000000..fb552b40 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/delegate/EzySessionAdapterTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing.delegate; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzySessionRemoveReason; +import com.tvd12.ezyfoxserver.delegate.EzyAbstractSessionDelegate; +import com.tvd12.ezyfoxserver.delegate.EzySessionDelegate; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.test.base.BaseTest; + +public class EzySessionAdapterTest extends BaseTest { + + @Test + public void test() { + EzySessionDelegate delegate = new EzyAbstractSessionDelegate() { + }; + delegate.onSessionReturned(EzySessionRemoveReason.ANOTHER_DEVICE_LOGIN); + delegate.onSessionLoggedIn(new EzySimpleUser()); + } + +} 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 new file mode 100644 index 00000000..e3c1ab81 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzyAbstractSessionTest.java @@ -0,0 +1,78 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import static org.testng.Assert.assertEquals; + +import java.net.InetSocketAddress; +import java.net.SocketAddress; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestSession; + +public class EzyAbstractSessionTest extends BaseCoreTest { + + @Test + public void test() { + MyTestSession session = new MyTestSession(); + session.setId(100); + session.setPrivateKey(new byte[] {1, 2, 3}); + session.setFullReconnectToken("123456"); + session.addReadBytes(10); + session.addWrittenBytes(10); + session.setLoggedInTime(12345); + session.setMaxWaitingTime(123); + session.setMaxIdleTime(12345L); + assertEquals(session.getPrivateKey(), new byte[] {1, 2, 3}); + assertEquals(session.getFullReconnectToken(), "123456"); + assertEquals(session.getReadBytes(), 10); + assertEquals(session.getWrittenBytes(), 10); + assertEquals(session.getLoggedInTime(), 12345L); + assertEquals(session.getMaxWaitingTime(), 123L); + MyTestSession session2 = new MyTestSession(); + session2.setId(1); + + MyTestSession session3 = new MyTestSession(); + session3.setId(100); + + assert !session.equals(null); + assert session.equals(session); + assert !session.equals(new Object()); + assert !session.equals(session2); + assert !session.equals(new Session()); + assert session.equals(session3); + assert session.hashCode() != session2.hashCode(); + } + + private static class Session extends EzyAbstractSession { + private static final long serialVersionUID = -3656335144134244222L; + + @Override + public SocketAddress getClientAddress() { + return new InetSocketAddress(10); + } + + @Override + public SocketAddress getServerAddress() { + return new InetSocketAddress(10); + } + + @Override + public void close() { + + } + + @Override + public void disconnect() { + + } + + @Override + protected void sendData(EzyData data, EzyTransportType type) { + } + + } +} 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 new file mode 100644 index 00000000..31ad35f8 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/entity/EzySimpleUserTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleUserTest extends BaseTest { + + @Test + public void test() { + EzySimpleUser user = new EzySimpleUser(); + user.setId(1); + user.setPassword("abc"); + assert user.getPassword().equals("abc"); + user.setName("dungtv1"); + + EzySimpleUser user2 = new EzySimpleUser(); + user2.setPassword("abc"); + user2.setId(2); + assert user2.getPassword().equals("abc"); + user.setName("dungtv2"); + + assert !user.equals(user2); + assert user.hashCode() != user2.hashCode(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyDisconnectEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyDisconnectEventImplTest.java new file mode 100644 index 00000000..81844a69 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyDisconnectEventImplTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.event; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyUserDisconnectEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserDisconnectEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyDisconnectEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyUser user = newUser(); + EzyUserDisconnectEvent event = (EzyUserDisconnectEvent) EzyUserDisconnectEventImpl.builder() + .user(user) + .reason(EzyDisconnectReason.IDLE) + .build(); + assert event.getUser() == user; + assert event.getReason() == EzyDisconnectReason.IDLE; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyReconnectEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyReconnectEventImplTest.java new file mode 100644 index 00000000..9582b730 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyReconnectEventImplTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.event; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyUserReconnectEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserReconnectEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyReconnectEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyUser user = new EzySimpleUser(); + EzyUserReconnectEvent event = (EzyUserReconnectEvent) EzyUserReconnectEventImpl.builder() + .user(user) + .build(); + assert event.getUser() == user; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyRequestAppEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyRequestAppEventImplTest.java new file mode 100644 index 00000000..fdd6388e --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyRequestAppEventImplTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.event; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.event.EzyUserRequestAppEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserRequestAppEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyRequestAppEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyUser user = newUser(); + EzyArray data = newArrayBuilder().append(100).build(); + EzyUserRequestAppEvent event = (EzyUserRequestAppEvent) EzyUserRequestAppEventImpl.builder() + .user(user) + .data(data) + .build(); + assert event.getData() == data; + assert event.getUser() == user; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyServerReadyEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyServerReadyEventImplTest.java new file mode 100644 index 00000000..7e38c87e --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyServerReadyEventImplTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.event; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.event.impl.EzyServerReadyEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyServerReadyEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyServerReadyEventImpl.builder() + .build(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyUserLoginEventImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyUserLoginEventImplTest.java new file mode 100644 index 00000000..2258dc59 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/event/EzyUserLoginEventImplTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.testing.event; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.event.EzyUserLoginEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyUserLoginEventImpl; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyUserLoginEventImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyArray data = newArrayBuilder().build(); + data.add("123.abc"); + EzyObject output = newObjectBuilder().append("1", "a").build(); + EzyObject output2 = newObjectBuilder().append("2", "b").build(); + EzyUserLoginEvent event = EzyUserLoginEventImpl.builder() + .data(data) + .output(output) + .username("dungtv") + .password("123") + .build(); + assert event.getData() == data; + assert event.getUsername().equals("dungtv"); + assert event.getPassword().equals("123"); + assert event.getOutput() == output; + + event.setUsername("new login name"); + event.setPassword("new password"); + event.setOutput(output2); + + assert event.getUsername().equals("new login name"); + assert event.getPassword().equals("new password"); + assert event.getOutput() == output2; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyRequestHandleExceptionTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyRequestHandleExceptionTest.java new file mode 100644 index 00000000..65b93c3d --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyRequestHandleExceptionTest.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.testing.exception; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyRequestHandleException; +import com.tvd12.test.base.BaseTest; + +public class EzyRequestHandleExceptionTest extends BaseTest { + + @Test(expectedExceptions = {EzyRequestHandleException.class}) + public void test() { + throw new EzyRequestHandleException("msg", new Exception()); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyResponseHandleExceptionTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyResponseHandleExceptionTest.java new file mode 100644 index 00000000..08dc32d4 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyResponseHandleExceptionTest.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.testing.exception; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyResponseHandleException; +import com.tvd12.test.base.BaseTest; + +public class EzyResponseHandleExceptionTest extends BaseTest { + + @Test(expectedExceptions = {EzyResponseHandleException.class}) + public void test() { + throw new EzyResponseHandleException("msg", new Exception()); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyAbstractSessionFactoryTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyAbstractSessionFactoryTest.java new file mode 100644 index 00000000..34815a70 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/factory/EzyAbstractSessionFactoryTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.factory; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.testing.MyTestSessionFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractSessionFactoryTest extends BaseTest { + + @Test + public void test() { + MyTestSessionFactory factory = new MyTestSessionFactory(); + assert factory.newProduct() != null; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyRequestFactoryTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyRequestFactoryTest.java new file mode 100644 index 00000000..cbfecb29 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzyRequestFactoryTest.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.testing.handler; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.handler.EzyRequestFactory; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleAccessAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleLoginParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyRequestFactoryTest extends BaseCoreTest { + + @Test + public void test() { + EzyUser user = newUser(); + EzySession session = newSession(); + EzyRequestFactory factory = EzyRequestFactory.builder() + .userSupplier(() -> user) + .sessionSupplier(() -> session) + .build(); + factory.newRequest(EzyCommand.LOGIN, EzySimpleLoginParams.builder().build()); + factory.newRequest(EzyCommand.APP_ACCESS, EzySimpleAccessAppParams.builder().build()); + factory.newRequest(EzyCommand.APP_REQUEST, EzySimpleRequestAppParams.builder().build()); + factory.newRequest(EzyCommand.HANDSHAKE, EzySimpleHandShakeParams.builder().build()); + } + +} 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 new file mode 100644 index 00000000..8566117b --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/handler/EzySimpleDataHandlerTest.java @@ -0,0 +1,81 @@ +package com.tvd12.ezyfoxserver.testing.handler; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.entity.EzySimpleUser; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestDataHandler; + +public class EzySimpleDataHandlerTest extends BaseCoreTest { + @Test + public void test1() throws Exception { + EzyServerContext context = newServerContext(); + EzyAppContext appContext = context.getAppContext("ezyfox-chat"); + MyTestDataHandler handler = new MyTestDataHandler(); + handler.setContext(context); + handler.getAppContext(appContext.getApp().getSetting().getId()); + handler.borrowSession(); + handler.sessionActive(); + + EzyArray message = newArrayBuilder() + .append(EzyCommand.LOGIN.getId()) + .append(newArrayBuilder() + .append("") + .append("") + .append(newArrayBuilder())) + .build(); + + handler.dataReceived(message); + handler.channelInactive(); + handler.onSessionReturned(EzyDisconnectReason.NOT_LOGGED_IN); + } + + @Test + public void test2() throws Exception { + EzySession session = newSession(); + session.setReconnectToken("123"); + EzySimpleUser user = newUser(); + user.setName("dungtv"); + user.addSession(session); + EzyServerContext context = newServerContext(); + MyTestDataHandler handler = new MyTestDataHandler(session); + handler.setContext(context); + handler.borrowSession(); + handler.sessionActive(); + handler.onSessionLoggedIn(user); + + EzyArray message = newArrayBuilder() + .append(EzyCommand.APP_ACCESS.getId()) + .append(newArrayBuilder() + .append("ezyfox-chat")) + .build(); + + handler.dataReceived(message); + handler.onSessionReturned(EzyDisconnectReason.NOT_LOGGED_IN); + } + + @Test + public void test3() throws Exception { + EzyServerContext context = newServerContext(); + MyTestDataHandler handler = new MyTestDataHandler(); + handler.setContext(context); + handler.borrowSession(); + handler.sessionActive(); + + EzyArray message = newArrayBuilder() + .append(EzyCommand.LOGIN.getId()) + .append(newArrayBuilder() + .append("")) + .build(); + + handler.dataReceived(message); + handler.channelInactive(); + handler.onSessionReturned(EzyDisconnectReason.NOT_LOGGED_IN); + } +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyInterceptorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyInterceptorTest.java new file mode 100644 index 00000000..474bed75 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyInterceptorTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.interceptor; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyInterceptorTest extends BaseCoreTest { + + @SuppressWarnings("unchecked") + @Test + public void test() throws Exception { + EzyServerContext context = newServerContext(); + EzyInterceptor.ALWAYS_PASS.intercept(context, null); + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyServerUserInterceptorTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyServerUserInterceptorTest.java new file mode 100644 index 00000000..d8623354 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/interceptor/EzyServerUserInterceptorTest.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.testing.interceptor; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.exception.NotAuthorizedException; +import com.tvd12.ezyfoxserver.interceptor.EzyServerUserInterceptor; +import com.tvd12.ezyfoxserver.request.EzyRequestAppRequest; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppRequest; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestUser; + +public class EzyServerUserInterceptorTest extends BaseCoreTest { + + @Test(expectedExceptions = {NotAuthorizedException.class}) + public void test() throws Exception { + EzyServerContext context = newServerContext(); + EzyServerUserInterceptor interceptor = + new EzyServerUserInterceptor<>(); + EzyRequestAppRequest request = EzySimpleRequestAppRequest.builder() + .build(); + interceptor.intercept(context, request); + } + + @Test + public void test1() throws Exception { + EzyServerContext context = newServerContext(); + EzyServerUserInterceptor interceptor = + new EzyServerUserInterceptor<>(); + EzyRequestAppRequest request = EzySimpleRequestAppRequest.builder() + .user(new MyTestUser()) + .build(); + interceptor.intercept(context, request); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/jaxberror/ClassA.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/jaxberror/ClassA.java new file mode 100644 index 00000000..0414cde6 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/jaxberror/ClassA.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.testing.jaxberror; + +public class ClassA { + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/jaxberror/jaxb.properties b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/jaxberror/jaxb.properties new file mode 100644 index 00000000..e69de29b diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/plugincontroller/EzyServerReadyControllerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/plugincontroller/EzyServerReadyControllerTest.java new file mode 100644 index 00000000..34a52eba --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/plugincontroller/EzyServerReadyControllerTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.plugincontroller; + +import org.mockito.Mockito; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.context.EzyPluginContext; +import com.tvd12.ezyfoxserver.event.EzyServerReadyEvent; +import com.tvd12.ezyfoxserver.event.impl.EzyServerReadyEventImpl; +import com.tvd12.ezyfoxserver.plugincontroller.EzyServerReadyController; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzyServerReadyControllerTest extends BaseCoreTest { + + @Test + public void test() { + EzyServerReadyEvent event = EzyServerReadyEventImpl.builder() + .build(); + EzyPluginContext context = Mockito.mock(EzyPluginContext.class); + EzyServerReadyController controller = new EzyServerReadyController(); + controller.handle(context, event); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleAccessAppRequestTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleAccessAppRequestTest.java new file mode 100644 index 00000000..bb5661c9 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleAccessAppRequestTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.request; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.request.EzyAccessAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleAccessAppParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleAccessAppRequestTest extends BaseCoreTest { + + @Test + public void test() { + EzyAccessAppParams request = EzySimpleAccessAppParams.builder() + .appName("chat") + .build(); + request.toString(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleHandShakeRequestTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleHandShakeRequestTest.java new file mode 100644 index 00000000..d72722c6 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleHandShakeRequestTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.request; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.request.EzyHandShakeParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleHandShakeParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleHandShakeRequestTest extends BaseCoreTest { + + @Test + public void test() { + EzyHandShakeParams request = EzySimpleHandShakeParams.builder() + .clientId("abc") + .clientKey("def") + .reconnectToken("haha") + .build(); + request.toString(); + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleLoginRequestTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleLoginRequestTest.java new file mode 100644 index 00000000..7bcd2bf1 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleLoginRequestTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing.request; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.request.EzyLoginParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleLoginParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleLoginRequestTest extends BaseCoreTest { + + @Test + public void test() { + EzyLoginParams request = EzySimpleLoginParams.builder() + .data(newArrayBuilder().build()) + .password("") + .username("") + .build(); + request.toString(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleRequestAppRequestTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleRequestAppRequestTest.java new file mode 100644 index 00000000..8e131eef --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/request/EzySimpleRequestAppRequestTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.request; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; +import com.tvd12.ezyfoxserver.request.impl.EzySimpleRequestAppParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleRequestAppRequestTest extends BaseCoreTest { + + @Test + public void test() { + EzyRequestAppParams request = EzySimpleRequestAppParams.builder() + .appId(1) + .data(newArrayBuilder().build()) + .build(); + request.toString(); + + assert request.getAppId() == 1; + assert request.getData() instanceof EzyArray; + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyAbstractResponseTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyAbstractResponseTest.java new file mode 100644 index 00000000..6a978dd3 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyAbstractResponseTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.response; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.response.EzyAbstractResponse; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractResponseTest extends BaseTest { + + @Test + public void test() { + EzyAbstractResponse response = new EzyAbstractResponse() { + }; + response.setAppId(1); + response.setCommand(EzyCommand.APP_ACCESS); + response.setData(123); + + assert response.getAppId() == 1; + assert response.getCommand() == EzyCommand.APP_ACCESS; + assert response.getData().equals(new Integer(123)); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyErrorResponseTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyErrorResponseTest.java new file mode 100644 index 00000000..c8a3c163 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyErrorResponseTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.response; + +import org.testng.annotations.Test; + +import com.tvd12.test.base.BaseTest; + +public class EzyErrorResponseTest extends BaseTest { + + @Test + public void test() { + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLiteResponseTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLiteResponseTest.java new file mode 100644 index 00000000..7ef5267c --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLiteResponseTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.response; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.response.EzyLiteResponse; +import com.tvd12.test.base.BaseTest; + +public class EzyLiteResponseTest extends BaseTest { + + @Test + public void test() { + EzyLiteResponse response = new EzyLiteResponse(); + response.setAppId(1); + response.setCommand(EzyCommand.APP_ACCESS); + response.setData(123); + + assert response.getAppId() == 1; + assert response.getCommand() == EzyCommand.APP_ACCESS; + assert response.getData().equals(new Integer(123)); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLoginErrorResponseTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLoginErrorResponseTest.java new file mode 100644 index 00000000..91564590 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/response/EzyLoginErrorResponseTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.response; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.response.EzyLoginErrorResponse; +import com.tvd12.test.base.BaseTest; + +public class EzyLoginErrorResponseTest extends BaseTest { + + @Test + public void test() { + EzyLoginErrorResponse response = EzyLoginErrorResponse.builder() + .code(10) + .message("123") + .build(); + EzyArray data = (EzyArray) response.getData(); + assert data.get(0).equals(new Integer(10)); + assert data.get(1).equals("123"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzyResponseSerializerTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzyResponseSerializerTest.java new file mode 100644 index 00000000..578a6059 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzyResponseSerializerTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.response.EzyResponse; +import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; + +public class EzyResponseSerializerTest { + + @Test + public void test() { + ResponseSerializer ser = new ResponseSerializer(); + ser.serializeToObject(null); + } + + public static class ResponseSerializer implements EzyResponseSerializer { + @Override + public T serialize(EzyResponse response, Class outType) { + return null; + } + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleJsonMapperTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleJsonMapperTest.java new file mode 100644 index 00000000..49de3a2b --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleJsonMapperTest.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.testing.service; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.tvd12.ezyfoxserver.mapping.jackson.EzyJsonMapper; +import com.tvd12.ezyfoxserver.mapping.jackson.EzySimpleJsonMapper; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; +import lombok.Setter; + +public class EzySimpleJsonMapperTest extends BaseTest { + + @Test + public void test() { + EzyJsonMapper mapper = EzySimpleJsonMapper.builder() + .build(); + assert mapper.writeAsString(new ClassA()) == null; + } + + @Setter + @Getter + public static class ClassA { + + @JsonProperty + public String getValue() throws Exception { + throw new Exception(); + } + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleXmlReaderTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleXmlReaderTest.java new file mode 100644 index 00000000..93ef51af --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/service/EzySimpleXmlReaderTest.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.testing.service; + +import java.io.File; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.mapping.jackson.EzySimpleJsonMapper; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzySimplXmlMapper; +import com.tvd12.ezyfoxserver.mapping.jaxb.EzyXmlReader; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettings; +import com.tvd12.ezyfoxserver.testing.jaxberror.ClassA; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleXmlReaderTest extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyXmlReader reader = EzySimplXmlMapper.builder() + .contextClass(ClassA.class) + .build(); + reader.read(new File("pom.xml"), ClassB.class); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyXmlReader reader = EzySimplXmlMapper.builder() + .contextPath("com.tvd12.ezyfoxserver.mapping") + .classLoader(getClass().getClassLoader()) + .build(); + reader.read(new File("pom.xml"), ClassB.class); + } + + @Test + public void test3() { + EzyXmlReader reader = EzySimplXmlMapper.builder() + .contextPath("com.tvd12.ezyfoxserver") + .classLoader(getClass().getClassLoader()) + .build(); + EzySimpleSettings settings = + reader.read(new File("src/main/resources/ezy-settings.xml"), EzySimpleSettings.class); + System.out.println(EzySimpleJsonMapper.builder().build().writeAsString(settings)); + } + + public static class ClassB { + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyAppsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyAppsTest.java new file mode 100644 index 00000000..500ff76a --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyAppsTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimpleAppsSetting; +import com.tvd12.test.base.BaseTest; + +public class EzyAppsTest extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzySimpleAppsSetting apps = new EzySimpleAppsSetting(); + apps.getAppByName("zzz"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFileNamesTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFileNamesTest.java new file mode 100644 index 00000000..dfe250de --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFileNamesTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import com.tvd12.ezyfoxserver.setting.EzyFileNames; +import com.tvd12.test.base.BaseTest; + +public class EzyFileNamesTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyFileNames.class; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFolderNamesTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFolderNamesTest.java new file mode 100644 index 00000000..5a7e97df --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyFolderNamesTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import com.tvd12.ezyfoxserver.setting.EzyFolderNamesSetting; +import com.tvd12.test.base.BaseTest; + +public class EzyFolderNamesTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyFolderNamesSetting.class; + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyPluginsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyPluginsTest.java new file mode 100644 index 00000000..3cded017 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzyPluginsTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimplePluginsSetting; +import com.tvd12.test.base.BaseTest; + +public class EzyPluginsTest extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzySimplePluginsSetting plugins = new EzySimplePluginsSetting(); + plugins.getPluginByName("zzz"); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySettingsTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySettingsTest.java new file mode 100644 index 00000000..e9814baa --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySettingsTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimpleAppsSetting; +import com.tvd12.ezyfoxserver.setting.EzySimplePluginsSetting; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettings; +import com.tvd12.ezyfoxserver.setting.EzySimpleSocketSetting; +import com.tvd12.ezyfoxserver.setting.EzySimpleWebSocketSetting; +import com.tvd12.test.base.BaseTest; + +public class EzySettingsTest extends BaseTest { + + @Test + public void test() { + EzySimpleSettings settings = new EzySimpleSettings(); + settings.setWorkerPoolSize(1); + settings.setSocket(new EzySimpleSocketSetting()); + settings.setPlugins(new EzySimplePluginsSetting()); + settings.setApplications(new EzySimpleAppsSetting()); + settings.setWebsocket(new EzySimpleWebSocketSetting()); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigTest.java new file mode 100644 index 00000000..696de02f --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/setting/EzySslConfigTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.setting; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.setting.EzySimpleSslConfigSetting; +import com.tvd12.test.base.BaseTest; + +public class EzySslConfigTest extends BaseTest { + + @Test + public void test() { + EzySimpleSslConfigSetting config = new EzySimpleSslConfigSetting(); + config.setFile("file"); + config.setLoader("loader"); + config.setContextFactoryBuilder("builder"); + } + +} 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 new file mode 100644 index 00000000..3b5f2eda --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySimpleSslContextFactoryTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.testing.ssl; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfig; +import com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactory; +import com.tvd12.ezyfoxserver.ssl.EzySslConfig; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySimpleSslContextFactoryTest extends BaseCoreTest { + + @Test + public void test() { + new EzySimpleSslContextFactory() { + protected String getAlgorithmProperty() { + return "zzfsdff"; + }; + + @Override + public String getAlgorithm(EzySslConfig config) { + return super.getAlgorithm(config); + } + }.getAlgorithm(new EzySimpleSslConfig()); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySslTrustManagerFactoryTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySslTrustManagerFactoryTest.java new file mode 100644 index 00000000..b5d87561 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/ssl/EzySslTrustManagerFactoryTest.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.testing.ssl; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Method; +import java.security.KeyStore; + +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.ssl.EzySslTrustManagerFactory; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; + +public class EzySslTrustManagerFactoryTest extends BaseCoreTest { + + @Test + public void test() throws Exception { + EzySslTrustManagerFactory factory = new EzySslTrustManagerFactory(); + Method engineInit1 = EzySslTrustManagerFactory.class + .getDeclaredMethod("engineInit", ManagerFactoryParameters.class); + engineInit1.setAccessible(true); + ManagerFactoryParameters managerFactoryParameters = + mock(ManagerFactoryParameters.class); + engineInit1.invoke(factory, managerFactoryParameters); + + Method engineInit2 = EzySslTrustManagerFactory.class + .getDeclaredMethod("engineInit", KeyStore.class); + engineInit2.setAccessible(true); + KeyStore keyStore = KeyStore.getInstance("JKS"); + engineInit2.invoke(factory, keyStore); + + Method engineGetTrustManagers = EzySslTrustManagerFactory.class + .getDeclaredMethod("engineGetTrustManagers"); + engineGetTrustManagers.setAccessible(true); + TrustManager[] trustManagers = (TrustManager[]) engineGetTrustManagers.invoke(factory); + X509TrustManager trustManagerAt0 = (X509TrustManager) trustManagers[0]; + trustManagerAt0.getAcceptedIssuers(); + trustManagerAt0.checkClientTrusted(null, null); + trustManagerAt0.checkServerTrusted(null, null); + } + + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBannerPrinterTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBannerPrinterTest.java new file mode 100644 index 00000000..7fc1483d --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBannerPrinterTest.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.io.IOException; +import java.io.InputStream; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyBannerPrinter; +import com.tvd12.test.base.BaseTest; + +public class EzyBannerPrinterTest extends BaseTest { + + @Test + public void test() { + new EzyBannerPrinter() { + @Override + protected InputStream getBannerInputStream() { + return new InputStream() { + + @Override + public int read() throws IOException { + throw new IOException(); + } + }; + } + }.getBannerString(); + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyManagersImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyManagersImplTest.java new file mode 100644 index 00000000..be2e8917 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyManagersImplTest.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.testing.wrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyStartable; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyManagersImpl; + +public class EzyManagersImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyManagers managers = EzyManagersImpl.builder().build(); + managers.addManager(Manager1.class, new Manager1()); + managers.addManager(Manager2.class, new Manager2()); + managers.addManager(Manager3.class, new Manager3()); + managers.startManagers(); + managers.stopManagers(); + } + + public static class Manager1 implements EzyStartable, EzyDestroyable { + + @Override + public void destroy() { + } + + @Override + public void start() throws Exception { + } + + } + + public static class Manager2 { + + } + + public static class Manager3 implements EzyStartable, EzyDestroyable { + + @Override + public void destroy() { + throw new RuntimeException(); + } + + @Override + public void start() throws Exception { + throw new RuntimeException(); + } + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyRequestMappersImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyRequestMappersImplTest.java new file mode 100644 index 00000000..0f7e510e --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyRequestMappersImplTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.testing.wrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyCommand; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.request.EzyRequestAppParams; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.wrapper.EzyRequestMappers; +import com.tvd12.ezyfoxserver.wrapper.impl.EzyRequestMappersImpl; + +public class EzyRequestMappersImplTest extends BaseCoreTest { + + @Test + public void test() { + EzyArray array = newArrayBuilder() + .append(1) + .append(newArrayBuilder().build()) + .build(); + EzyRequestMappers mappers = EzyRequestMappersImpl.builder() + .build(); + EzyRequestAppParams request = mappers.toObject(EzyCommand.APP_REQUEST, array); + assert request.getAppId() == 1; + } + +} 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 new file mode 100644 index 00000000..55b150c2 --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzySimpleSessionManagerTest.java @@ -0,0 +1,85 @@ +package com.tvd12.ezyfoxserver.testing.wrapper; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.util.UUID; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.constant.EzySessionRemoveReason; +import com.tvd12.ezyfoxserver.delegate.EzyAbstractSessionDelegate; +import com.tvd12.ezyfoxserver.service.EzySessionTokenGenerator; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestSession; +import com.tvd12.ezyfoxserver.testing.MyTestSessionManager; + +public class EzySimpleSessionManagerTest extends BaseCoreTest { + + @Test + public void test() { + MyTestSessionManager manager = new MyTestSessionManager.Builder() + .build(); + MyTestSession session = manager.borrowSession(EzyConnectionType.SOCKET); + manager.returnSession(session); + session = manager.borrowSession(EzyConnectionType.SOCKET); + session.setDelegate(new EzyAbstractSessionDelegate() { + }); + manager.returnSession(session, EzySessionRemoveReason.IDLE); + manager.returnSession(null, EzySessionRemoveReason.IDLE); + + session = manager.borrowSession(EzyConnectionType.SOCKET); + session.setDelegate(new EzyAbstractSessionDelegate() { + }); + session.setLoggedIn(true); + manager.addLoggedInSession(session); + assertEquals(manager.getLoggedInSessions(), Lists.newArrayList(session)); + + assertFalse(manager.isStaleObject(session)); + + session = manager.borrowSession(EzyConnectionType.SOCKET); + session.setLoggedIn(false); + session.setCreationTime(System.currentTimeMillis() - 1000); + session.setMaxWaitingTime(100); + assertTrue(manager.isStaleObject(session)); + + manager.removeStaleObject(session); + + session = manager.borrowSession(EzyConnectionType.SOCKET); + session.setLoggedIn(false); + session.setCreationTime(System.currentTimeMillis()); + session.setMaxWaitingTime(10000); + assertFalse(manager.isStaleObject(session)); + + try { + manager.start(); + } catch (Exception e) { + } + } + + @Test + public void test1() { + MyTestSessionManager manager = + (MyTestSessionManager) new MyTestSessionManager.Builder() + .tokenGenerator(new EzySessionTokenGenerator() { + + @Override + public String generate() { + return UUID.randomUUID().toString(); + } + }) + .build(); + MyTestSession session = manager.borrowSession(EzyConnectionType.SOCKET); + session.setLoggedIn(true); + manager.addLoggedInSession(session); + MyTestSession session2 = manager.borrowSession(EzyConnectionType.SOCKET); + assert session.getId() != session2.getId(); + assertEquals(manager.getBorrowedObjects(), Lists.newArrayList(session, session2)); + assertEquals(manager.getCanBeStaleObjects(), Lists.newArrayList(session2)); + + } + +} diff --git a/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyUserManagerImplTest.java b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyUserManagerImplTest.java new file mode 100644 index 00000000..d8559c7f --- /dev/null +++ b/ezyfox-server-core/src/test/java/com/tvd12/ezyfoxserver/testing/wrapper/EzyUserManagerImplTest.java @@ -0,0 +1,42 @@ +package com.tvd12.ezyfoxserver.testing.wrapper; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.testing.BaseCoreTest; +import com.tvd12.ezyfoxserver.testing.MyTestSession; +import com.tvd12.ezyfoxserver.testing.MyTestUser; +import com.tvd12.ezyfoxserver.testing.MyTestUserManager; + +public class EzyUserManagerImplTest extends BaseCoreTest { + + @Test + public void test() { + MyTestUserManager manager = MyTestUserManager.builder() + .build(); + MyTestSession session = new MyTestSession(); + session.setId(10); + MyTestUser user = new MyTestUser(); + user.setId(1); + user.setName("dungtv"); + session.setReconnectToken("123456"); + user.addSession(session); + manager.addUser(session, user); + + assert manager.getUser(1) == user; + assert manager.getUser("dungtv") == user; + assert manager.containsUser(1); + assert !manager.containsUser(-1); + assert manager.containsUser(session); + assert manager.containsUser(user); + manager.removeUser(user.getId()); + assert manager.getUser(1) == null; + + manager.addUser(session, user); + manager.removeUser(user.getName()); + assert manager.getUser("dungtv") == null; + manager.addUser(session, user); + manager.removeUser((EzyUser)null); + } + +} diff --git a/ezyfox-server-core/src/test/resources/AllTests.tng.xml b/ezyfox-server-core/src/test/resources/AllTests.tng.xml index 3f571ed5..55313dea 100644 --- a/ezyfox-server-core/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-core/src/test/resources/AllTests.tng.xml @@ -6,4 +6,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-core/test-data/apps/entries/ezyfox-chat/ezyfox-chat.jar b/ezyfox-server-core/test-data/apps/entries/ezyfox-chat/ezyfox-chat.jar new file mode 100644 index 00000000..0b5ca549 Binary files /dev/null and b/ezyfox-server-core/test-data/apps/entries/ezyfox-chat/ezyfox-chat.jar differ diff --git a/ezyfox-server-core/test-data/plugins/ezyfox-auth-plugin/ezyfox-auth-plugin.jar b/ezyfox-server-core/test-data/plugins/ezyfox-auth-plugin/ezyfox-auth-plugin.jar new file mode 100644 index 00000000..eb4720e6 Binary files /dev/null and b/ezyfox-server-core/test-data/plugins/ezyfox-auth-plugin/ezyfox-auth-plugin.jar differ diff --git a/ezyfox-server-core/test-data/settings/config.properties b/ezyfox-server-core/test-data/settings/config.properties new file mode 100644 index 00000000..b068ab65 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/config.properties @@ -0,0 +1,3 @@ +ezyfox.home=test-data +ezyfox.version=1.0.0 +logger.config.file=logback.groovy \ No newline at end of file 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 new file mode 100644 index 00000000..06648ba3 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/ezy-settings-1.0.0.xsd @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-core/test-data/settings/ezy-settings.xml b/ezyfox-server-core/test-data/settings/ezy-settings.xml new file mode 100644 index 00000000..a5765a5c --- /dev/null +++ b/ezyfox-server-core/test-data/settings/ezy-settings.xml @@ -0,0 +1,57 @@ + + + + + 8080 + + + + 3005 + com.tvd12.ezyfoxserver.codec.MsgPackCodecCreator + + + + 2208 + 2812 + false + + ssl-config.properties + com.tvd12.ezyfoxserver.ssl.EzySimpleSslConfigLoader + com.tvd12.ezyfoxserver.ssl.EzySimpleSslContextFactoryBuilder + + com.tvd12.ezyfoxserver.codec.JacksonWsCodecCreator + + + + 15000 + 15 + + + + 15000 + 30000 + + + + + ezyfox-chat + com.tvd12.ezyfoxserver.chat.EzyChatEntryLoader + 30 + + + + + + ezyfox-auth-plugin + -1 + com.tvd12.ezyfoxserver.plugin.auth.EzyAuthPluginEntryLoader + 30 + + + + + \ 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 new file mode 100644 index 00000000..b637e092 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/logback.groovy @@ -0,0 +1,26 @@ +// +// Built on Sun Apr 24 09:59:09 UTC 2016 by logback-translator +// For more information on configuration files in Groovy +// please see http://logback.qos.ch/manual/groovy.html + +// For assistance related to this tool or configuration files +// in general, please contact the logback user mailing list at +// http://qos.ch/mailman/listinfo/logback-user + +// For professional support please see +// http://www.qos.ch/shop/products/professionalSupport + +import ch.qos.logback.classic.encoder.PatternLayoutEncoder +import ch.qos.logback.core.ConsoleAppender + +import static ch.qos.logback.classic.Level.DEBUG +import static ch.qos.logback.classic.Level.INFO + +appender("stdout", ConsoleAppender) { + target = "System.out" + encoder(PatternLayoutEncoder) { + pattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5p %c{1}:%L - %m%n" + //pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %class{36}.%M %L - %msg%n" + } +} +root(DEBUG, ["stdout"]) \ No newline at end of file diff --git a/ezyfox-server-core/test-data/settings/ssl-config.properties b/ezyfox-server-core/test-data/settings/ssl-config.properties new file mode 100644 index 00000000..9aba8b86 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/ssl-config.properties @@ -0,0 +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 diff --git a/ezyfox-server-core/test-data/settings/ssl/ssl-certificate-password.txt b/ezyfox-server-core/test-data/settings/ssl/ssl-certificate-password.txt new file mode 100644 index 00000000..536aca34 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/ssl/ssl-certificate-password.txt @@ -0,0 +1 @@ +secret \ No newline at end of file diff --git a/ezyfox-server-core/test-data/settings/ssl/ssl-key-store.txt b/ezyfox-server-core/test-data/settings/ssl/ssl-key-store.txt new file mode 100644 index 00000000..439ef0da Binary files /dev/null and b/ezyfox-server-core/test-data/settings/ssl/ssl-key-store.txt differ diff --git a/ezyfox-server-core/test-data/settings/ssl/ssl-keystore-password.txt b/ezyfox-server-core/test-data/settings/ssl/ssl-keystore-password.txt new file mode 100644 index 00000000..536aca34 --- /dev/null +++ b/ezyfox-server-core/test-data/settings/ssl/ssl-keystore-password.txt @@ -0,0 +1 @@ +secret \ 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 new file mode 100644 index 00000000..bbfa129d --- /dev/null +++ b/ezyfox-server-core/test-data1/settings/config.properties @@ -0,0 +1,2 @@ +ezyfox.version=1.0.0 +logger.config.file=logback.groovy \ No newline at end of file diff --git a/ezyfox-server-database/pom.xml b/ezyfox-server-database/pom.xml new file mode 100644 index 00000000..0eb47b7f --- /dev/null +++ b/ezyfox-server-database/pom.xml @@ -0,0 +1,27 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-database + 1.0.0 + ezyfox-server-database + http://maven.apache.org + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-util + ${ezy.util.version} + + + + diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/EzyDatabaseNameAware.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/EzyDatabaseNameAware.java new file mode 100644 index 00000000..7f5d3112 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/EzyDatabaseNameAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database; + +public interface EzyDatabaseNameAware { + + void setDatabaseName(String databaseName); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyMapstore.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyMapstore.java new file mode 100644 index 00000000..e328d511 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyMapstore.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.database.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyMapstore { + + String value() default ""; + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyRepository.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyRepository.java new file mode 100644 index 00000000..7dc64fa8 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/annotation/EzyRepository.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.database.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyRepository { + + String value() default ""; + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyEntity.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyEntity.java new file mode 100644 index 00000000..b61722d3 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyEntity.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.entity; + +import java.io.Serializable; + +public interface EzyEntity extends Serializable { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyHasIdEntity.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyHasIdEntity.java new file mode 100644 index 00000000..1965e78f --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyHasIdEntity.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.entity; + +public interface EzyHasIdEntity { + + I getId(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyLongIdEntity.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyLongIdEntity.java new file mode 100644 index 00000000..49cee671 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/entity/EzyLongIdEntity.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.entity; + +public interface EzyLongIdEntity extends EzyEntity { + + long getId(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/exception/EzyTransactionException.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/exception/EzyTransactionException.java new file mode 100644 index 00000000..3276ea87 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/exception/EzyTransactionException.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.database.exception; + +public class EzyTransactionException extends Exception { + private static final long serialVersionUID = 2578127055193650532L; + + public EzyTransactionException() { + super(); + } + + public EzyTransactionException(String msg) { + super(msg); + } + + public EzyTransactionException(String msg, Throwable e) { + super(msg, e); + } + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckContainService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckContainService.java new file mode 100644 index 00000000..45e6bc9b --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckContainService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyCheckContainService { + + boolean containsKey(K key); + + boolean containsValue(V value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckEmptyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckEmptyService.java new file mode 100644 index 00000000..5ba0f56b --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckEmptyService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyCheckEmptyService { + + boolean isEmpty(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckService.java new file mode 100644 index 00000000..c73b8262 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyCheckService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyCheckService extends + EzyCheckEmptyService, + EzyCheckContainService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyClearService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyClearService.java new file mode 100644 index 00000000..ffcd242a --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyClearService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyClearService { + + void clear(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllListService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllListService.java new file mode 100644 index 00000000..74f9084e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllListService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.List; + +public interface EzyFetchAllListService { + + List getAllList(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllMapService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllMapService.java new file mode 100644 index 00000000..40d90db2 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllMapService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.Map; + +public interface EzyFetchAllMapService { + + Map getAllMap(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllService.java new file mode 100644 index 00000000..62d0f52d --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchAllService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyFetchAllService extends + EzyFetchAllMapService, + EzyFetchAllListService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeyService.java new file mode 100644 index 00000000..846b5541 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeyService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyFetchByKeyService { + + V get(K key); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeys.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeys.java new file mode 100644 index 00000000..c9b48832 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchByKeys.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyFetchByKeys extends + EzyFetchListByKeys, + EzyFetchMapByKeys { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchListByKeys.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchListByKeys.java new file mode 100644 index 00000000..3aac7f0d --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchListByKeys.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.List; + +public interface EzyFetchListByKeys { + + List getListByIds(Iterable keys); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchMapByKeys.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchMapByKeys.java new file mode 100644 index 00000000..22e7ea77 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchMapByKeys.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.Map; + +public interface EzyFetchMapByKeys { + + Map getMapByIds(Iterable keys); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchService.java new file mode 100644 index 00000000..4262e3e7 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchService.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyFetchService extends + EzyFetchByKeyService, + EzyFetchAllService, + EzyFetchByKeys { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchSizeService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchSizeService.java new file mode 100644 index 00000000..f2603feb --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyFetchSizeService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyFetchSizeService { + + int size(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyMapService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyMapService.java new file mode 100644 index 00000000..538cef48 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyMapService.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyMapService extends + EzySetService, + EzyPutService, + EzyFetchService, + EzyRemoveService, + EzyCheckService, + EzyFetchSizeService, + EzyClearService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutKeyValueService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutKeyValueService.java new file mode 100644 index 00000000..674c104e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutKeyValueService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyPutKeyValueService { + + V put(K key, V value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutMapService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutMapService.java new file mode 100644 index 00000000..b8e6562a --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutMapService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.Map; + +public interface EzyPutMapService { + + void put(Map map); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutService.java new file mode 100644 index 00000000..9a30bc96 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutService.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyPutService extends + EzyPutKeyValueService, + EzyPutValueService, + EzyPutValuesService, + EzyPutMapService { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValueService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValueService.java new file mode 100644 index 00000000..77cb0b5a --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValueService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyPutValueService { + + V put(V value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValuesService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValuesService.java new file mode 100644 index 00000000..079e238f --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyPutValuesService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyPutValuesService { + + void put(Iterable values); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeyService.java new file mode 100644 index 00000000..0159a11f --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeyService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyRemoveByKeyService { + + V remove(K key); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeysService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeysService.java new file mode 100644 index 00000000..71ea5ca7 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveByKeysService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyRemoveByKeysService { + + void remove(Iterable keys); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveService.java new file mode 100644 index 00000000..0f557247 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzyRemoveService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzyRemoveService extends + EzyRemoveByKeyService, + EzyRemoveByKeysService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetKeyValueService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetKeyValueService.java new file mode 100644 index 00000000..32af6e2e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetKeyValueService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzySetKeyValueService { + + void set(K key, V value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetMapService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetMapService.java new file mode 100644 index 00000000..f614e692 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetMapService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +import java.util.Map; + +public interface EzySetMapService { + + void set(Map map); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetService.java new file mode 100644 index 00000000..69286b29 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzySetService extends + EzySetKeyValueService, + EzySetValueService, + EzySetValuesService, + EzySetMapService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValueService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValueService.java new file mode 100644 index 00000000..3e01afd0 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValueService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzySetValueService { + + void set(V value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValuesService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValuesService.java new file mode 100644 index 00000000..0e1f829e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/mapservice/EzySetValuesService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.mapservice; + +public interface EzySetValuesService { + + void set(Iterable values); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyFindAndModifyOptions.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyFindAndModifyOptions.java new file mode 100644 index 00000000..3f883f33 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyFindAndModifyOptions.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.database.query; + +import java.util.concurrent.TimeUnit; + +public interface EzyFindAndModifyOptions { + + /** + * Returns the remove + * + * @return the remove + */ + boolean isRemove(); + + /** + * Indicates whether to remove the elements matching the query or not + * + * @param remove true if the matching elements should be deleted + * @return this + */ + EzyFindAndModifyOptions remove(boolean remove);; + + /** + * Returns the upsert + * + * @return the upsert + */ + boolean isUpsert(); + + /** + * Indicates that an upsert should be performed + * + * @param upsert the upsert + * @return this + */ + EzyFindAndModifyOptions upsert(boolean upsert); + + /** + * Returns the returnNew + * + * @return the returnNew + */ + boolean isReturnNew(); + /** + * Sets the returnNew + * + * @param returnNew the returnNew + * @return this + */ + EzyFindAndModifyOptions returnNew(boolean returnNew); + + /** + * Gets the maximum execution time on the server for this operation. The default is 0, which places no limit on the execution time. + * + * @param timeUnit the time unit to return the result in + * @return the maximum execution time in the given time unit + */ + long getMaxTime(TimeUnit timeUnit); + + /** + * Sets the maximum execution time on the server for this operation. + * + * @param maxTime the max time + * @param timeUnit the time unit, which may not be null + * @return this + */ + EzyFindAndModifyOptions maxTime(long maxTime, TimeUnit timeUnit); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyPushOptions.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyPushOptions.java new file mode 100644 index 00000000..123120c2 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyPushOptions.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.database.query; + +public interface EzyPushOptions { + + /** + * Sets the position for the update + * @param position the position in the array for the update + * @return this + */ + EzyPushOptions position(int position); + + /** + * Sets the slice value for the update + * @param slice the slice value for the update + * @return this + */ + EzyPushOptions slice(int slice); + + /** + * Sets the sort value for the update + * @param sort the sort value for the update + * @return this + */ + EzyPushOptions sort(int sort); + + /** + * Sets the sort value for the update + * + * @param field the field to sort by + * @param direction the direction of the sort + * @return this + */ + EzyPushOptions sort(String field, int direction); +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyUpdateOperations.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyUpdateOperations.java new file mode 100644 index 00000000..2b7b002d --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/query/EzyUpdateOperations.java @@ -0,0 +1,215 @@ +package com.tvd12.ezyfoxserver.database.query; + +import java.util.List; + +import com.tvd12.ezyfoxserver.function.EzyApply; + +/** + *

A nicer interface to the update operations in monogodb. All these operations happen at the server and can cause the server and + * client + * version of the Entity to be different

+ * + * @param The Java type used in the updates + */ +public interface EzyUpdateOperations { + + /** + * adds the value to an array field if it doesn't already exist in the array + * + * @param field the field to update + * @param value the value to add + * @return this + */ + EzyUpdateOperations addToSet(String field, Object value); + + /** + * adds the values to an array field if they doesn't already exist in the array + * + * @param field the field to update + * @param values the values to add + * @return this + */ + EzyUpdateOperations addToSet(String field, List values); + + /** + * Decrements the numeric field by 1 + * + * @param field the field to update + * @return this + */ + EzyUpdateOperations dec(String field); + + /** + * Decrements the numeric field by value (must be a positive Double, + * Float, Long, or Integer). + * + * @param field the field to update + * @param value the value to decrement by + * @throws IllegalArgumentException of the value is not an instance of + * Double, Float,Long, or Integer + * @return this + */ + EzyUpdateOperations dec(String field, Number value); + + /** + * Turns off validation (for all calls made after) + * + * @return this + */ + EzyUpdateOperations disableValidation(); + + /** + * Turns on validation (for all calls made after); by default validation is on + * + * @return this + */ + EzyUpdateOperations enableValidation(); + + /** + * Increments the numeric field by 1 + * + * @param field the field to update + * @return this + */ + EzyUpdateOperations inc(String field); + + /** + * increments the numeric field by value (negatives are allowed) + * + * @param field the field to update + * @param value the value to increment by + * @return this + */ + EzyUpdateOperations inc(String field, Number value); + + /** + * Enables isolation (so this update happens in one shot, without yielding) + * + * @return this + */ + EzyUpdateOperations isolated(); + + /** + * @return true if this update is to be run in isolation + * + * @since 1.3 + */ + boolean isIsolated(); + + /** + * Sets the numeric field to value if it is greater than the current value. + * + * @param field the field to update + * @param value the value to use + * @return this + */ + EzyUpdateOperations max(String field, Number value); + + /** + * sets the numeric field to value if it is less than the current value. + * + * @param field the field to update + * @param value the value to use + * @return this + */ + EzyUpdateOperations min(String field, Number value); + + /** + * Adds new values to an array field. + * + * @param field the field to updated + * @param value the value to add + * @return this + */ + EzyUpdateOperations push(String field, Object value); + + /** + * Adds new values to an array field at the given position + * + * @param field the field to updated + * @param value the value to add + * @param options the options to apply to the push + * @return this + */ + EzyUpdateOperations push(String field, Object value, EzyApply options); + + /** + * Adds new values to an array field. + * + * @param field the field to updated + * @param values the values to add + * @return this + */ + EzyUpdateOperations push(String field, List values); + + /** + * Adds new values to an array field at the given position + * + * @param field the field to updated + * @param values the values to add + * @param options the options to apply to the push + * @return this + */ + EzyUpdateOperations push(String field, List values, EzyApply options); + + /** + * removes the value from the array field + * + * @param field the field to update + * @param value the value to use + * @return this + */ + EzyUpdateOperations removeAll(String field, Object value); + + /** + * removes the values from the array field + * + * @param field the field to update + * @param values the values to use + * @return this + */ + EzyUpdateOperations removeAll(String field, List values); + + /** + * removes the first value from the array + * + * @param field the field to update + * @return this + */ + EzyUpdateOperations removeFirst(String field); + + /** + * removes the last value from the array + * + * @param field the field to update + * @return this + */ + EzyUpdateOperations removeLast(String field); + + /** + * sets the field value + * + * @param field the field to update + * @param value the value to use + * @return this + */ + EzyUpdateOperations set(String field, Object value); + + /** + * sets the field on insert. + * + * @param field the field to update + * @param value the value to use + * @return this + */ + EzyUpdateOperations setOnInsert(String field, Object value); + + /** + * removes the field + * + * @param field the field to update + * @return this + */ + EzyUpdateOperations unset(String field); +} + diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/repository/EzyEmptyRepository.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/repository/EzyEmptyRepository.java new file mode 100644 index 00000000..63fb0794 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/repository/EzyEmptyRepository.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.database.repository; + +public interface EzyEmptyRepository { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCountSerivce.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCountSerivce.java new file mode 100644 index 00000000..7297e288 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCountSerivce.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyCountSerivce { + + long count(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCrudService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCrudService.java new file mode 100644 index 00000000..fa5e794f --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyCrudService.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyCrudService extends + EzyCountSerivce, + EzySaveService, + EzyFindService, + EzyUpdateService, + EzyDeleteService, + EzyFindAndModifyService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteAllService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteAllService.java new file mode 100644 index 00000000..0d716aed --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteAllService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyDeleteAllService { + + int deleteAll(); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdService.java new file mode 100644 index 00000000..31f2297e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyDeleteByIdService { + + void delete(I id); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdsService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdsService.java new file mode 100644 index 00000000..49a0f83b --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteByIdsService.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.database.service; + +import java.util.Collection; + +public interface EzyDeleteByIdsService { + + int deleteByIds(Collection ids); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteService.java new file mode 100644 index 00000000..26e23e52 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyDeleteService.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyDeleteService extends + EzyDeleteAllService, + EzyDeleteByIdService, + EzyDeleteByIdsService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAllService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAllService.java new file mode 100644 index 00000000..7128aaa9 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAllService.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.database.service; + +import java.util.List; + +public interface EzyFindAllService { + + List findAll(); + + List findAll(int skip, int limit); +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByFieldService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByFieldService.java new file mode 100644 index 00000000..74b76c3a --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByFieldService.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.tvd12.ezyfoxserver.database.query.EzyFindAndModifyOptions; +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public interface EzyFindAndModifyByFieldService { + + E findAndModifyByField(String field, Object value, EzyApply> operations); + + E findAndModifyByField(String field, Object value, EzyApply> operations, EzyApply options); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByIdService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByIdService.java new file mode 100644 index 00000000..a057da28 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyByIdService.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.tvd12.ezyfoxserver.database.query.EzyFindAndModifyOptions; +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public interface EzyFindAndModifyByIdService { + + E findAndModifyById(I id, EzyApply> operations); + + E findAndModifyById(I id, EzyApply> operations, EzyApply options); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyService.java new file mode 100644 index 00000000..c3b4e3a6 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindAndModifyService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyFindAndModifyService extends + EzyFindAndModifyByIdService, + EzyFindAndModifyByFieldService { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindByField.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindByField.java new file mode 100644 index 00000000..e22785af --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindByField.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyFindByField { + + E findByField(String field, Object value); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindById.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindById.java new file mode 100644 index 00000000..1fcd23ff --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindById.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyFindById { + + E findById(I id); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByField.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByField.java new file mode 100644 index 00000000..296b2b5c --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByField.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.database.service; + +import java.util.List; + +public interface EzyFindListByField { + + List findListByField(String field, Object value); + + List findListByField(String field, Object value, int skip, int limit); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByIds.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByIds.java new file mode 100644 index 00000000..72ef10c0 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindListByIds.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.database.service; + +import java.util.Collection; +import java.util.List; + +public interface EzyFindListByIds { + + List findListByIds(Collection ids); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindService.java new file mode 100644 index 00000000..2d88b344 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyFindService.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyFindService extends + EzyFindById, + EzyFindListByIds, + EzyFindByField, + EzyFindListByField, + EzyFindAllService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveManyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveManyService.java new file mode 100644 index 00000000..b64173e3 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveManyService.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.google.common.collect.Lists; + +public interface EzySaveManyService { + + void save(Iterable entities); + + @SuppressWarnings("unchecked") + default void save(E... entities) { + save(Lists.newArrayList(entities)); + } + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveOneSerivce.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveOneSerivce.java new file mode 100644 index 00000000..3b81ce44 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveOneSerivce.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzySaveOneSerivce { + + void save(E entity); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveService.java new file mode 100644 index 00000000..143c37c8 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzySaveService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzySaveService + extends EzySaveOneSerivce, EzySaveManyService { + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyByFieldService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyByFieldService.java new file mode 100644 index 00000000..8e829bbc --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyByFieldService.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public interface EzyUpdateManyByFieldService { + + void updateManyByField(String field, Object value, EzyApply> operations); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyService.java new file mode 100644 index 00000000..e0ef4d98 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateManyService.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyUpdateManyService extends + EzyUpdateManyByFieldService { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByFieldService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByFieldService.java new file mode 100644 index 00000000..da69abd4 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByFieldService.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public interface EzyUpdateOneByFieldService { + + void updateOneByField(String field, Object value, E entity); + + void updateOneByField(String field, Object value, E entity, boolean upsert); + + void updateOneByField(String field, Object value, EzyApply> operations); + + void updateOneByField(String field, Object value, EzyApply> operations, boolean upsert); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByIdService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByIdService.java new file mode 100644 index 00000000..f4e920f0 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneByIdService.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.database.service; + +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public interface EzyUpdateOneByIdService { + + void updateOneById(I id, E entity); + + void updateOneById(I id, E entity, boolean upsert); + + void updateOneById(I id, EzyApply> operations); + + void updateOneById(I id, EzyApply> operations, boolean upsert); + +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneService.java new file mode 100644 index 00000000..24ae3b18 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateOneService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyUpdateOneService extends + EzyUpdateOneByIdService, + EzyUpdateOneByFieldService { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateService.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateService.java new file mode 100644 index 00000000..f323cf4e --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/service/EzyUpdateService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.database.service; + +public interface EzyUpdateService extends + EzyUpdateOneService, + EzyUpdateManyService { +} diff --git a/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/util/EzyMapstoreAnnotations.java b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/util/EzyMapstoreAnnotations.java new file mode 100644 index 00000000..b0603c99 --- /dev/null +++ b/ezyfox-server-database/src/main/java/com/tvd12/ezyfoxserver/database/util/EzyMapstoreAnnotations.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.database.util; + +import static com.tvd12.ezyfoxserver.reflect.EzyClasses.getVariableName; +import static org.apache.commons.lang3.StringUtils.isEmpty; + +import com.tvd12.ezyfoxserver.database.annotation.EzyMapstore; + +public final class EzyMapstoreAnnotations { + + private EzyMapstoreAnnotations() { + } + + public static String getMapName(Class clazz) { + EzyMapstore anno = clazz.getAnnotation(EzyMapstore.class); + String name = anno.value(); + return isEmpty(name) ? getVariableName(clazz) : name; + } + +} diff --git a/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzySaveManyServiceTest.java b/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzySaveManyServiceTest.java new file mode 100644 index 00000000..1c0938c7 --- /dev/null +++ b/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzySaveManyServiceTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.database.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.database.service.EzySaveManyService; + +public class EzySaveManyServiceTest { + + @Test + public void test() { + new EzySaveManyService() { + public void save(java.lang.Iterable entities) {}; + } + .save(new Object(), new Object()); + } + +} diff --git a/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzyTransactionExceptionTest.java b/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzyTransactionExceptionTest.java new file mode 100644 index 00000000..794e854c --- /dev/null +++ b/ezyfox-server-database/src/test/java/com/tvd12/ezyfoxserver/database/testing/EzyTransactionExceptionTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.database.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.database.exception.EzyTransactionException; + +public class EzyTransactionExceptionTest { + + @Test + public void test() { + new EzyTransactionException(); + new EzyTransactionException(""); + new EzyTransactionException("", new Throwable()); + } + +} diff --git a/ezyfox-server-database/src/test/resources/AllTests.tng.xml b/ezyfox-server-database/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..cc819f04 --- /dev/null +++ b/ezyfox-server-database/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-databridge/pom.xml b/ezyfox-server-databridge/pom.xml new file mode 100644 index 00000000..7d27bba5 --- /dev/null +++ b/ezyfox-server-databridge/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-databridge + 1.0.0 + ezyfox-server-databridge + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-core + ${ezy.core.version} + + + \ No newline at end of file diff --git a/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxySession.java b/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxySession.java new file mode 100644 index 00000000..56769583 --- /dev/null +++ b/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxySession.java @@ -0,0 +1,82 @@ +package com.tvd12.ezyfoxserver.proxydata; + +import java.net.SocketAddress; +import java.util.Collection; +import java.util.Date; + +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.io.EzyDates; +import com.tvd12.ezyfoxserver.io.EzyLists; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EzyProxySession { + + private final EzySession real; + + public static EzyProxySession newInstance(EzySession real) { + return new EzyProxySession(real); + } + + public static Collection newCollection(Collection reals) { + return EzyLists.newArrayList(reals, EzyProxySession::new); + } + + public long getId() { + return real.getId(); + } + + public String getClientId() { + return real.getClientId(); + } + + public String getReconnectToken() { + return real.getReconnectToken(); + } + + public long getMaxIdleTime() { + return real.getMaxIdleTime(); + } + + public long getMaxWaitingTime() { + return real.getMaxWaitingTime(); + } + + public boolean isActivated() { + return real.isActivated(); + } + + public boolean isLoggedIn() { + return real.isLoggedIn(); + } + + public SocketAddress getClientAddress() { + return real.getClientAddress(); + } + + public long getReadBytes() { + return real.getReadBytes(); + } + + public long getWrittenBytes() { + return real.getWrittenBytes(); + } + + public String getCreationTime() { + return EzyDates.format(new Date(real.getCreationTime())); + } + + public String getLastActivityTime() { + return EzyDates.format(new Date(real.getLastActivityTime())); + } + + public String getLastReadTime() { + return EzyDates.format(new Date(real.getLastReadTime())); + } + + public String getLastWriteTime() { + return EzyDates.format(new Date(real.getLastWriteTime())); + } + +} diff --git a/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxyUser.java b/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxyUser.java new file mode 100644 index 00000000..9a85ec04 --- /dev/null +++ b/ezyfox-server-databridge/src/main/java/com/tvd12/ezyfoxserver/proxydata/EzyProxyUser.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.proxydata; + +import java.util.Collection; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.io.EzyLists; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EzyProxyUser { + + private EzyUser real; + + public static EzyProxyUser newInstance(EzyUser real) { + return new EzyProxyUser(real); + } + + public static Collection newCollection(Collection reals) { + return EzyLists.newArrayList(reals, EzyProxyUser::new); + } + + public long getId() { + return real.getId(); + } + + public String getName() { + return real.getName(); + } + + public Collection getSessions() { + return EzyProxySession.newCollection(real.getSessions()); + } + +} diff --git a/ezyfox-server-databridge/src/test/resources/AllTests.tng.xml b/ezyfox-server-databridge/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-databridge/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-elasticsearch/pom.xml b/ezyfox-server-elasticsearch/pom.xml new file mode 100644 index 00000000..4de85404 --- /dev/null +++ b/ezyfox-server-elasticsearch/pom.xml @@ -0,0 +1,36 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-elasticsearch + ezyfox-server-elasticsearch + 1.0.0 + + + 1.0.0 + 5.6.3 + + + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + org.elasticsearch + elasticsearch + ${elasticsearch.version} + + + org.elasticsearch.client + transport + ${elasticsearch.version} + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-bean/assembly.xml b/ezyfox-server-hazelcast-bean/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-hazelcast-bean/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-bean/pom.xml b/ezyfox-server-hazelcast-bean/pom.xml new file mode 100644 index 00000000..ba4d7f20 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-hazelcast-bean + ezyfox-server-hazelcast-bean + 1.0.0 + http://maven.apache.org + + 1.0.0 + 1.0.0 + + + + + com.tvd12 + ezyfox-server-hazelcast + ${ezy.hazelcast.version} + + + com.tvd12 + ezyfox-server-bean + ${ezy.bean.version} + + + diff --git a/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyBeanHazelcastFactory.java b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyBeanHazelcastFactory.java new file mode 100644 index 00000000..5bdf7977 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyBeanHazelcastFactory.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextAware; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyBeanMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; + +import lombok.Setter; + +public class EzyBeanHazelcastFactory + extends EzyAbstractHazelcastFactory + implements EzyBeanContextAware { + + @Setter + protected EzyBeanContext context; + + @Override + protected EzyMapstoreCreator newMapstoreCreator() { + EzyBeanMapstoreCreator creator = new EzyBeanMapstoreCreator(); + creator.setContext(context); + return creator; + } + +} diff --git a/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyBeanMapstoreCreator.java b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyBeanMapstoreCreator.java new file mode 100644 index 00000000..a26c5abf --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyBeanMapstoreCreator.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import static com.tvd12.ezyfoxserver.database.util.EzyMapstoreAnnotations.getMapName; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextAware; +import com.tvd12.ezyfoxserver.bean.EzySingletonFactory; +import com.tvd12.ezyfoxserver.database.annotation.EzyMapstore; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings("rawtypes") +public class EzyBeanMapstoreCreator + extends EzyLoggable + implements EzyMapstoreCreator, EzyBeanContextAware { + + protected Map mapstores = new ConcurrentHashMap<>(); + + @Override + public Set getMapNames() { + return new HashSet<>(mapstores.keySet()); + } + + @Override + public MapStore create(String mapName, Properties properties) { + return mapstores.get(mapName); + } + + @SuppressWarnings("unchecked") + public void setContext(EzyBeanContext context) { + EzySingletonFactory singletonFactory = context.getSingletonFactory(); + List objects = singletonFactory.getSingletons(EzyMapstore.class); + for(Object object : objects) + mapstores.put(getMapName(object.getClass()), (MapStore) object); + } + +} diff --git a/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractHazelcastService.java b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractHazelcastService.java new file mode 100644 index 00000000..a904dd2a --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractHazelcastService.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +public class EzyBeanAbstractHazelcastService extends EzyAbstractHazelcastService { + + @EzyAutoBind + @Override + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + super.setHazelcastInstance(hazelcastInstance); + } + + @EzyPostInit + @Override + public void init() { + super.init(); + } + +} diff --git a/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractMapService.java b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractMapService.java new file mode 100644 index 00000000..c9715d80 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanAbstractMapService.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +public abstract class EzyBeanAbstractMapService extends EzyAbstractMapService { + + @EzyAutoBind + @Override + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + super.setHazelcastInstance(hazelcastInstance); + } + + @EzyPostInit + @Override + public void init() { + super.init(); + } + +} diff --git a/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanSimpleHazelcastMapService.java b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanSimpleHazelcastMapService.java new file mode 100644 index 00000000..00631054 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyBeanSimpleHazelcastMapService.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzyPostInit; + +public abstract class EzyBeanSimpleHazelcastMapService + extends EzySimpleHazelcastMapService { + + @EzyAutoBind + @Override + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + super.setHazelcastInstance(hazelcastInstance); + } + + @EzyPostInit + @Override + public void init() { + super.init(); + } +} diff --git a/ezyfox-server-hazelcast-bean/src/test/resources/AllTests.tng.xml b/ezyfox-server-hazelcast-bean/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-bean/src/test/resources/hazelcast.xml b/ezyfox-server-hazelcast-bean/src/test/resources/hazelcast.xml new file mode 100644 index 00000000..6ca0e4de --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/test/resources/hazelcast.xml @@ -0,0 +1,24 @@ + + + http://localhost:8080/mancenter + + + dev + dev-pass + + + + true + slf4j + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-bean/src/test/resources/mongo_config.properties b/ezyfox-server-hazelcast-bean/src/test/resources/mongo_config.properties new file mode 100644 index 00000000..d8c3d5c9 --- /dev/null +++ b/ezyfox-server-hazelcast-bean/src/test/resources/mongo_config.properties @@ -0,0 +1,5 @@ +database.mongo.host=127.0.0.1 +database.mongo.port=27017 +database.mongo.database=test +database.mongo.username=root +database.mongo.password=123456 \ No newline at end of file diff --git a/ezyfox-server-hazelcast-mongodb/assembly.xml b/ezyfox-server-hazelcast-mongodb/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-mongodb/pom.xml b/ezyfox-server-hazelcast-mongodb/pom.xml new file mode 100644 index 00000000..04687f25 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-hazelcast-mongodb + ezyfox-server-hazelcast-mongodb + 1.0.0 + http://maven.apache.org + + 3.8.1 + 1.0.0 + 1.0.0 + + + + + com.tvd12 + ezyfox-server-hazelcast + ${ezy.hazelcast.version} + + + com.tvd12 + ezyfox-server-mongodb + ${ezy.mongodb.version} + + + diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatabaseHazelcastFactory.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatabaseHazelcastFactory.java new file mode 100644 index 00000000..5c7b3d29 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatabaseHazelcastFactory.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.mongodb.client.MongoDatabase; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMongoDatabaseMapstoreCreator; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoDatabaseAware; + +import lombok.Setter; + +@Setter +public class EzyMongoDatabaseHazelcastFactory + extends EzyAbstractHazelcastFactory + implements EzyMongoDatabaseAware { + + protected MongoDatabase database; + + @Override + protected EzyMapstoreCreator newMapstoreCreator() { + EzyMongoDatabaseMapstoreCreator creator = newDatabaseMapstoreCreator(); + creator.setDatabase(database); + return creator; + } + + protected EzyMongoDatabaseMapstoreCreator newDatabaseMapstoreCreator() { + return new EzyMongoDatabaseMapstoreCreator(); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMongoAccount.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMongoAccount.java new file mode 100644 index 00000000..6e9dd255 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMongoAccount.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.hazelcast.entity; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzyMongoAccount extends EzyAbstractAccount { + private static final long serialVersionUID = 3884020036545997524L; + + private Long id; + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMongoAccoutFactory.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMongoAccoutFactory.java new file mode 100644 index 00000000..f6e7ebda --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMongoAccoutFactory.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyMongoAccount; + +public class EzyMongoAccoutFactory extends EzyAbstractAccoutFactory { + + @Override + protected EzyMongoAccount newAccount() { + return new EzyMongoAccount(); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoCollectionMapstore.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoCollectionMapstore.java new file mode 100644 index 00000000..73547236 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoCollectionMapstore.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import org.bson.Document; + +import com.mongodb.client.MongoCollection; + +public abstract class EzyMongoCollectionMapstore + extends EzyMongoDatabaseMapstore { + + protected MongoCollection collection; + + @Override + public void postInit() { + super.postInit(); + this.collection = database.getCollection(getCollectionName()); + } + + protected abstract String getCollectionName(); + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstore.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstore.java new file mode 100644 index 00000000..6e377a07 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstore.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import com.mongodb.client.MongoDatabase; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoDatabaseAware; + +import lombok.Setter; + +/** + * @author tavandung12 + * + */ +public abstract class EzyMongoDatabaseMapstore + extends EzyAbstractMapstore + implements EzyMongoDatabaseAware { + + @Setter + protected MongoDatabase database; + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstoreCreator.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstoreCreator.java new file mode 100644 index 00000000..ccf01efc --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatabaseMapstoreCreator.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import com.hazelcast.core.MapStore; +import com.mongodb.client.MongoDatabase; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoDatabaseAware; + +import lombok.Setter; + +public class EzyMongoDatabaseMapstoreCreator + extends EzySimpleMapstoreCreator + implements EzyMongoDatabaseAware { + + @Setter + protected MongoDatabase database; + + @SuppressWarnings("rawtypes") + private Map defaultMapstores = defaultMapstores(); + + @SuppressWarnings("rawtypes") + @Override + public MapStore create(String mapName, Properties properties) { + MapStore mapstore = defaultMapstores.get(mapName); + if(mapstore == null) + mapstore = (MapStore) mapstoresFetcher.getMapstore(mapName); + if(mapstore instanceof EzyMongoDatabaseAware) + ((EzyMongoDatabaseAware)mapstore).setDatabase(database); + return mapstore; + } + + public Set getMapNames() { + Set mapNames = super.getMapNames(); + mapNames.addAll(defaultMapstores.keySet()); + return mapNames; + } + + @SuppressWarnings("rawtypes") + protected Map defaultMapstores() { + Map suppliers = new HashMap<>(); + addDefaultMapStores(suppliers); + return suppliers; + } + + @SuppressWarnings("rawtypes") + protected void addDefaultMapStores(Map suppliers) { + suppliers.put(EzyMapNames.MAX_ID, new EzyMongoMaxIdMapstore()); + } +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMapstore.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMapstore.java new file mode 100644 index 00000000..ba685dde --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMapstore.java @@ -0,0 +1,22 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import com.mongodb.MongoClient; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoClientAware; + +import lombok.Setter; + +/** + * @author tavandung12 + * + */ +public abstract class EzyMongoMapstore + extends EzyAbstractMapstore + implements EzyMongoClientAware { + + @Setter + protected MongoClient mongoClient; + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMaxIdMapstore.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMaxIdMapstore.java new file mode 100644 index 00000000..a7eb1f75 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoMaxIdMapstore.java @@ -0,0 +1,49 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import org.bson.Document; +import org.bson.conversions.Bson; + +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.UpdateOptions; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; + +/** + * @author tavandung12 + * + */ +public class EzyMongoMaxIdMapstore extends EzyMongoCollectionMapstore { + + @Override + public Long load(String key) { + Bson filter = getFilter(key); + Document first = collection.find(filter).first(); + Long answer = first != null ? first.getLong("maxId") : 0L; + getLogger().info("load maxId of: {} max: {}", key, answer); + return answer; + } + + @Override + public void store(String key, Long value) { + collection.updateOne(getFilter(key), getUpdate(value), getUpdateOptions()); + } + + protected Bson getUpdate(Long value) { + return new Document("$set", new Document("maxId", value)); + } + + private Bson getFilter(String key) { + return Filters.eq("_id", key); + } + + private UpdateOptions getUpdateOptions() { + return new UpdateOptions().upsert(true); + } + + @Override + protected String getCollectionName() { + return EzyMapNames.MAX_ID; + } +} diff --git a/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMongoAccountService.java b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMongoAccountService.java new file mode 100644 index 00000000..65069ee8 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMongoAccountService.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleAccountService; + +public class EzyMongoAccountService extends EzySimpleAccountService { + + public EzyMongoAccountService() { + } + + public EzyMongoAccountService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java new file mode 100644 index 00000000..1915fa81 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import com.hazelcast.config.Config; +import com.hazelcast.core.HazelcastInstance; +import com.mongodb.client.MongoDatabase; +import com.tvd12.ezyfoxserver.function.EzyCreation; +import com.tvd12.ezyfoxserver.hazelcast.EzyMongoDatabaseHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.util.EzyHazelcastConfigs; + +public class ExampleHazelcastCreator implements EzyCreation { + + private String filePath; + private MongoDatabase database; + + public ExampleHazelcastCreator filePath(String filePath) { + this.filePath = filePath; + return this; + } + + public ExampleHazelcastCreator database(MongoDatabase database) { + this.database = database; + return this; + } + + @Override + public HazelcastInstance create() { + EzyMongoDatabaseHazelcastFactory factory = new EzyMongoDatabaseHazelcastFactory(); + factory.setDatabase(database); + factory.setMapstoresFetcher(newMapstoresFetcher()); + return factory.newHazelcast(newConfig()); + } + + private Config newConfig() { + return EzyHazelcastConfigs.newXmlConfigBuilder(filePath); + } + + private EzyMapstoresFetcher newMapstoresFetcher() { + return EzySimpleMapstoresFetcher.builder() + .scan("com.tvd12.ezyfoxserver.hazelcast.testing.mapstore") + .build(); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java new file mode 100644 index 00000000..c2a2b683 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.core.HazelcastInstance; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzySimpleMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleMaxIdService; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyInputStreamMongoClientLoader; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyMongoClientLoader; +import com.tvd12.ezyfoxserver.stream.EzyAnywayInputStreamLoader; +import com.tvd12.test.base.BaseTest; + +public abstract class HazelcastBaseTest extends BaseTest { + + protected static final MongoClient MONGO_CLIENT; + protected static final MongoDatabase DATABASE; + protected static final HazelcastInstance HZ_INSTANCE; + protected static final EzyMaxIdService MAX_ID_SERVICE; + protected static final EzyMapTransactionFactory MAP_TRANSACTION_FACTORY; + + static { + MONGO_CLIENT = newMongoClient(); + DATABASE = MONGO_CLIENT.getDatabase("test"); + HZ_INSTANCE = newHzInstance(); + MAP_TRANSACTION_FACTORY = newMapTransactionFactory(); + MAX_ID_SERVICE = newMaxIdService(); + Runtime.getRuntime().addShutdownHook(new Thread(() -> MONGO_CLIENT.close())); + } + + private static HazelcastInstance newHzInstance() { + return new ExampleHazelcastCreator() + .filePath("hazelcast.xml") + .database(MONGO_CLIENT.getDatabase("test")) + .create(); + } + + private static EzyMaxIdService newMaxIdService() { + EzySimpleMaxIdService service = new EzySimpleMaxIdService(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + return service; + } + + private static EzyMapTransactionFactory newMapTransactionFactory() { + return new EzySimpleMapTransactionFactory(HZ_INSTANCE); + } + + private static MongoClient newMongoClient() { + return new EzyInputStreamMongoClientLoader() + .inputStream(getMongoConfigInputStream()) + .property(EzyMongoClientLoader.DATABASE, "test") + .properties(EzyMaps.newHashMap(EzyMongoClientLoader.DATABASE, "test")) + .load(); + } + + private static InputStream getMongoConfigInputStream() { + return EzyAnywayInputStreamLoader.builder() + .context(HazelcastBaseTest.class) + .build() + .load("mongo_config.properties"); + } + + protected Logger getLogger() { + return LoggerFactory.getLogger(getClass()); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/constant/Entities.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/constant/Entities.java new file mode 100644 index 00000000..a9dded58 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/constant/Entities.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.constant; + +public final class Entities { + + public static final String USER = "ezyfox.server.hazelcast.mongodb.example_users"; + + private Entities() { + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java new file mode 100644 index 00000000..925e4963 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.entity; + +import java.io.Serializable; + +import com.tvd12.ezyfoxserver.database.entity.EzyHasIdEntity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ExampleUser implements EzyHasIdEntity, Serializable { + private static final long serialVersionUID = 9176938015407765002L; + + private Long userId; + private String username; + + public ExampleUser(String username) { + this.username = username; + } + + @Override + public String getId() { + return username; + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyMongoAccountTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyMongoAccountTest.java new file mode 100644 index 00000000..d27fdc3e --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyMongoAccountTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.entity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyMongoAccount; +import com.tvd12.test.base.BaseTest; + +public class EzyMongoAccountTest extends BaseTest { + + @Test + public void test() { + EzyMongoAccount account = new EzyMongoAccount(); + account.setId(1L); + assert account.getId() == 1L; + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/factory/EzyMongoAccoutFactoryTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/factory/EzyMongoAccoutFactoryTest.java new file mode 100644 index 00000000..f985cc1a --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/factory/EzyMongoAccoutFactoryTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.factory; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMongoAccoutFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyMongoAccoutFactoryTest extends BaseTest { + + @Test + public void test() { + EzyMongoAccoutFactory factory = new EzyMongoAccoutFactory(); + factory.newAccount(1L); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstore.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstore.java new file mode 100644 index 00000000..0ea59cdf --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstore.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMongoMapstore; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; + +public class ExampleMongoMapstore extends EzyMongoMapstore { + + @Override + public void store(String key, ExampleUser value) { + } + + @Override + public ExampleUser load(String key) { + return null; + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstoreTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstoreTest.java new file mode 100644 index 00000000..7de7f5f7 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleMongoMapstoreTest.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class ExampleMongoMapstoreTest extends HazelcastBaseTest { + + @Test + public void test() { + ExampleMongoMapstore mapstore = new ExampleMongoMapstore(); + mapstore.setMongoClient(MONGO_CLIENT); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java new file mode 100644 index 00000000..399366a6 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.database.annotation.EzyMapstore; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyAbstractMapstore; +import com.tvd12.ezyfoxserver.hazelcast.testing.constant.Entities; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +@EzyMapstore(Entities.USER) +public class ExampleUserMapstore extends EzyAbstractMapstore { + + private static final Map MAP = + EzyMaps.newHashMap("dungtv", new ExampleUser("dungtv")); + + @Override + public void store(String key, ExampleUser value) { + MAP.put(key, value); + } + + @Override + public ExampleUser load(String key) { + return MAP.get(key); + } + + + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzyMongoMaxIdMapstoreTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzyMongoMaxIdMapstoreTest.java new file mode 100644 index 00000000..86d88c37 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzyMongoMaxIdMapstoreTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMongoMaxIdMapstore; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class EzyMongoMaxIdMapstoreTest extends HazelcastBaseTest { + + @Test + public void test() { + EzyMongoMaxIdMapstore mapstore = new EzyMongoMaxIdMapstore(); + mapstore.setDatabase(DATABASE); + mapstore.postInit(); + mapstore.load("not exists key"); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserTest.java new file mode 100644 index 00000000..0c5e3744 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserTest.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.hazelcast.core.IMap; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.constant.Entities; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; + +public class ExampleUserTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + EzySimpleMaxIdService service = new EzySimpleMaxIdService(); + service.setHazelcastInstance(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + long userId1 = service.incrementAndGet(Entities.USER); + long userId2 = service.incrementAndGet(Entities.USER); + + ExampleUser user1 = new ExampleUser(userId1, "user1"); + ExampleUser user2 = new ExampleUser(userId2, "user2"); + + IMap userMap = HZ_INSTANCE.getMap(Entities.USER); + userMap.set("user1", user1); + userMap.set("user2", user2); + + Thread.sleep(3000); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoAccountServiceTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoAccountServiceTest.java new file mode 100644 index 00000000..3582fc49 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoAccountServiceTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.service.EzyMongoAccountService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class EzyMongoAccountServiceTest extends HazelcastBaseTest { + + @Test + public void test() { + EzyMongoAccountService service = new EzyMongoAccountService(); + service = new EzyMongoAccountService(HZ_INSTANCE); + service.clear(); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoDatabaseHazelcastFactoryTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoDatabaseHazelcastFactoryTest.java new file mode 100644 index 00000000..635b6017 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyMongoDatabaseHazelcastFactoryTest.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +public class EzyMongoDatabaseHazelcastFactoryTest { + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java new file mode 100644 index 00000000..b47849eb --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class MaxIdServiceTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + MAX_ID_SERVICE.incrementAndGet("count"); + long time = System.currentTimeMillis(); + long newId = 0; + for(int i = 0 ; i < 10000 ; i++) + newId = MAX_ID_SERVICE.incrementAndGet("count"); + long offset = System.currentTimeMillis() - time; + System.err.println("elapsed = " + offset + ", newId = " + newId); + Thread.sleep(5000L); + } + +} diff --git a/ezyfox-server-hazelcast-mongodb/src/test/resources/AllTests.tng.xml b/ezyfox-server-hazelcast-mongodb/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..38755046 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/resources/AllTests.tng.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-mongodb/src/test/resources/hazelcast.xml b/ezyfox-server-hazelcast-mongodb/src/test/resources/hazelcast.xml new file mode 100644 index 00000000..6ca0e4de --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/resources/hazelcast.xml @@ -0,0 +1,24 @@ + + + http://localhost:8080/mancenter + + + dev + dev-pass + + + + true + slf4j + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-mongodb/src/test/resources/mongo_config.properties b/ezyfox-server-hazelcast-mongodb/src/test/resources/mongo_config.properties new file mode 100644 index 00000000..d8c3d5c9 --- /dev/null +++ b/ezyfox-server-hazelcast-mongodb/src/test/resources/mongo_config.properties @@ -0,0 +1,5 @@ +database.mongo.host=127.0.0.1 +database.mongo.port=27017 +database.mongo.database=test +database.mongo.username=root +database.mongo.password=123456 \ No newline at end of file diff --git a/ezyfox-server-hazelcast-morphia/assembly.xml b/ezyfox-server-hazelcast-morphia/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-morphia/pom.xml b/ezyfox-server-hazelcast-morphia/pom.xml new file mode 100644 index 00000000..fe8e72b6 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-hazelcast-morphia + ezyfox-server-hazelcast-morphia + 1.0.0 + http://maven.apache.org + + 1.0.0 + 1.0.0 + + + + + com.tvd12 + ezyfox-server-morphia + ${ezy.morphia.version} + + + com.tvd12 + ezyfox-server-hazelcast-mongodb + ${ezy.hazelcast.mongodb.version} + + + diff --git a/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatastoreHazelcastFactory.java b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatastoreHazelcastFactory.java new file mode 100644 index 00000000..c9334dc5 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMongoDatastoreHazelcastFactory.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import org.mongodb.morphia.Datastore; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMongoDatabaseMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMongoDatastoreMapstoreCreator; +import com.tvd12.ezyfoxserver.morphia.EzyDatastoreAware; + +import lombok.Setter; + +@Setter +public class EzyMongoDatastoreHazelcastFactory + extends EzyMongoDatabaseHazelcastFactory + implements EzyDatastoreAware { + + protected Datastore datastore; + + @Override + protected EzyMongoDatabaseMapstoreCreator newDatabaseMapstoreCreator() { + EzyMongoDatastoreMapstoreCreator creator = new EzyMongoDatastoreMapstoreCreator(); + creator.setDatastore(datastore); + return creator; + } + +} diff --git a/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMorphiaAccount.java b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMorphiaAccount.java new file mode 100644 index 00000000..27bdfb70 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyMorphiaAccount.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.hazelcast.entity; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Entity(value = EzyMapNames.ACCOUNT, noClassnameStored = true) +public class EzyMorphiaAccount extends EzyAbstractAccount { + private static final long serialVersionUID = 3884020036545997524L; + + @Id + private Long id; + +} diff --git a/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstore.java b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstore.java new file mode 100644 index 00000000..c0df776f --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstore.java @@ -0,0 +1,23 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import org.mongodb.morphia.Datastore; + +import com.tvd12.ezyfoxserver.morphia.EzyDatastoreAware; + +import lombok.Setter; + +/** + * @author tavandung12 + * + */ +public abstract class EzyMongoDatastoreMapstore + extends EzyAbstractMapstore + implements EzyDatastoreAware { + + @Setter + protected Datastore datastore; + +} diff --git a/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstoreCreator.java b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstoreCreator.java new file mode 100644 index 00000000..35b33541 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMongoDatastoreMapstoreCreator.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.Properties; + +import org.mongodb.morphia.Datastore; + +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.morphia.EzyDatastoreAware; + +import lombok.Setter; + +public class EzyMongoDatastoreMapstoreCreator + extends EzyMongoDatabaseMapstoreCreator + implements EzyDatastoreAware { + + @Setter + protected Datastore datastore; + + @SuppressWarnings("rawtypes") + @Override + public MapStore create(String mapName, Properties properties) { + MapStore mapstore = super.create(mapName, properties); + if(mapstore instanceof EzyDatastoreAware) + ((EzyDatastoreAware)mapstore).setDatastore(datastore); + return mapstore; + } + +} diff --git a/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/HazelcastBaseTest.java b/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/HazelcastBaseTest.java new file mode 100644 index 00000000..98ea03f8 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/HazelcastBaseTest.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.config.Config; +import com.hazelcast.core.HazelcastInstance; +import com.mongodb.MongoClient; +import com.tvd12.ezyfoxserver.hazelcast.EzyMongoDatastoreHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyInputStreamMongoClientLoader; +import com.tvd12.test.base.BaseTest; + +public abstract class HazelcastBaseTest extends BaseTest { + + protected static final MongoClient MONGO_CLIENT; + protected static final EzyMaxIdService MAX_ID_SERVICE; + protected static final HazelcastInstance HZ_INSTANCE; + + static { + MONGO_CLIENT = newMongoClient(); + HZ_INSTANCE = newHzInstance(); + MAX_ID_SERVICE = newMaxIdService(); + + Runtime.getRuntime().addShutdownHook(new Thread(()-> { + System.err.println("\n\nshutdown hook, close mongo client\n\n"); + MONGO_CLIENT.close(); + })); + } + + private static MongoClient newMongoClient() { + return new EzyInputStreamMongoClientLoader() + .inputStream(getConfigStream()) + .load(); + } + + private static EzyMaxIdService newMaxIdService() { + EzySimpleMaxIdService service = new EzySimpleMaxIdService(HZ_INSTANCE); + return service; + } + + private static HazelcastInstance newHzInstance() { + EzyMongoDatastoreHazelcastFactory factory = new EzyMongoDatastoreHazelcastFactory(); + factory.setDatabase(MONGO_CLIENT.getDatabase("test")); + return factory.newHazelcast(new Config()); + } + + private static InputStream getConfigStream() { + return HazelcastBaseTest.class.getResourceAsStream("/mongo_config.properties"); + } + + protected Object newServiceBuilder() { + return null; + } + + protected Logger getLogger() { + return LoggerFactory.getLogger(getClass()); + } + +} diff --git a/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java b/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java new file mode 100644 index 00000000..b47849eb --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MaxIdServiceTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class MaxIdServiceTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + MAX_ID_SERVICE.incrementAndGet("count"); + long time = System.currentTimeMillis(); + long newId = 0; + for(int i = 0 ; i < 10000 ; i++) + newId = MAX_ID_SERVICE.incrementAndGet("count"); + long offset = System.currentTimeMillis() - time; + System.err.println("elapsed = " + offset + ", newId = " + newId); + Thread.sleep(5000L); + } + +} diff --git a/ezyfox-server-hazelcast-morphia/src/test/resources/AllTests.tng.xml b/ezyfox-server-hazelcast-morphia/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-morphia/src/test/resources/hazelcast.xml b/ezyfox-server-hazelcast-morphia/src/test/resources/hazelcast.xml new file mode 100644 index 00000000..6ca0e4de --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/test/resources/hazelcast.xml @@ -0,0 +1,24 @@ + + + http://localhost:8080/mancenter + + + dev + dev-pass + + + + true + slf4j + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast-morphia/src/test/resources/mongo_config.properties b/ezyfox-server-hazelcast-morphia/src/test/resources/mongo_config.properties new file mode 100644 index 00000000..d8c3d5c9 --- /dev/null +++ b/ezyfox-server-hazelcast-morphia/src/test/resources/mongo_config.properties @@ -0,0 +1,5 @@ +database.mongo.host=127.0.0.1 +database.mongo.port=27017 +database.mongo.database=test +database.mongo.username=root +database.mongo.password=123456 \ No newline at end of file diff --git a/ezyfox-server-hazelcast/assembly.xml b/ezyfox-server-hazelcast/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-hazelcast/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast/pom.xml b/ezyfox-server-hazelcast/pom.xml new file mode 100644 index 00000000..23062421 --- /dev/null +++ b/ezyfox-server-hazelcast/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-hazelcast + ezyfox-server-hazelcast + 1.0.0 + http://maven.apache.org + + 3.9 + 1.0.0 + 1.0.0 + + + + + com.hazelcast + hazelcast + ${hazelcast.version} + + + com.hazelcast + hazelcast-client + ${hazelcast.version} + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + com.tvd12 + ezyfox-server-database + ${ezy.database.version} + + + diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyAbstractHazelcastFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyAbstractHazelcastFactory.java new file mode 100644 index 00000000..0b1d6b09 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyAbstractHazelcastFactory.java @@ -0,0 +1,115 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.MapStoreFactory; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzySimpleMapstoreFactory; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcherAware; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@Setter +@SuppressWarnings("rawtypes") +public abstract class EzyAbstractHazelcastFactory + extends EzyLoggable + implements EzyHazelcastFactory, EzyMapstoresFetcherAware { + + protected EzyMapstoresFetcher mapstoresFetcher; + + @Override + public HazelcastInstance newHazelcast(Config config) { + customizeConfig(config); + addMapConfigs(config, getMapConfigs()); + return Hazelcast.newHazelcastInstance(config); + } + + protected void customizeConfig(Config config) { + EzyConfigCustomizer customizer = getConfigCustomizer(); + customizer.customize(config); + } + + protected void addMapConfigs(Config config, Iterable mapConfigs) { + Iterator iterator = mapConfigs.iterator(); + while(iterator.hasNext()) + config.addMapConfig(iterator.next()); + } + + protected Iterable getMapConfigs() { + EzyMapConfigsFetcher fetcher = getMapConfigsFetcher(); + return fetcher.get(); + } + + protected EzyConfigCustomizer getConfigCustomizer() { + return newConfigCustomizer(); + } + protected EzyMapConfigsFetcher getMapConfigsFetcher() { + return newMapConfigsFetcher(); + } + + protected EzyConfigCustomizer newConfigCustomizer() { + return new EzySimpleConfigCustomizer(); + } + + protected EzyMapConfigsFetcher newMapConfigsFetcher() { + EzySimpleMapConfigsFetcher.Builder builder + = newMapConfigsFetcherBuilder(); + EzyMapstoreCreator mapstoreCreator = newMapstoreCreator(); + if(mapstoreCreator instanceof EzyMapstoresFetcherAware) + ((EzyMapstoresFetcherAware)mapstoreCreator) + .setMapstoresFetcher(mapstoresFetcher); + MapStoreFactory mapstoreFactory = newMapstoreFactory(mapstoreCreator); + builder.mapstoreFactory(mapstoreFactory); + Set mapNames = new HashSet<>(); + mapNames.addAll(normalMapNames()); + mapNames.addAll(mapstoreCreator.getMapNames()); + builder.mapNames(mapNames); + applyMapConfigs(builder); + applyMapstoreConfigs(builder); + return builder.build(); + } + + protected Set normalMapNames() { + return new HashSet<>(); + } + + protected MapStoreFactory newMapstoreFactory(EzyMapstoreCreator mapstoreCreator) { + return new EzySimpleMapstoreFactory(mapstoreCreator); + } + + protected EzySimpleMapConfigsFetcher.Builder newMapConfigsFetcherBuilder() { + return EzySimpleMapConfigsFetcher.builder(); + } + + protected void applyMapConfigs( + EzySimpleMapConfigsFetcher.Builder builder) { + } + + protected void applyMapstoreConfigs( + EzySimpleMapConfigsFetcher.Builder builder) { + builder + .mapAllConfigApply(mc -> { + mc.setBackupCount(0); + mc.setAsyncBackupCount(1); + }) + .mapstoreAllConfigApply(mc -> { + mc.setWriteDelaySeconds(3); + mc.setWriteBatchSize(25); + }) + .mapstoreConfigApply(EzyMapNames.MAX_ID, mc -> { + mc.setWriteDelaySeconds(2); + }); + } + + protected abstract EzyMapstoreCreator newMapstoreCreator(); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyConfigCustomizer.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyConfigCustomizer.java new file mode 100644 index 00000000..66ee032f --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyConfigCustomizer.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.hazelcast.config.Config; + +public interface EzyConfigCustomizer { + + void customize(Config config); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyHazelcastFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyHazelcastFactory.java new file mode 100644 index 00000000..30f4df8f --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyHazelcastFactory.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.hazelcast.config.Config; +import com.hazelcast.core.HazelcastInstance; + +public interface EzyHazelcastFactory { + + HazelcastInstance newHazelcast(Config config); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMapConfigsFetcher.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMapConfigsFetcher.java new file mode 100644 index 00000000..cb23db03 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzyMapConfigsFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.hazelcast.config.MapConfig; + +public interface EzyMapConfigsFetcher { + + Iterable get(); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleConfigCustomizer.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleConfigCustomizer.java new file mode 100644 index 00000000..6a5fb1b0 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleConfigCustomizer.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.hazelcast.config.Config; + +public class EzySimpleConfigCustomizer implements EzyConfigCustomizer { + + @Override + public void customize(Config config) { + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleHazelcastFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleHazelcastFactory.java new file mode 100644 index 00000000..de44292a --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleHazelcastFactory.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoreCreator; + +public class EzySimpleHazelcastFactory extends EzyAbstractHazelcastFactory { + + @Override + protected EzyMapstoreCreator newMapstoreCreator() { + return new EzySimpleMapstoreCreator(); + } + + + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleMapConfigsFetcher.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleMapConfigsFetcher.java new file mode 100644 index 00000000..0c8840ed --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/EzySimpleMapConfigsFetcher.java @@ -0,0 +1,150 @@ +package com.tvd12.ezyfoxserver.hazelcast; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.MapStoreConfig; +import com.hazelcast.config.MapStoreConfig.InitialLoadMode; +import com.hazelcast.core.MapStoreFactory; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.function.EzyApply; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings("rawtypes") +public class EzySimpleMapConfigsFetcher + extends EzyLoggable + implements EzyMapConfigsFetcher { + + protected Set mapNames; + protected MapStoreFactory mapstoreFactory; + protected EzyApply mapAllConfigApply; + protected EzyApply mapstoreAllConfigApply; + protected Map> mapConfigApplies; + protected Map> mapstoreConfigApplies; + + protected EzySimpleMapConfigsFetcher(Builder builder) { + this.mapNames = builder.mapNames; + this.mapstoreFactory = builder.mapstoreFactory; + this.mapConfigApplies = builder.mapConfigApplies; + this.mapAllConfigApply = builder.mapAllConfigApply; + this.mapstoreConfigApplies = builder.mapstoreConfigApplies; + this.mapstoreAllConfigApply = builder.mapstoreAllConfigApply; + } + + @Override + public Iterable get() { + return EzyLists.newArrayList( + getMapNames(), (mn) -> newMapConfig(mn)); + } + + protected MapConfig newMapConfig(String name) { + MapConfig mapCfg = new MapConfig(); + mapCfg.setName(name); + mapCfg.setMapStoreConfig(newMapStoreConfig(name)); + applyCommonConfig(mapCfg); + applyConfig(name, mapCfg); + getLogger().debug("config map: {}", name); + return mapCfg; + } + + protected void applyConfig(String mapName, MapConfig config) { + if(mapConfigApplies.containsKey(mapName)) + mapConfigApplies.get(mapName).apply(config); + } + + protected void applyCommonConfig(MapConfig config) { + if(mapAllConfigApply != null) + mapAllConfigApply.apply(config); + } + + protected MapStoreConfig newMapStoreConfig(String mapName) { + MapStoreConfig config = new MapStoreConfig(); + config.setEnabled(true); + config.setInitialLoadMode(InitialLoadMode.EAGER); + applyCommonConfig(config); + applyConfig(mapName, config); + config.setFactoryImplementation(mapstoreFactory); + return config; + } + + protected void applyConfig(String mapName, MapStoreConfig config) { + if(mapstoreConfigApplies.containsKey(mapName)) + mapstoreConfigApplies.get(mapName).apply(config); + } + + protected void applyCommonConfig(MapStoreConfig config) { + if(mapstoreAllConfigApply != null) + mapstoreAllConfigApply.apply(config); + } + + protected Set getMapNames() { + return mapNames; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected Set mapNames; + protected MapStoreFactory mapstoreFactory; + protected EzyApply mapAllConfigApply; + protected EzyApply mapstoreAllConfigApply; + protected Map> mapConfigApplies = new HashMap<>(); + protected Map> mapstoreConfigApplies = new HashMap<>(); + + public Builder mapNames(Set mapNames) { + this.mapNames = mapNames; + return this; + } + + public Builder mapstoreFactory(MapStoreFactory mapStoreFactory) { + this.mapstoreFactory = mapStoreFactory; + return this; + } + + public Builder mapConfigApply( + String mapName, EzyApply apply) { + this.mapConfigApplies.put(mapName, apply); + return this; + } + + public Builder mapstoreConfigApply( + String mapName, EzyApply apply) { + this.mapstoreConfigApplies.put(mapName, apply); + return this; + } + + public Builder mapConfigApplies( + Map> mapConfigApplies) { + this.mapConfigApplies.putAll(mapConfigApplies); + return this; + } + + public Builder mapstoreConfigApplies( + Map> mapStoreConfigApplies) { + this.mapstoreConfigApplies.putAll(mapStoreConfigApplies); + return this; + } + + public Builder mapAllConfigApply(EzyApply mapAllConfigApply) { + this.mapAllConfigApply = mapAllConfigApply; + return this; + } + + public Builder mapstoreAllConfigApply(EzyApply mapStoreAllConfigApply) { + this.mapstoreAllConfigApply = mapStoreAllConfigApply; + return this; + } + + @Override + public EzySimpleMapConfigsFetcher build() { + return new EzySimpleMapConfigsFetcher(this); + } + + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/annotation/EzyMapServiceAutoImpl.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/annotation/EzyMapServiceAutoImpl.java new file mode 100644 index 00000000..261d0ae8 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/annotation/EzyMapServiceAutoImpl.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Documented +@Retention(RUNTIME) +@Target({ TYPE }) +public @interface EzyMapServiceAutoImpl { + + /** + * @return the map name + */ + String value(); + + /** + * + * @return the bean name + */ + String name() default ""; + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/bean/EzyServicesImplementor.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/bean/EzyServicesImplementor.java new file mode 100644 index 00000000..12188edc --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/bean/EzyServicesImplementor.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.hazelcast.bean; + +import java.util.Map; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.impl.EzySimpleSerivcesImplementor; + +public interface EzyServicesImplementor { + + public static EzyServicesImplementor newInstance() { + return new EzySimpleSerivcesImplementor(); + } + + public abstract EzyServicesImplementor scan(String packageName); + + public abstract EzyServicesImplementor scan(String... packageNames); + + public abstract EzyServicesImplementor scan(Iterable packageNames); + + public abstract EzyServicesImplementor serviceInterface(String mapName, Class itf); + + public abstract Map, Object> implement(HazelcastInstance hzInstance); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/constant/EzyMapNames.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/constant/EzyMapNames.java new file mode 100644 index 00000000..b26f65e4 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/constant/EzyMapNames.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.hazelcast.constant; + +public final class EzyMapNames { + + public static final String MAX_ID = "max_ids"; + public static final String ACCOUNT = "accounts"; + + private EzyMapNames() { + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAbstractAccount.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAbstractAccount.java new file mode 100644 index 00000000..0af1b503 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAbstractAccount.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.hazelcast.entity; + +import java.util.Date; + +import com.tvd12.ezyfoxserver.exception.EzyNegativeValueException; +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public abstract class EzyAbstractAccount implements EzyAccount, EzyAccountTypeAware { + private static final long serialVersionUID = -3802880651857320583L; + + protected Long value = 0L; + protected String type = ""; + protected Date creationDate; + protected Date lastUpdatedDate; + protected boolean acceptNegativeValue; + + public abstract void setId(Long id); + + @Override + public Long update(long value) { + long newValue = this.value + value; + this.checkAndSetValue(newValue); + return newValue; + } + + @Override + public Long[] update(double percent, long initValue) { + long oldValue = value; + long updated = (long) (percent * value); + long newValue = value + updated + initValue; + this.checkAndSetValue(newValue); + return new Long[] {updated, newValue, oldValue}; + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(acc -> acc.getId()) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .append(getId()) + .toHashCode(); + } + + private void checkAndSetValue(long value) { + if(value < 0 && !acceptNegativeValue) + throw new EzyNegativeValueException(value); + this.value = value; + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccount.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccount.java new file mode 100644 index 00000000..7ad3d4c2 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccount.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.entity; + +import java.io.Serializable; +import java.util.Date; + +import com.tvd12.ezyfoxserver.database.entity.EzyHasIdEntity; + +public interface EzyAccount extends EzyHasIdEntity, Serializable { + + String getType(); + + Long getValue(); + + Long update(long value); + + Long[] update(double percent, long initValue); + + boolean isAcceptNegativeValue(); + + Date getCreationDate(); + + Date getLastUpdatedDate(); + + void setLastUpdatedDate(Date date); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccountTypeAware.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccountTypeAware.java new file mode 100644 index 00000000..c19e0c4d --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/entity/EzyAccountTypeAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.hazelcast.entity; + +public interface EzyAccountTypeAware { + + void setType(String type); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractAccoutFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractAccoutFactory.java new file mode 100644 index 00000000..e874efc6 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractAccoutFactory.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import java.util.Date; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzyAbstractAccoutFactory + extends EzyLoggable + implements EzyAccountFactory { + + @Override + public final EzyAccount newAccount(long accountId, boolean acceptNegativeValue) { + EzyAbstractAccount account = newAccount(); + account.setId(accountId); + account.setCreationDate(new Date()); + account.setLastUpdatedDate(new Date()); + account.setAcceptNegativeValue(acceptNegativeValue); + return account; + } + + protected abstract EzyAbstractAccount newAccount(); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractMapstoreFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractMapstoreFactory.java new file mode 100644 index 00000000..f25e4bab --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAbstractMapstoreFactory.java @@ -0,0 +1,33 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import java.util.Properties; + +import com.hazelcast.core.MapLoader; +import com.hazelcast.core.MapStoreFactory; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyPostInit; + +/** + * @author tavandung12 + * + */ +@SuppressWarnings("rawtypes") +public abstract class EzyAbstractMapstoreFactory + extends EzyLoggable + implements MapStoreFactory { + + @Override + public final MapLoader newMapStore(String mapName, Properties properties) { + Object map = newMapstore(mapName, properties); + if(map instanceof EzyPostInit) + ((EzyPostInit)map).postInit(); + return (MapLoader) map; + + } + + protected abstract Object newMapstore(String mapName, Properties properties); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAccountFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAccountFactory.java new file mode 100644 index 00000000..4f01de36 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyAccountFactory.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; + +public interface EzyAccountFactory { + + EzyAccount newAccount(long accountId, boolean acceptNegativeValue); + + default EzyAccount newAccount(long accountId) { + return newAccount(accountId, false); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactory.java new file mode 100644 index 00000000..803fab77 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactory.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapApplyTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionOptions; + +public interface EzyMapTransactionFactory { + + EzyMapApplyTransaction + newApplyTransaction(String mapName, EzyTransactionOptions options); + + EzyMapReturnTransaction + newReturnTransaction(String mapName, EzyTransactionOptions options); + + default EzyMapApplyTransaction newApplyTransaction(String mapName) { + return newApplyTransaction(mapName, EzyTransactionOptions.newInstance()); + } + + default EzyMapReturnTransaction newReturnTransaction(String mapName) { + return newReturnTransaction(mapName, EzyTransactionOptions.newInstance()); + } +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactoryAware.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactoryAware.java new file mode 100644 index 00000000..b4d1111b --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzyMapTransactionFactoryAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +public interface EzyMapTransactionFactoryAware { + + void setMapTransactionFactory(EzyMapTransactionFactory mapTransactionFactory); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapTransactionFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapTransactionFactory.java new file mode 100644 index 00000000..4b21df7d --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapTransactionFactory.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import static com.hazelcast.transaction.TransactionOptions.TransactionType.valueOf; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.transaction.TransactionContext; +import com.hazelcast.transaction.TransactionOptions; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapApplyTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionOptions; +import com.tvd12.ezyfoxserver.hazelcast.transaction.impl.EzySimpleMapApplyTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.impl.EzySimpleMapReturnTransaction; + +public class EzySimpleMapTransactionFactory implements EzyMapTransactionFactory { + + protected final HazelcastInstance hazelcastInstance; + + public EzySimpleMapTransactionFactory(HazelcastInstance hazelcastInstance) { + this.hazelcastInstance = hazelcastInstance; + } + + @Override + public EzyMapApplyTransaction + newApplyTransaction(String mapName, EzyTransactionOptions options) { + TransactionOptions txOptions = newHazelcastTransactionOptions(options); + TransactionContext txCxt = hazelcastInstance.newTransactionContext(txOptions); + return new EzySimpleMapApplyTransaction<>(txCxt, mapName); + } + + @Override + public EzyMapReturnTransaction + newReturnTransaction(String mapName, EzyTransactionOptions options) { + TransactionOptions txOptions = newHazelcastTransactionOptions(options); + TransactionContext txCxt = hazelcastInstance.newTransactionContext(txOptions); + return new EzySimpleMapReturnTransaction<>(txCxt, mapName); + } + + private TransactionOptions newHazelcastTransactionOptions(EzyTransactionOptions options) { + return new TransactionOptions() + .setTimeout(options.getTimeout(), options.getTimeoutUnit()) + .setTransactionType(valueOf(options.getTransactionType().toString())) + .setDurability(options.getDurability()); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapstoreFactory.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapstoreFactory.java new file mode 100644 index 00000000..b25768cf --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/factory/EzySimpleMapstoreFactory.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.hazelcast.factory; + +import java.util.Properties; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EzySimpleMapstoreFactory extends EzyAbstractMapstoreFactory { + + protected EzyMapstoreCreator mapstoreCreator; + + @Override + protected Object newMapstore(String mapName, Properties properties) { + return mapstoreCreator.create(mapName, properties); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleMapNameFetcher.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleMapNameFetcher.java new file mode 100644 index 00000000..9fa853aa --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleMapNameFetcher.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.hazelcast.impl; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; + +public class EzySimpleMapNameFetcher { + + public String getMapName(Class clazz) { + EzyAutoImpl autoImplAnno = clazz.getAnnotation(EzyAutoImpl.class); + if(autoImplAnno != null) { + return getMapName(autoImplAnno); + } + EzyMapServiceAutoImpl mapServiceAuto = clazz.getAnnotation(EzyMapServiceAutoImpl.class); + if(mapServiceAuto != null) { + return getMapName(mapServiceAuto); + } + throw new IllegalArgumentException("can't get map name, annotate your interface with:\n" + + "@EzyAutoImpl(properties = {\n" + + "\t@EzyKeyValue(key = \"map.name\", value = \"\")\n" + + "})" + + "\nor\n" + + "@EzyMapServiceAutoImpl(\"\")"); + } + + private String getMapName(EzyMapServiceAutoImpl anno) { + return anno.value(); + } + + private String getMapName(EzyAutoImpl anno) { + EzyKeyValue[] props = anno.properties(); + EzyKeyValue keyValue = null; + if(props.length != 0) { + for(EzyKeyValue pro : props) { + if(pro.key().equals("map.name")) { + keyValue = pro; break; + } + } + } + if(keyValue == null) { + throw new IllegalArgumentException("can't get map name, annotate your interface with:\n" + + "@EzyAutoImpl(properties = {\n" + + "\t@EzyKeyValue(key = \"map.name\", value = \"\")\n" + + "})"); + } + return keyValue.value(); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleSerivcesImplementor.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleSerivcesImplementor.java new file mode 100644 index 00000000..1a4be473 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleSerivcesImplementor.java @@ -0,0 +1,85 @@ +package com.tvd12.ezyfoxserver.hazelcast.impl; + +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.common.collect.Sets; +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.bean.EzyServicesImplementor; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleSerivcesImplementor + extends EzyLoggable + implements EzyServicesImplementor { + + protected Set> autoImplInterfaces = new HashSet<>(); + protected Map> autoImplInterfaceMap = new HashMap<>(); + + public EzyServicesImplementor scan(String packageName) { + autoImplInterfaces.addAll(getAutoImplRepoInterfaces(packageName)); + return this; + } + + public EzyServicesImplementor scan(String... packageNames) { + return scan(Sets.newHashSet(packageNames)); + } + + public EzyServicesImplementor scan(Iterable packageNames) { + packageNames.forEach(this::scan); + return this; + } + + @Override + public EzyServicesImplementor serviceInterface(String mapName, Class itf) { + autoImplInterfaceMap.put(mapName, itf); + return this; + } + + @Override + public Map, Object> implement(HazelcastInstance hzInstance) { + Map, Object> repositories = new ConcurrentHashMap<>(); + for(Class itf : autoImplInterfaces) { + Object repo = newRepoImplementor(itf).implement(hzInstance); + repositories.put(itf, repo); + } + for(String mapName : autoImplInterfaceMap.keySet()) { + Class itf = autoImplInterfaceMap.get(mapName); + Object repo = newRepoImplementor(itf).implement(hzInstance, mapName); + repositories.put(itf, repo); + } + return repositories; + } + + private EzySimpleServiceImplementor newRepoImplementor(Class itf) { + return new EzySimpleServiceImplementor(new EzyClass(itf)); + } + + private Set> getRepoInterfaces(String packageName) { + return EzyPackages.getExtendsClasses(packageName, EzyHazelcastMapService.class); + } + + private Collection> getAutoImplRepoInterfaces(String packageName) { + Set> classes = getRepoInterfaces(packageName); + return EzyLists.filter(classes, this::isAutoImplRepoInterface); + } + + private boolean isAutoImplRepoInterface(Class clazz) { + return (clazz.isAnnotationPresent(EzyAutoImpl.class) || + clazz.isAnnotationPresent(EzyMapServiceAutoImpl.class)) && + Modifier.isPublic(clazz.getModifiers()) && + Modifier.isInterface(clazz.getModifiers()); + + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleServiceImplementor.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleServiceImplementor.java new file mode 100644 index 00000000..9633a51b --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/impl/EzySimpleServiceImplementor.java @@ -0,0 +1,109 @@ +package com.tvd12.ezyfoxserver.hazelcast.impl; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.concurrent.atomic.AtomicInteger; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleHazelcastMapService; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethods; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.CtNewMethod; + +public class EzySimpleServiceImplementor { + + private final EzyClass clazz; + + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzySimpleServiceImplementor(EzyClass clazz) { + this.clazz = clazz; + this.checkInterface(clazz); + } + + public Object implement(HazelcastInstance hzInstance) { + return implement(hzInstance, getMapName()); + } + + public Object implement(HazelcastInstance hzInstance, String mapName) { + try { + return doimplement(hzInstance, mapName); + } + catch(Exception e) { + throw new IllegalStateException(e); + } + } + + private void checkInterface(EzyClass clazz) { + if(!Modifier.isInterface(clazz.getModifiers())) + throw new IllegalArgumentException(clazz + " is not an interface"); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object doimplement(HazelcastInstance hzInstance, String mapName) throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyClass superClass = getSuperClass(); + String getMapNameMethodContent = makeGetMapNameMethodContent(mapName); + implClass.setInterfaces(new CtClass[] { pool.get(clazz.getName()) }); + implClass.setSuperclass(pool.get(superClass.getName())); + CtConstructor constructorMethod = makeContructorMethod(pool, implClass); + implClass.addConstructor(constructorMethod); + implClass.addMethod(CtNewMethod.make(getMapNameMethodContent, implClass)); + Class answerClass = implClass.toClass(); + implClass.detach(); + Constructor constructor = answerClass.getConstructor(HazelcastInstance.class); + Object service = constructor.newInstance(hzInstance); + return service; + } + + protected CtConstructor makeContructorMethod( + ClassPool pool, CtClass implClass) throws Exception{ + CtConstructor constructor = new CtConstructor( + new CtClass[] { + pool.get(HazelcastInstance.class.getName()) + }, + implClass + ); + constructor.setModifiers(Modifier.PUBLIC); + constructor.setBody("super($1);"); + return constructor; + } + + protected String makeGetMapNameMethodContent(String mapName) { + return new EzyFunction(getMapNameMethod()) + .body() + .append(new EzyInstruction("\t", "\n") + .answer() + .string(mapName)) + .function() + .toString(); + } + + private String getMapName() { + return new EzySimpleMapNameFetcher().getMapName(clazz.getClazz()); + } + + protected EzyMethod getMapNameMethod() { + Method method = EzyMethods.getMethod(EzySimpleHazelcastMapService.class, "getMapName"); + return new EzyMethod(method); + } + + protected EzyClass getSuperClass() { + return new EzyClass(EzySimpleHazelcastMapService.class); + } + + protected String getImplClassName() { + return clazz.getName() + "$EzyHazelcastService$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyAbstractMapstore.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyAbstractMapstore.java new file mode 100644 index 00000000..dc3c30dd --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyAbstractMapstore.java @@ -0,0 +1,83 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.MapLoaderLifecycleSupport; +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyPostInit; + +public abstract class EzyAbstractMapstore + extends EzyLoggable + implements MapStore, MapLoaderLifecycleSupport, EzyPostInit { + + protected Properties properties; + protected HazelcastInstance hzInstance; + + @Override + public final void init( + HazelcastInstance hzInstance, Properties properties, String mapName) { + initComponents(hzInstance, properties, mapName); + config(hzInstance, properties, mapName); + } + + private final void initComponents( + HazelcastInstance hzInstance, Properties properties, String mapName) { + this.properties = properties; + this.hzInstance = hzInstance; + } + + protected void config( + HazelcastInstance hzInstance, Properties properties, String mapName) { + } + + @Override + public void postInit() { + } + + @Override + public void destroy() { + } + + @Override + public void delete(K key) { + } + + @Override + public Map loadAll(Collection keys) { + Map map = new HashMap<>(); + for (K key : keys) + map.put(key, load(key)); + return map; + } + + @Override + public Iterable loadAllKeys() { + return new HashSet<>(); + } + + @Override + public void storeAll(Map map) { + for (K key : map.keySet()) + store(key, map.get(key)); + } + + @Override + public void deleteAll(Collection keys) { + } + + @SuppressWarnings("unchecked") + protected final T getProperty(Object key) { + return (T) properties.get(key); + } + + protected final boolean containsProperty(Object key) { + return properties.containsKey(key); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoreCreator.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoreCreator.java new file mode 100644 index 00000000..af0798e4 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoreCreator.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.Properties; +import java.util.Set; + +import com.hazelcast.core.MapStore; + +public interface EzyMapstoreCreator { + + Set getMapNames(); + + @SuppressWarnings("rawtypes") + MapStore create(String mapName, Properties properties); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcher.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcher.java new file mode 100644 index 00000000..8c4aee59 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcher.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.Map; +import java.util.Set; + +public interface EzyMapstoresFetcher { + + Set getMapNames(); + + Object getMapstore(String mapName); + + Map getMapstores(); + + boolean containsMapstore(String mapName); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcherAware.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcherAware.java new file mode 100644 index 00000000..27318e70 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzyMapstoresFetcherAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +public interface EzyMapstoresFetcherAware { + + void setMapstoresFetcher(EzyMapstoresFetcher fetcher); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoreCreator.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoreCreator.java new file mode 100644 index 00000000..58dc1fc4 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoreCreator.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import java.util.Properties; +import java.util.Set; + +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +public class EzySimpleMapstoreCreator + extends EzyLoggable + implements EzyMapstoreCreator, EzyMapstoresFetcherAware { + + @Setter + protected EzyMapstoresFetcher mapstoresFetcher; + + @Override + public Set getMapNames() { + return mapstoresFetcher.getMapNames(); + } + + @SuppressWarnings("rawtypes") + @Override + public MapStore create(String mapName, Properties properties) { + if(mapstoresFetcher.containsMapstore(mapName)) + return (MapStore) mapstoresFetcher.getMapstore(mapName); + throw new IllegalArgumentException("has no mapstore with name = " + mapName); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoresFetcher.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoresFetcher.java new file mode 100644 index 00000000..4af9011b --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/mapstore/EzySimpleMapstoresFetcher.java @@ -0,0 +1,123 @@ +package com.tvd12.ezyfoxserver.hazelcast.mapstore; + +import static com.tvd12.ezyfoxserver.database.util.EzyMapstoreAnnotations.getMapName; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.common.base.Supplier; +import com.google.common.collect.Sets; +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.database.annotation.EzyMapstore; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleMapstoresFetcher + extends EzyLoggable + implements EzyMapstoresFetcher { + + protected Map mapstores = new ConcurrentHashMap<>(); + + protected EzySimpleMapstoresFetcher(Builder builder) { + this.mapstores.putAll(builder.mapstores); + } + + @Override + public Set getMapNames() { + return new HashSet<>(mapstores.keySet()); + } + + @Override + public Object getMapstore(String mapName) { + return mapstores.get(mapName); + } + + @Override + public Map getMapstores() { + return new HashMap<>(mapstores); + } + + @Override + public boolean containsMapstore(String mapName) { + return mapstores.containsKey(mapName); + } + + public static Builder builder() { + return new Builder(); + } + + @SuppressWarnings({"rawtypes"}) + public static class Builder + extends EzyLoggable + implements EzyBuilder { + + protected Map mapstores = new HashMap<>(); + protected Map> mapstoreClassMap = new HashMap<>(); + + public Builder scan(String packageName) { + Set> classes = getMapstoreClasses(packageName);; + classes.forEach(this::addMapstoreClass); + return this; + } + + public Builder scan(String... packageNames) { + return scan(Sets.newHashSet(packageNames)); + } + + public Builder scan(Iterable packageNames) { + packageNames.forEach(this::scan); + return this; + } + + public Builder addMapstoreClass(Class clazz) { + return addMapstoreClass(() -> getMapName(clazz), clazz); + } + + public Builder addMapstoreClass(String mapName, Class clazz) { + return addMapstoreClass(() -> mapName, clazz); + } + + public Builder addMapstore(MapStore mapstore) { + return addMapstore(getMapName(mapstore.getClass()), mapstore); + } + + public Builder addMapstore(String mapName, MapStore mapstore) { + this.mapstores.put(mapName, mapstore); + getLogger().debug("add mapstore {} of class {}", mapName, mapstore.getClass().getName()); + return this; + } + + @Override + public EzySimpleMapstoresFetcher build() { + for(String mapName : mapstoreClassMap.keySet()) { + Class clazz = mapstoreClassMap.get(mapName); + Object mapstore = newMapstore(clazz); + addMapstore(mapName, (MapStore) mapstore); + } + return new EzySimpleMapstoresFetcher(this); + } + + protected Object newMapstore(Class mapstoreClass) { + return EzyClasses.newInstance(mapstoreClass); + } + + private Set> getMapstoreClasses(String packageName) { + return EzyPackages.getAnnotatedClasses(packageName, EzyMapstore.class); + } + + private Builder addMapstoreClass(Supplier mapNameSupplier, Class clazz) { + if(MapStore.class.isAssignableFrom(clazz)) + this.mapstoreClassMap.put(mapNameSupplier.get(), clazz); + else + getLogger().warn("{} doesn't implements {}, ignore it", clazz, MapStore.class); + return this; + } + + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractHazelcastService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractHazelcastService.java new file mode 100644 index 00000000..97589fd7 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractHazelcastService.java @@ -0,0 +1,95 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.HazelcastInstanceAware; +import com.hazelcast.core.ILock; +import com.tvd12.ezyfoxserver.function.EzyExceptionVoid; +import com.tvd12.ezyfoxserver.function.EzySupplier; +import com.tvd12.ezyfoxserver.util.EzyInitable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzyAbstractHazelcastService + extends EzyLoggable + implements HazelcastInstanceAware, EzyInitable { + + protected HazelcastInstance hazelcastInstance; + + public EzyAbstractHazelcastService() { + } + + public EzyAbstractHazelcastService(HazelcastInstance hazelcastInstance) { + this.setHazelcastInstance(hazelcastInstance); + } + + @Override + public void init() { + } + + @Override + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + this.hazelcastInstance = hazelcastInstance; + } + + protected ILock getLock(String key) { + return hazelcastInstance.getLock(key); + } + + protected void lockUpdate(String key, EzyExceptionVoid applier) { + ILock lock = getLock(key); + lock.lock(); + try { + applier.apply(); + } + catch (Exception e) { + throw new IllegalStateException("lock to update with key " + key + " error", e); + } + finally { + lock.unlock(); + } + } + + protected T lockUpdateAndGet(String key, EzySupplier supplier) { + ILock lock = getLock(key); + lock.lock(); + try { + return supplier.get(); + } + catch (Exception e) { + throw new IllegalStateException("lock to update and get with key " + key + " error", e); + } + finally { + lock.unlock(); + } + } + + protected void lockUpdateWithException( + String key, EzyExceptionVoid applier) throws Exception { + ILock lock = getLock(key); + lock.lock(); + try { + applier.apply(); + } + catch (Exception e) { + throw e; + } + finally { + lock.unlock(); + } + } + + protected T lockUpdateAndGetWithException( + String key, EzySupplier supplier) throws Exception { + ILock lock = getLock(key); + lock.lock(); + try { + return supplier.get(); + } + catch (Exception e) { + throw e; + } + finally { + lock.unlock(); + } + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractMapService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractMapService.java new file mode 100644 index 00000000..5998e86a --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAbstractMapService.java @@ -0,0 +1,111 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import com.hazelcast.core.TransactionalMap; +import com.tvd12.ezyfoxserver.function.EzyExceptionApply; +import com.tvd12.ezyfoxserver.function.EzyExceptionFunction; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMapTransactionFactoryAware; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapApplyTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; + +import lombok.Setter; + +public abstract class EzyAbstractMapService + extends EzyAbstractHazelcastService + implements EzyMapTransactionFactoryAware { + + protected IMap map; + + @Setter + protected EzyMapTransactionFactory mapTransactionFactory; + + public EzyAbstractMapService() { + } + + public EzyAbstractMapService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + + @Override + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + super.setHazelcastInstance(hazelcastInstance); + this.map = hazelcastInstance.getMap(getMapName()); + } + + protected abstract String getMapName(); + + protected EzyMapApplyTransaction newApplyTransaction() { + return mapTransactionFactory.newApplyTransaction(getMapName()); + } + + protected EzyMapReturnTransaction newReturnTransaction() { + return mapTransactionFactory.newReturnTransaction(getMapName()); + } + + protected final void transactionUpdate( + EzyExceptionApply> applier) throws Exception { + EzyMapApplyTransaction transaction = newApplyTransaction(); + transaction.begin(); + try { + transaction.apply(applier); + transaction.commit(); + } + catch(Exception e) { + transaction.rollback(); + throw e; + } + } + + protected final void transactionUpdate( + K key, EzyExceptionApply applier, V defValue) throws Exception { + transactionUpdate(map -> transactionUpdate(map, key, applier, defValue)); + } + + protected final R transactionUpdateAndGet( + EzyExceptionFunction, R> applier) throws Exception { + EzyMapReturnTransaction transaction = newReturnTransaction(); + transaction.begin(); + try { + R answer = + transaction.apply(applier); + transaction.commit(); + return answer; + } + catch(Exception e) { + transaction.rollback(); + throw e; + } + } + + protected final R transactionUpdateAndGet( + K key, EzyExceptionFunction applier, V defValue) throws Exception { + return transactionUpdateAndGet(map -> transactionUpdateAndGet(map, key, applier, defValue)); + } + + private void transactionUpdate( + TransactionalMap map, K key, EzyExceptionApply applier, V defValue) throws Exception { + V value = map.getForUpdate(key); + if(value == null) + value = defValue; + if(value != null) { + applier.apply(value); + map.set(key, value); + } + } + + private R transactionUpdateAndGet( + TransactionalMap map, K key, EzyExceptionFunction applier, V defValue) throws Exception { + V value = map.getForUpdate(key); + if(value == null) + value = defValue; + R result = null; + if(value != null) { + result = applier.apply(value); + map.set(key, value); + } + return result; + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAccountService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAccountService.java new file mode 100644 index 00000000..8606827e --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyAccountService.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; + +public interface EzyAccountService { + + EzyAccount newAccount(String accountType); + + EzyAccount getAccount(long accoutId); + + Long update(long accountId, long value); + + Long[] update(long accountId, double percent, long initValue); + + Map getAccounts(Iterable keys); + + EzyAccount removeAccount(long accoutId); + + void removeAccounts(Iterable keys); + + default Long[] update(long accountId, double percent) { + return update(accountId, percent, 0L); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyHazelcastMapService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyHazelcastMapService.java new file mode 100644 index 00000000..8d77dd1f --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyHazelcastMapService.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.tvd12.ezyfoxserver.database.mapservice.EzyMapService; + +public interface EzyHazelcastMapService extends EzyMapService { + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdService.java new file mode 100644 index 00000000..fded74bd --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdService.java @@ -0,0 +1,16 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.service; + +/** + * @author tavandung12 + * + */ +public interface EzyMaxIdService { + + void loadAll(); + + Long incrementAndGet(String key); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdServiceAware.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdServiceAware.java new file mode 100644 index 00000000..f40a58f2 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzyMaxIdServiceAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +public interface EzyMaxIdServiceAware { + + void setMaxIdService(EzyMaxIdService maxIdService); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleAccountService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleAccountService.java new file mode 100644 index 00000000..76e12cad --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleAccountService.java @@ -0,0 +1,114 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import java.util.Map; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccountTypeAware; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyAccountFactory; + +import lombok.Setter; + +public class EzySimpleAccountService + extends EzySimpleHazelcastMapService + implements EzyAccountService, EzyMaxIdServiceAware { + + @Setter + protected EzyMaxIdService maxIdService; + @Setter + protected EzyAccountFactory accountFactory; + + public EzySimpleAccountService() { + } + + public EzySimpleAccountService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + + @Override + public EzyAccount newAccount(String accountType) { + EzyAccount account = createAccount(accountType); + map.set(account.getId(), account); + return account; + } + + @Override + public EzyAccount getAccount(long accoutId) { + return get(accoutId); + } + + @Override + public Map getAccounts(Iterable keys) { + return getMapByIds(keys); + } + + @Override + public EzyAccount removeAccount(long accoutId) { + return remove(accoutId); + } + + @Override + public void removeAccounts(Iterable keys) { + remove(keys); + } + + @Override + public Long update(long accountId, long offset) { + try { + return transactionUpdateAndGet( + accountId, + account -> updateAccount(account, offset), + null); + } + catch(Exception e) { + throw new IllegalArgumentException("cannot update accout id = " + accountId + ", with offset = " + offset, e); + } + } + + @Override + public Long[] update(long accountId, double percent, long initValue) { + try { + return transactionUpdateAndGet( + accountId, + account -> updateAccount(account, percent, initValue), + null); + } + catch(Exception e) { + throw new IllegalArgumentException("cannot update accout id = " + accountId + ", with percent = " + percent, e); + } + } + + private Long updateAccount(EzyAccount account, long offset) { + long updated = account.update(offset); + map.set(account.getId(), account); + return updated; + } + + private Long[] updateAccount(EzyAccount account, double percent, long initValue) { + Long[] updated = account.update(percent, initValue); + map.set(account.getId(), account); + return updated; + } + + private EzyAccount createAccount(String accountType) { + long accountId = newAccountId(); + EzyAccount account = accountFactory.newAccount(accountId); + ((EzyAccountTypeAware)account).setType(accountType); + return account; + } + + private long newAccountId() { + return maxIdService.incrementAndGet(getIdKeyName()); + } + + protected String getIdKeyName() { + return getMapName(); + } + + @Override + protected String getMapName() { + return EzyMapNames.ACCOUNT; + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleHazelcastMapService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleHazelcastMapService.java new file mode 100644 index 00000000..a6339cea --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleHazelcastMapService.java @@ -0,0 +1,151 @@ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.common.collect.Sets; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.query.EntryObject; +import com.hazelcast.query.Predicate; +import com.hazelcast.query.PredicateBuilder; +import com.tvd12.ezyfoxserver.database.entity.EzyHasIdEntity; + +public abstract class EzySimpleHazelcastMapService + extends EzyAbstractMapService + implements EzyHazelcastMapService { + + public EzySimpleHazelcastMapService() { + } + + public EzySimpleHazelcastMapService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + + @Override + public V get(K key) { + return map.get(key); + } + + @Override + public List getAllList() { + return new ArrayList<>(map.values()); + } + + @Override + public Map getAllMap() { + return new HashMap<>(map); + } + + @Override + public List getListByIds(Iterable keys) { + return new ArrayList<>(getMapByIds(keys).values()); + } + + @Override + public Map getMapByIds(Iterable keys) { + return map.getAll(Sets.newHashSet(keys)); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public void set(K key, V value) { + map.set(key, value); + } + + @Override + public void set(V value) { + map.set(getKey(value), value); + } + + @Override + public void set(Map map) { + put(map); + } + + @Override + public void set(Iterable values) { + put(values); + } + + @Override + public V put(K key, V value) { + return map.put(key, value); + } + + @Override + public V put(V value) { + return map.put(getKey(value), value); + } + + @Override + public void put(Map map) { + this.map.putAll(map); + } + + @Override + public void put(Iterable values) { + Map map = new HashMap<>(); + values.forEach(v -> map.put(getKey(v), v)); + put(map); + } + + @SuppressWarnings("unchecked") + private K getKey(V value) { + if(value instanceof EzyHasIdEntity) + return ((EzyHasIdEntity)value).getId(); + throw new IllegalArgumentException("value must implements 'EzyHasIdEntity' interface"); + } + + @Override + public V remove(K key) { + return map.remove(key); + } + + @Override + public void remove(Iterable keys) { + keys.forEach(this::remove); + } + + @Override + public void clear() { + map.clear(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public boolean containsKey(K key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(V value) { + return map.containsValue(value); + } + + @SuppressWarnings("rawtypes") + public List getListByField(String field, Comparable value) { + EntryObject e = getEntryObject(); + Predicate predicate = e.get(field).equal(value); + return getList(predicate); + } + + @SuppressWarnings("rawtypes") + protected List getList(Predicate predicate) { + return new ArrayList<>(map.values(predicate)); + } + + protected final EntryObject getEntryObject() { + return new PredicateBuilder().getEntryObject(); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleMaxIdService.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleMaxIdService.java new file mode 100644 index 00000000..e806d741 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/service/EzySimpleMaxIdService.java @@ -0,0 +1,60 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.hazelcast.service; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.TransactionalMap; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; + +/** + * @author tavandung12 + * + */ +public class EzySimpleMaxIdService + extends EzyAbstractMapService + implements EzyMaxIdService { + + public EzySimpleMaxIdService() { + } + + public EzySimpleMaxIdService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + + @Override + public void loadAll() { + map.loadAll(false); + } + + @Override + public Long incrementAndGet(String key) { + EzyMapReturnTransaction transaction = + newReturnTransaction(); + transaction.begin(); + try { + Long maxId = + transaction.apply(map -> incrementAndGetMaxId(map, key)); + transaction.commit(); + return maxId; + } + catch(Exception e) { + transaction.rollback(); + throw new IllegalStateException("cannot increment and get on key " + key, e); + } + } + + private Long incrementAndGetMaxId(TransactionalMap map, String key) { + Long current = map.getForUpdate(key); + Long maxId = current != null ? current + 1L : 1L; + map.set(key, maxId); + return maxId; + } + + @Override + protected String getMapName() { + return EzyMapNames.MAX_ID; + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyApplyTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyApplyTransaction.java new file mode 100644 index 00000000..3429fc33 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyApplyTransaction.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import com.tvd12.ezyfoxserver.function.EzyExceptionApply; + +public interface EzyApplyTransaction extends EzyTransaction { + + void apply(EzyExceptionApply func) throws Exception; + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapApplyTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapApplyTransaction.java new file mode 100644 index 00000000..2673dd6d --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapApplyTransaction.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import com.hazelcast.core.TransactionalMap; + +public interface EzyMapApplyTransaction + extends EzyApplyTransaction> { + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapReturnTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapReturnTransaction.java new file mode 100644 index 00000000..9419ced9 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyMapReturnTransaction.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import com.hazelcast.core.TransactionalMap; + +public interface EzyMapReturnTransaction + extends EzyReturnTransaction, R> { + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyReturnTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyReturnTransaction.java new file mode 100644 index 00000000..2b7c2d6d --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyReturnTransaction.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import com.tvd12.ezyfoxserver.function.EzyExceptionFunction; + +public interface EzyReturnTransaction extends EzyTransaction { + + R apply(EzyExceptionFunction func) throws Exception; + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzySimpleTransactionOptions.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzySimpleTransactionOptions.java new file mode 100644 index 00000000..25f6a421 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzySimpleTransactionOptions.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import java.util.concurrent.TimeUnit; + +import lombok.Getter; + +@Getter +public class EzySimpleTransactionOptions extends EzyTransactionOptions { + + protected long timeout = 60; + protected TimeUnit timeoutUnit = TimeUnit.SECONDS; + protected int durability = 1; + protected EzyTransactionType transactionType = EzyTransactionType.TWO_PHASE; + + public EzySimpleTransactionOptions timeout(long timeout, TimeUnit timeUnit) { + this.timeout = timeout; + this.timeoutUnit = timeUnit; + return this; + } + + public EzySimpleTransactionOptions durability(int durability) { + this.durability = durability; + return this; + } + + public EzySimpleTransactionOptions transactionType(EzyTransactionType type) { + this.transactionType = type; + return this; + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransaction.java new file mode 100644 index 00000000..c2c9c929 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransaction.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +public interface EzyTransaction { + + void begin(); + + void commit(); + + void rollback(); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionOptions.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionOptions.java new file mode 100644 index 00000000..5a8bf0ed --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionOptions.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import java.util.concurrent.TimeUnit; + +public abstract class EzyTransactionOptions { + + public static EzySimpleTransactionOptions newInstance() { + return new EzySimpleTransactionOptions(); + } + + public abstract long getTimeout(); + + public abstract TimeUnit getTimeoutUnit(); + + public abstract int getDurability(); + + public abstract EzyTransactionType getTransactionType(); + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionType.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionType.java new file mode 100644 index 00000000..9a865cae --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/EzyTransactionType.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyEnums; + +import lombok.Getter; + +public enum EzyTransactionType implements EzyConstant { + + TWO_PHASE(1), + ONE_PHASE(2); + + @Getter + private int id; + + private EzyTransactionType(int id) { + this.id = id; + } + + @Override + public String getName() { + return toString(); + } + + public static EzyTransactionType valueOf(int id) { + return EzyEnums.valueOf(values(), id); + } +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapApplyTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapApplyTransaction.java new file mode 100644 index 00000000..88dd0db1 --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapApplyTransaction.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction.impl; + +import com.hazelcast.core.TransactionalMap; +import com.hazelcast.transaction.TransactionContext; +import com.tvd12.ezyfoxserver.function.EzyExceptionApply; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapApplyTransaction; + +public class EzySimpleMapApplyTransaction + extends EzySimpleTransaction + implements EzyMapApplyTransaction { + + protected final String mapName; + + public EzySimpleMapApplyTransaction( + TransactionContext context, String mapName) { + super(context); + this.mapName = mapName; + } + + @Override + public void apply(EzyExceptionApply> func) throws Exception { + TransactionalMap map = context.getMap(mapName); + func.apply(map); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapReturnTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapReturnTransaction.java new file mode 100644 index 00000000..eb21ce3e --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleMapReturnTransaction.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction.impl; + +import com.hazelcast.core.TransactionalMap; +import com.hazelcast.transaction.TransactionContext; +import com.tvd12.ezyfoxserver.function.EzyExceptionFunction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; + +public class EzySimpleMapReturnTransaction + extends EzySimpleTransaction + implements EzyMapReturnTransaction { + + private final String mapName; + + public EzySimpleMapReturnTransaction( + TransactionContext context, String mapName) { + super(context); + this.mapName = mapName; + } + + @Override + public R apply(EzyExceptionFunction, R> func) throws Exception { + TransactionalMap map = context.getMap(mapName); + return func.apply(map); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleTransaction.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleTransaction.java new file mode 100644 index 00000000..565365fc --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/transaction/impl/EzySimpleTransaction.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.hazelcast.transaction.impl; + +import com.hazelcast.transaction.TransactionContext; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransaction; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleTransaction + extends EzyLoggable + implements EzyTransaction { + + protected final TransactionContext context; + + public EzySimpleTransaction(TransactionContext context) { + this.context = context; + } + + @Override + public void begin() { + context.beginTransaction(); + } + + @Override + public void commit() { + context.commitTransaction(); + } + + @Override + public void rollback() { + context.rollbackTransaction(); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyHazelcastConfigs.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyHazelcastConfigs.java new file mode 100644 index 00000000..24ac12cf --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyHazelcastConfigs.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.hazelcast.util; + +import java.io.InputStream; + +import com.hazelcast.config.Config; +import com.hazelcast.config.XmlConfigBuilder; +import com.tvd12.ezyfoxserver.stream.EzyAnywayInputStreamLoader; + +public final class EzyHazelcastConfigs { + + private EzyHazelcastConfigs() { + } + + public static Config newXmlConfigBuilder(String filePath) { + InputStream stream = EzyAnywayInputStreamLoader.builder() + .build() + .load(filePath); + return newXmlConfigBuilder(stream); + } + + public static Config newXmlConfigBuilder(InputStream stream) { + return new XmlConfigBuilder(stream).build(); + } + +} diff --git a/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyMapServiceAutoImplAnnotations.java b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyMapServiceAutoImplAnnotations.java new file mode 100644 index 00000000..9ab1316f --- /dev/null +++ b/ezyfox-server-hazelcast/src/main/java/com/tvd12/ezyfoxserver/hazelcast/util/EzyMapServiceAutoImplAnnotations.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.hazelcast.util; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; + +public final class EzyMapServiceAutoImplAnnotations { + + private EzyMapServiceAutoImplAnnotations() { + } + + public static String getBeanName(Class annotatedClass) { + EzyMapServiceAutoImpl anno = annotatedClass.getAnnotation(EzyMapServiceAutoImpl.class); + String beanName = anno.name().trim(); + return StringUtils.isEmpty(beanName) ? EzyClasses.getVariableName(annotatedClass) : beanName; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java new file mode 100644 index 00000000..5e2d4fe0 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/ExampleHazelcastCreator.java @@ -0,0 +1,89 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import java.util.HashSet; +import java.util.Set; + +import com.google.common.collect.Sets; +import com.hazelcast.config.Config; +import com.hazelcast.config.EvictionPolicy; +import com.hazelcast.config.MapStoreConfig.InitialLoadMode; +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.function.EzyCreation; +import com.tvd12.ezyfoxserver.hazelcast.EzyAbstractHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.EzySimpleHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.EzySimpleMapConfigsFetcher.Builder; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.util.EzyHazelcastConfigs; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +public class ExampleHazelcastCreator implements EzyCreation { + + private String filePath; + + public ExampleHazelcastCreator filePath(String filePath) { + this.filePath = filePath; + return this; + } + + @Override + public HazelcastInstance create() { + EzyAbstractHazelcastFactory factory = new EzySimpleHazelcastFactory() { + @Override + protected void applyMapConfigs(Builder builder) { + builder + .mapConfigApply("example_users", mc -> { + mc.setEvictionPolicy(EvictionPolicy.LFU); + mc.setMaxIdleSeconds(100); + }) + .mapConfigApplies(EzyMaps.newHashMap("example_users", mc -> { + mc.setEvictionPolicy(EvictionPolicy.LFU); + mc.setMaxIdleSeconds(100); + })); + } + + @Override + protected void applyMapstoreConfigs(Builder builder) { + super.applyMapstoreConfigs(builder); + builder.mapstoreConfigApplies(EzyMaps.newHashMap("example_users", mc -> { + mc.setInitialLoadMode(InitialLoadMode.EAGER); + })); + } + + @Override + protected Set normalMapNames() { + return Sets.newHashSet("a", "b", "c"); + } + + @Override + protected EzyMapstoreCreator newMapstoreCreator() { + return new EzySimpleMapstoreCreator() { + @Override + public Set getMapNames() { + Set set = new HashSet<>(); + set.addAll(super.getMapNames()); + set.add("a"); + set.add("b"); + set.add("c"); + return set; + } + }; + } + }; + factory.setMapstoresFetcher(newMapstoresFetcher()); + return factory.newHazelcast(newConfig()); + } + + private Config newConfig() { + return EzyHazelcastConfigs.newXmlConfigBuilder(filePath); + } + + private EzyMapstoresFetcher newMapstoresFetcher() { + return EzySimpleMapstoresFetcher.builder() + .scan("com.tvd12.ezyfoxserver.hazelcast.testing.mapstore") + .build(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractHazelcastFactoryTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractHazelcastFactoryTest.java new file mode 100644 index 00000000..9594670b --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractHazelcastFactoryTest.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import java.util.Properties; +import java.util.Set; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.hazelcast.config.Config; +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.hazelcast.EzyAbstractHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyAbstractMapstore; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.testing.mapstore.ExampleUserMapstore; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractHazelcastFactoryTest extends BaseTest { + + @Test + public void test() { + EzyAbstractHazelcastFactory factory = new EzyAbstractHazelcastFactory() { + @Override + protected EzyMapstoreCreator newMapstoreCreator() { + return new EzyMapstoreCreator() { + + @Override + public Set getMapNames() { + return Sets.newHashSet("example_users", EzyMapNames.MAX_ID); + } + + @SuppressWarnings("rawtypes") + @Override + public MapStore create(String mapName, Properties properties) { + if(mapName.equals("example_users")) + return new ExampleUserMapstore(); + return new EzyAbstractMapstore() { + + @Override + public void store(Object key, Object value) { + } + + @Override + public Object load(Object key) { + return null; + } + + }; + } + }; + } + }; + factory.newHazelcast(new Config()); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractMapstoreFactoryTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractMapstoreFactoryTest.java new file mode 100644 index 00000000..45e96338 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyAbstractMapstoreFactoryTest.java @@ -0,0 +1,59 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import java.util.Collection; +import java.util.Map; +import java.util.Properties; + +import org.testng.annotations.Test; + +import com.hazelcast.core.MapStore; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyAbstractMapstoreFactory; + +public class EzyAbstractMapstoreFactoryTest { + + @Test + public void test() { + EzyAbstractMapstoreFactory factory = new EzyAbstractMapstoreFactory() { + + @Override + protected Object newMapstore(String mapName, Properties properties) { + return new MapStore() { + + @Override + public String load(String key) { + return null; + } + + @Override + public Map loadAll(Collection keys) { + return null; + } + + @Override + public Iterable loadAllKeys() { + return null; + } + + @Override + public void store(String key, String value) { + } + + @Override + public void storeAll(Map map) { + } + + @Override + public void delete(String key) { + } + + @Override + public void deleteAll(Collection keys) { + } + + }; + } + }; + factory.newMapStore("map", new Properties()); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyMapNamesTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyMapNamesTest.java new file mode 100644 index 00000000..982bb115 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzyMapNamesTest.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import com.tvd12.ezyfoxserver.hazelcast.constant.EzyMapNames; +import com.tvd12.test.base.BaseTest; + +public class EzyMapNamesTest extends BaseTest { + + public java.lang.Class getTestClass() { + return EzyMapNames.class; + }; + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleAccountTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleAccountTest.java new file mode 100644 index 00000000..df737934 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleAccountTest.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import java.util.Date; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; +import lombok.Setter; + +public class EzySimpleAccountTest extends BaseTest { + + @Test + public void test() { + EzyAbstractAccount account = new EzyAbstractAccount() { + private static final long serialVersionUID = -1100249149170475581L; + + @Setter + @Getter + private Long id; + + }; + account.setId(10L); + account.setValue(100L); + account.setType("MONEY"); + Date now = new Date(); + account.setCreationDate(now); + account.setLastUpdatedDate(now); + assert account.getType().equals("MONEY"); + assert account.getCreationDate().equals(now); + assert account.getLastUpdatedDate().equals(now); + assert account.getId() == 10L; + assert account.getValue() == 100L; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleConfigCustomizerTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleConfigCustomizerTest.java new file mode 100644 index 00000000..86fc88a7 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleConfigCustomizerTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import org.testng.annotations.Test; + +import com.hazelcast.config.Config; +import com.tvd12.ezyfoxserver.hazelcast.EzySimpleConfigCustomizer; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleConfigCustomizerTest extends BaseTest { + + @Test + public void test() { + new EzySimpleConfigCustomizer().customize(new Config()); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleHazelcastFactoryTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleHazelcastFactoryTest.java new file mode 100644 index 00000000..8d62c292 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleHazelcastFactoryTest.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import org.testng.annotations.Test; + +import com.hazelcast.config.Config; +import com.tvd12.ezyfoxserver.hazelcast.EzyAbstractHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.EzySimpleHazelcastFactory; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoresFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleHazelcastFactoryTest extends BaseTest { + + @Test + public void test() { + EzyAbstractHazelcastFactory factory = new EzySimpleHazelcastFactory(); + factory.setMapstoresFetcher(newMapstoresFetcher()); + factory.newHazelcast(new Config()); + } + + private EzyMapstoresFetcher newMapstoresFetcher() { + return EzySimpleMapstoresFetcher.builder() + .scan("com.tvd12.ezyfoxserver.hazelcast.testing.mapstore") + .build(); + } +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapConfigsFetcherTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapConfigsFetcherTest.java new file mode 100644 index 00000000..26438a54 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapConfigsFetcherTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.hazelcast.EzySimpleMapConfigsFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleMapConfigsFetcherTest extends BaseTest { + + @Test + public void test() { + EzySimpleMapConfigsFetcher fetcher = EzySimpleMapConfigsFetcher.builder() + .mapNames(Sets.newHashSet("a", "b", "c")) + .build(); + fetcher.get(); + } + + + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapNameFetcherTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapNameFetcherTest.java new file mode 100644 index 00000000..0ca84461 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleMapNameFetcherTest.java @@ -0,0 +1,54 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.hazelcast.impl.EzySimpleMapNameFetcher; + +public class EzySimpleMapNameFetcherTest { + + @Test + public void test1() { + try { + new EzySimpleMapNameFetcher().getMapName(Object.class); + } + catch(Exception e) { + System.err.println(e.getMessage()); + } + } + + @Test + public void test2() { + try { + new EzySimpleMapNameFetcher().getMapName(InterfaceA.class); + } + catch(Exception e) { + System.err.println(e.getMessage()); + } + } + + @Test + public void test3() { + try { + new EzySimpleMapNameFetcher().getMapName(InterfaceB.class); + } + catch(Exception e) { + System.err.println(e.getMessage()); + } + } + + @EzyAutoImpl(properties = { + }) + public static interface InterfaceA { + + } + + @EzyAutoImpl(properties = { + @EzyKeyValue(key = "key", value = "value") + }) + public static interface InterfaceB { + + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleServiceImplementorTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleServiceImplementorTest.java new file mode 100644 index 00000000..fb5e73dc --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/EzySimpleServiceImplementorTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.impl.EzySimpleServiceImplementor; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class EzySimpleServiceImplementorTest extends HazelcastBaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzySimpleServiceImplementor implementor = + new EzySimpleServiceImplementor(new EzyClass(ClassA.class)); + implementor.implement(HZ_INSTANCE); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test2() { + EzySimpleServiceImplementor implementor = + new EzySimpleServiceImplementor(new EzyClass(InterfaceA.class)); + implementor.implement(null); + } + + @EzyMapServiceAutoImpl("a") + public static class ClassA { + + } + + @EzyMapServiceAutoImpl("a") + public static interface InterfaceA { + + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java new file mode 100644 index 00000000..028e4489 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/HazelcastBaseTest.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzySimpleMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleMaxIdService; +import com.tvd12.test.base.BaseTest; + +public abstract class HazelcastBaseTest extends BaseTest { + + protected static final HazelcastInstance HZ_INSTANCE; + protected static final EzyMaxIdService MAX_ID_SERVICE; + protected static final EzyMapTransactionFactory MAP_TRANSACTION_FACTORY; + + static { + HZ_INSTANCE = newHzInstance(); + MAP_TRANSACTION_FACTORY = newMapTransactionFactory(); + MAX_ID_SERVICE = newMaxIdService(); + } + + private static HazelcastInstance newHzInstance() { + return new ExampleHazelcastCreator() + .filePath("hazelcast.xml") + .create(); + } + + private static EzyMaxIdService newMaxIdService() { + EzySimpleMaxIdService service = new EzySimpleMaxIdService(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + return service; + } + + private static EzyMapTransactionFactory newMapTransactionFactory() { + return new EzySimpleMapTransactionFactory(HZ_INSTANCE); + } + + protected Logger getLogger() { + return LoggerFactory.getLogger(getClass()); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/Person.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/Person.java new file mode 100644 index 00000000..b4de1cb8 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/Person.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing; + +import java.io.Serializable; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class Person implements Serializable { + private static final long serialVersionUID = -6731210894904620373L; + + private String name; + private int age; + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java new file mode 100644 index 00000000..23039a6a --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/ExampleUser.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.entity; + +import java.io.Serializable; + +import com.tvd12.ezyfoxserver.database.entity.EzyHasIdEntity; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class ExampleUser implements EzyHasIdEntity, Serializable { + private static final long serialVersionUID = 975411654175906424L; + + private String username; + + @Override + public String getId() { + return username; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyAbstractAccountTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyAbstractAccountTest.java new file mode 100644 index 00000000..1ea927f3 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/entity/EzyAbstractAccountTest.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.entity; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyNegativeValueException; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; +import com.tvd12.test.base.BaseTest; + +public class EzyAbstractAccountTest extends BaseTest { + + @Test + public void test1() { + MyAccount account = new MyAccount(); + account.setAcceptNegativeValue(true); + account.update(100); + } + + @Test + public void test2() { + MyAccount account = new MyAccount(); + account.setAcceptNegativeValue(true); + account.update(-100); + } + + @Test + public void test3() { + MyAccount account = new MyAccount(); + account.setValue(100L); + account.setAcceptNegativeValue(true); + Long[] update = account.update(-0.5D, 200L); + assertEquals(update, new long[] {-50L, 250L, 100}); + } + + @Test + public void test4() { + MyAccount account = new MyAccount(); + account.setValue(100L); + account.setAcceptNegativeValue(true); + assert account.isAcceptNegativeValue(); + Long[] update = account.update(-1.5D, 0L); + assertEquals(update, new long[] {-150L, -50, 100}); + } + + @Test(expectedExceptions = {EzyNegativeValueException.class}) + public void test5() { + MyAccount account = new MyAccount(); + account.setValue(100L); + Long[] update = account.update(-1.5D, 0L); + assertEquals(update, new long[] {-150L, -50, 100}); + } + + public static class MyAccount extends EzyAbstractAccount { + private static final long serialVersionUID = -640884788284000277L; + + @Override + public Long getId() { + return 1L; + } + + @Override + public void setId(Long id) { + } + + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java new file mode 100644 index 00000000..a3d09c0a --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/ExampleUserMapstore.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.database.annotation.EzyMapstore; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyAbstractMapstore; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +@EzyMapstore("example_users") +public class ExampleUserMapstore extends EzyAbstractMapstore { + + private static final Map MAP = + EzyMaps.newHashMap("dungtv", new ExampleUser("dungtv")); + + @Override + public void store(String key, ExampleUser value) { + MAP.put(key, value); + } + + @Override + public ExampleUser load(String key) { + return MAP.get(key); + } + + + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzySimpleMapstoreCreatorTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzySimpleMapstoreCreatorTest.java new file mode 100644 index 00000000..01d659e4 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/mapstore/EzySimpleMapstoreCreatorTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.mapstore; + +import java.util.Properties; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoreCreator; +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoresFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleMapstoreCreatorTest extends BaseTest { + + @Test + public void test() { + EzyMapstoresFetcher fetcher = newMapstoresFetcher(); + EzySimpleMapstoreCreator creator = new EzySimpleMapstoreCreator(); + creator.setMapstoresFetcher(fetcher); + try { + creator.create("no", new Properties()); + } + catch(Exception e) { + } + } + + private EzyMapstoresFetcher newMapstoresFetcher() { + return EzySimpleMapstoresFetcher.builder() + .scan("com.tvd12.ezyfoxserver.hazelcast.testing.mapstore") + .build(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountService2Test.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountService2Test.java new file mode 100644 index 00000000..894e7ede --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountService2Test.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.impl.TestAccountService; + +public class AccountService2Test extends HazelcastBaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + TestAccountService service = new TestAccountService(); + service.setHazelcastInstance(HZ_INSTANCE); + service.setMaxIdService(MAX_ID_SERVICE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.setAccountFactory(new TestAccountFactory()); + EzyAccount account = service.newAccount("MONEY"); + service.update(account.getId(), 100); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + TestAccountService service = new TestAccountService(HZ_INSTANCE); + service.setMaxIdService(MAX_ID_SERVICE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.setAccountFactory(new TestAccountFactory()); + EzyAccount account = service.newAccount("MONEY"); + service.update(account.getId(), 0.5D); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountServiceTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountServiceTest.java new file mode 100644 index 00000000..f7cbfa3d --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/AccountServiceTest.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAccount; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyAbstractAccoutFactory; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.impl.TestAccountService; + +public class AccountServiceTest extends HazelcastBaseTest { + + @Test + public void test() { + TestAccountService service = new TestAccountService(HZ_INSTANCE); + service.setMaxIdService(MAX_ID_SERVICE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.setAccountFactory(new EzyAbstractAccoutFactory() { + @Override + protected EzyAbstractAccount newAccount() { + return new TestAcount(); + } + }); + EzyAccount account = service.newAccount("MONEY"); + assert account.getValue() == 0; + assert service.update(account.getId(), 100) == 100L; + assertEquals(service.update(account.getId(), -0.3D), new Long[] {-30L, 70L, 100L}); + assert service.getAccount(account.getId()).getValue() == 70L; + EzyAccount account2 = service.newAccount("MONEY"); + assert service.getAccounts(Sets.newHashSet(account.getId(), account2.getId())).size() == 2; + EzyAccount account2r = service.removeAccount(account2.getId()); + assert account2.equals(account2r); + assert account2.hashCode() == account2r.hashCode(); + service.removeAccounts(Sets.newHashSet(account.getId(), account2.getId())); + assert service.getAccount(account.getId()) == null; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Chicken.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Chicken.java new file mode 100644 index 00000000..da257c67 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Chicken.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@AllArgsConstructor +public class Chicken implements Serializable { + private static final long serialVersionUID = 8171070638249273626L; + + private String name; + private int age; + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ChickenMapService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ChickenMapService.java new file mode 100644 index 00000000..d300cf11 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ChickenMapService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; + +public interface ChickenMapService extends EzyHazelcastMapService { +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Dog.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Dog.java new file mode 100644 index 00000000..3ad0a623 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Dog.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class Dog implements Serializable { + private static final long serialVersionUID = -868330127693127237L; + + private String name; + private int age; + + public void exception() { + throw new RuntimeException(); + } + + public long exception2() { + throw new RuntimeException(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogService.java new file mode 100644 index 00000000..09a1f6a6 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogService.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +public interface DogService { + + void updateAge(String name); + + void updateAge2(String name); + + long updateAge3(String name); + + void throwException(String name); + + void throwException2(String name); +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogServiceTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogServiceTest.java new file mode 100644 index 00000000..b4b54a7e --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/DogServiceTest.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.impl.DogServiceImpl; + +public class DogServiceTest extends HazelcastBaseTest { + + @Test + public void test1() { + DogServiceImpl service = new DogServiceImpl(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.updateAge("hehe"); + } + + @Test + public void test2() { + DogServiceImpl service = new DogServiceImpl(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.updateAge2("hoho"); + } + + @Test + public void test3() { + DogServiceImpl service = new DogServiceImpl(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.updateAge3("hoho"); + } + + @Test + public void test4() { + DogServiceImpl service = new DogServiceImpl(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.throwException("hehe"); + } + + @Test + public void test5() { + DogServiceImpl service = new DogServiceImpl(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.throwException2("hehe"); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserMapstoreTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserMapstoreTest.java new file mode 100644 index 00000000..fac0c567 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserMapstoreTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.lang.reflect.Method; +import java.util.Properties; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzyAbstractMapstore; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; +import com.tvd12.ezyfoxserver.hazelcast.testing.mapstore.ExampleUserMapstore; +import com.tvd12.ezyfoxserver.io.EzyMaps; + +public class ExampleUserMapstoreTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + ExampleUserMapstore mapstore = new ExampleUserMapstore(); + Properties properties = new Properties(); + properties.put("hello", "world"); + mapstore.init(HZ_INSTANCE, properties, "example_users"); + mapstore.storeAll(EzyMaps.newHashMap("dungtv1", new ExampleUser("dungtv1"))); + mapstore.delete("dungtv"); + mapstore.destroy(); + + Method getProperty = EzyAbstractMapstore.class.getDeclaredMethod("getProperty", Object.class); + getProperty.setAccessible(true); + Method containsProperty = EzyAbstractMapstore.class.getDeclaredMethod("containsProperty", Object.class); + containsProperty.setAccessible(true); + + assert getProperty.invoke(mapstore, "hello") != null; + assert containsProperty.invoke(mapstore, "hello").equals(Boolean.TRUE); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserService.java new file mode 100644 index 00000000..6728a57e --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserService.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; + +public interface ExampleUserService { + + void saveUser(ExampleUser user); + + void saveUser(List users); + + ExampleUser getUser(String username); + + Map getUsers(Set usernames); + + void deleteUser(String username); + + void deleteAllUser(); + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserServiceTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserServiceTest.java new file mode 100644 index 00000000..6f8adbcf --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/ExampleUserServiceTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.impl.ExampleUserServiceImpl; + +public class ExampleUserServiceTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + ExampleUserServiceImpl service = new ExampleUserServiceImpl(); + service.setHazelcastInstance(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + assert service.get("dungtv") != null; + assert service.get("abc") == null; + assert service.getMapByIds(Sets.newHashSet("dungtv", "abc")).size() == 1; + + service.saveUser(new ExampleUser("dungtv1")); + service.saveUser(Lists.newArrayList(new ExampleUser("dungtv1"), new ExampleUser("dungtv2"))); + + service.deleteUser("dungtv1"); + service.clear(); + Thread.sleep(3000L); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyAbstractHazelcastServiceTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyAbstractHazelcastServiceTest.java new file mode 100644 index 00000000..a1779829 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzyAbstractHazelcastServiceTest.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.service.EzyAbstractHazelcastService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class EzyAbstractHazelcastServiceTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + MyService service = new MyService() {}; + service.setHazelcastInstance(HZ_INSTANCE); + service.init(); + service.one(); + service.two(); + service.three(); + service.four(); + service.five(); + } + + public static class MyService extends EzyAbstractHazelcastService { + + public void one() throws Exception { + lockUpdate("1", () -> {}); + lockUpdateAndGet("2", () -> 1L); + lockUpdateWithException("3", () -> {}); + lockUpdateAndGetWithException("4", () -> 1L); + } + + public void two() { + try { + lockUpdate("1", () -> {throw new Exception();}); + } + catch(Exception e) { + } + } + + public void three() { + try { + lockUpdateAndGet("1", () -> {throw new Exception();}); + } + catch(Exception e) { + } + } + + public void four() { + try { + lockUpdateWithException("1", () -> {throw new Exception();}); + } + catch(Exception e) { + } + } + + public void five() { + try { + lockUpdateAndGetWithException("1", () -> {throw new Exception();}); + } + catch(Exception e) { + } + } + + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMapstoresFetcherTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMapstoresFetcherTest.java new file mode 100644 index 00000000..4b600ca5 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMapstoresFetcherTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.mapstore.EzySimpleMapstoresFetcher; +import com.tvd12.ezyfoxserver.hazelcast.testing.mapstore.ExampleUserMapstore; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleMapstoresFetcherTest extends BaseTest { + + @Test + public void test() { + EzySimpleMapstoresFetcher fetcher = EzySimpleMapstoresFetcher.builder() + .scan("com.tvd12.ezyfoxserver.hazelcast.testing.mapstore", "com.tvd12.ezyfoxserver.hazelcast.testing.mapstore") + .addMapstoreClass(Class.class) + .addMapstoreClass("hello", Class.class) + .addMapstoreClass("example_users", ExampleUserMapstore.class) + .addMapstore(new ExampleUserMapstore()) + .addMapstore("example_users", new ExampleUserMapstore()) + .build(); + assert fetcher.getMapstores().size() == 1; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMaxIdServiceTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMaxIdServiceTest.java new file mode 100644 index 00000000..3a062bea --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/EzySimpleMaxIdServiceTest.java @@ -0,0 +1,99 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import org.testng.annotations.Test; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import com.hazelcast.core.TransactionalMap; +import com.tvd12.ezyfoxserver.function.EzyExceptionFunction; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyMapTransactionFactory; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleMaxIdService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapApplyTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyMapReturnTransaction; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionOptions; + +public class EzySimpleMaxIdServiceTest extends HazelcastBaseTest { + + @Test + public void test() throws Exception { + final EzySimpleMaxIdService service = new EzySimpleMaxIdService(HZ_INSTANCE); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + + List nums = new ArrayList<>(); + Thread[] threads = new Thread[1000]; + for(int i = 0 ; i < threads.length ; i++) { + threads[i] = new Thread(() -> { + nums.add(service.incrementAndGet("something")); + }); + } + for(int i = 0 ; i < threads.length ; i++) { + threads[i].start(); + threads[i].join(); + } + + System.out.println(nums); + for(int i = 0 ; i < nums.size() - 1 ; i++) { + if(nums.get(i + 1) != nums.get(i) + 1) { + System.err.println("error in " + i); + } + } + + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test2() { + EzySimpleMaxIdService service = new EzySimpleMaxIdService(); + service.setHazelcastInstance(HZ_INSTANCE); + service.setMapTransactionFactory(new EzyMapTransactionFactory() { + + @Override + public EzyMapReturnTransaction newReturnTransaction(String mapName, + EzyTransactionOptions options) { + return new EzyMapReturnTransaction() { + @Override + public R apply(EzyExceptionFunction, R> func) throws Exception { + throw new RuntimeException(); + } + + @Override + public void begin() { + } + + @Override + public void commit() { + } + + @Override + public void rollback() { + } + }; + } + + @Override + public EzyMapApplyTransaction newApplyTransaction(String mapName, EzyTransactionOptions options) { + return null; + } + }); + service.incrementAndGet("d"); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void test3() { + IMap map = mock(IMap.class); + HazelcastInstance hzInstance = mock(HazelcastInstance.class); + when(hzInstance.getMap(anyString())).thenReturn(map); + EzySimpleMaxIdService service = new EzySimpleMaxIdService(hzInstance); + service.setMapTransactionFactory(MAP_TRANSACTION_FACTORY); + service.loadAll(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Monkey.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Monkey.java new file mode 100644 index 00000000..c68f4e2b --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Monkey.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.io.Serializable; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@AllArgsConstructor +public class Monkey implements Serializable { + private static final long serialVersionUID = 8171070638249273626L; + + private String name; + private int age; + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService.java new file mode 100644 index 00000000..8bf861fd --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; + +@EzyMapServiceAutoImpl("monkey") +public interface MonkeyMapService extends EzyHazelcastMapService { +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService1.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService1.java new file mode 100644 index 00000000..93dcf21e --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService1.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; + +@EzyMapServiceAutoImpl("monkey") +interface MonkeyMapService1 extends EzyHazelcastMapService { +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService2.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService2.java new file mode 100644 index 00000000..a63332db --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/MonkeyMapService2.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; + +@EzyMapServiceAutoImpl("monkey") +public abstract class MonkeyMapService2 implements EzyHazelcastMapService { +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Person.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Person.java new file mode 100644 index 00000000..1e136a13 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Person.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.io.Serializable; + +import com.tvd12.ezyfoxserver.database.entity.EzyHasIdEntity; + +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +@EqualsAndHashCode(of = "name") +public class Person implements EzyHasIdEntity, Serializable { + private static final long serialVersionUID = -3967779291148509736L; + + private String name; + private int age; + + @Override + public String getId() { + return name; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/PersonMapService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/PersonMapService.java new file mode 100644 index 00000000..615d36f7 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/PersonMapService.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.hazelcast.service.EzyHazelcastMapService; + +@EzyAutoImpl(properties = { + @EzyKeyValue(key = "map.name", value = "person") +}) +public interface PersonMapService extends EzyHazelcastMapService { +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAccountFactory.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAccountFactory.java new file mode 100644 index 00000000..08e5e03b --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAccountFactory.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; +import com.tvd12.ezyfoxserver.hazelcast.factory.EzyAbstractAccoutFactory; + +public class TestAccountFactory extends EzyAbstractAccoutFactory { + + @Override + protected EzyAbstractAccount newAccount() { + return new TestAcount2(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount.java new file mode 100644 index 00000000..a6cfaa4c --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class TestAcount extends EzyAbstractAccount { + private static final long serialVersionUID = 2935749419090105L; + + private Long id; + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount2.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount2.java new file mode 100644 index 00000000..13cacd62 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TestAcount2.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import com.tvd12.ezyfoxserver.hazelcast.entity.EzyAbstractAccount; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class TestAcount2 extends EzyAbstractAccount { + private static final long serialVersionUID = 2935749419090105L; + + private Long id; + + @Override + public Long[] update(double percent, long initValue) { + throw new RuntimeException(); + } + + @Override + public Long update(long value) { + throw new RuntimeException(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Try2Test.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Try2Test.java new file mode 100644 index 00000000..8d70c0e3 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/Try2Test.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.bean.EzyServicesImplementor; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; + +public class Try2Test extends HazelcastBaseTest { + + @Test + public void test1() { + EzyServicesImplementor implementor = EzyServicesImplementor.newInstance() + .scan(new String[] {"com.tvd12.ezyfoxserver.hazelcast.testing.service"}) + .serviceInterface("chicken", ChickenMapService.class); + Map, Object> map = implementor.implement(HZ_INSTANCE); + MonkeyMapService service = (MonkeyMapService) map.get(MonkeyMapService.class); + service.put("dung", new Monkey("dung", 25)); + Monkey monkey = service.get("dung"); + assert monkey.getAge() == 25; + ChickenMapService chickenMapService = (ChickenMapService)map.get(ChickenMapService.class); + chickenMapService.put("chicken", new Chicken("chicken", 10)); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyServicesImplementor implementor = EzyServicesImplementor.newInstance() + .scan(new String[] {"com.tvd12.ezyfoxserver.hazelcast.testing.service"}); + Map, Object> map = implementor.implement(HZ_INSTANCE); + MonkeyMapService service = (MonkeyMapService) map.get(MonkeyMapService.class); + service.put(new Monkey("dung", 25)); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TryTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TryTest.java new file mode 100644 index 00000000..649960ec --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/TryTest.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.hazelcast.impl.EzySimpleServiceImplementor; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleHazelcastMapService; +import com.tvd12.ezyfoxserver.hazelcast.testing.HazelcastBaseTest; +import com.tvd12.ezyfoxserver.reflect.EzyClass; + +public class TryTest extends HazelcastBaseTest { + + @SuppressWarnings("unchecked") + @Test + public void test() { + EzySimpleServiceImplementor implementor = + new EzySimpleServiceImplementor(new EzyClass(PersonMapService.class)); + PersonMapService service = (PersonMapService)implementor.implement(HZ_INSTANCE); + service.clear(); + assert service.isEmpty(); + service.put(new Person("dung", 25)); + Person person = service.get("dung"); + assert person.getAge() == 25; + service.put(new Person("duong", 26)); + assert service.getAllList().size() == 2; + assert service.getAllMap().size() == 2; + assert service.getListByIds(Sets.newHashSet("dung", "duong")).size() == 2; + assert service.getMapByIds(Sets.newHashSet("dung", "duong")).size() == 2; + service.set(new Person("dat", 27)); + service.set("son", new Person("son", 28)); + assert service.size() == 4; + service.remove(Sets.newHashSet("dat", "son")); + assert service.size() == 2; + assert service.containsKey("dung"); + assert !service.containsKey("son"); + assert service.containsValue(person); + assert !service.containsValue(new Person("not found", 1)); + service.put("hung", new Person("hung", 32)); + assert !service.isEmpty(); + EzySimpleHazelcastMapService ab = (EzySimpleHazelcastMapService)service; + assert ab.getListByField("name", "dung").size() == 1; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/DogServiceImpl.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/DogServiceImpl.java new file mode 100644 index 00000000..c108be12 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/DogServiceImpl.java @@ -0,0 +1,62 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service.impl; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleHazelcastMapService; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.Dog; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.DogService; + +public class DogServiceImpl + extends EzySimpleHazelcastMapService + implements DogService { + + public DogServiceImpl(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + + @Override + public void updateAge(String name) { + try { + transactionUpdate(name, dog -> dog.setAge(100), new Dog()); + } catch (Exception e) { + } + } + + @Override + public void updateAge2(String name) { + try { + transactionUpdate(name, dog -> dog.setAge(100), null); + } catch (Exception e) { + } + } + + @Override + public long updateAge3(String name) { + try { + return transactionUpdateAndGet(name, dog -> (long)dog.getAge(), null); + } catch (Exception e) { + return 0; + } + } + + @Override + public void throwException(String name) { + try { + transactionUpdate(name, dog -> dog.exception(), new Dog()); + } catch (Exception e) { + } + } + + @Override + public void throwException2(String name) { + try { + transactionUpdateAndGet(name, dog -> dog.exception2(), new Dog()); + } catch (Exception e) { + } + } + + @Override + protected String getMapName() { + return "dog"; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/ExampleUserServiceImpl.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/ExampleUserServiceImpl.java new file mode 100644 index 00000000..575f5dd7 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/ExampleUserServiceImpl.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleHazelcastMapService; +import com.tvd12.ezyfoxserver.hazelcast.testing.entity.ExampleUser; +import com.tvd12.ezyfoxserver.hazelcast.testing.service.ExampleUserService; + +public class ExampleUserServiceImpl + extends EzySimpleHazelcastMapService + implements ExampleUserService { + + @Override + public void saveUser(ExampleUser user) { + map.set(user.getUsername(), user); + } + + @Override + public void saveUser(List users) { + set(users); + set(new HashMap<>()); + } + + @Override + public ExampleUser getUser(String username) { + return map.get(username); + } + + @Override + protected String getMapName() { + return "example_users"; + } + + @Override + public Map getUsers(Set usernames) { + return getMapByIds(usernames); + } + + @Override + public void deleteUser(String username) { + remove(username); + } + + @Override + public void deleteAllUser() { + clear(); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/TestAccountService.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/TestAccountService.java new file mode 100644 index 00000000..8c614960 --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/service/impl/TestAccountService.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.service.impl; + +import com.hazelcast.core.HazelcastInstance; +import com.tvd12.ezyfoxserver.hazelcast.service.EzySimpleAccountService; + +public class TestAccountService extends EzySimpleAccountService { + + public TestAccountService() { + super(); + } + + public TestAccountService(HazelcastInstance hazelcastInstance) { + super(hazelcastInstance); + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzySimpleTransactionOptionsTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzySimpleTransactionOptionsTest.java new file mode 100644 index 00000000..83baa8cf --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzySimpleTransactionOptionsTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.transaction; + +import java.util.concurrent.TimeUnit; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionOptions; +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionType; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleTransactionOptionsTest extends BaseTest { + + @Test + public void test() { + EzyTransactionOptions options = EzyTransactionOptions.newInstance() + .timeout(1000L, TimeUnit.MILLISECONDS) + .durability(2) + .transactionType(EzyTransactionType.ONE_PHASE); + assert options.getTimeout() == 1000L; + assert options.getTimeoutUnit() == TimeUnit.MILLISECONDS; + assert options.getDurability() == 2; + assert options.getTransactionType() == EzyTransactionType.ONE_PHASE; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzyTransactionTypeTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzyTransactionTypeTest.java new file mode 100644 index 00000000..2fce6e8f --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/transaction/EzyTransactionTypeTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.transaction; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.transaction.EzyTransactionType; +import com.tvd12.test.base.BaseTest; + +public class EzyTransactionTypeTest extends BaseTest { + + @Test + public void test() { + assert EzyTransactionType.TWO_PHASE.getId() == 1; + assert EzyTransactionType.TWO_PHASE.getName().equals("TWO_PHASE"); + assert EzyTransactionType.valueOf(1) == EzyTransactionType.TWO_PHASE; + EzyTransactionType.values(); + assert EzyTransactionType.valueOf("TWO_PHASE") == EzyTransactionType.TWO_PHASE; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyHazelcastConfigsTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyHazelcastConfigsTest.java new file mode 100644 index 00000000..da8fa4dc --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyHazelcastConfigsTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.util; + +import com.tvd12.ezyfoxserver.hazelcast.util.EzyHazelcastConfigs; +import com.tvd12.test.base.BaseTest; + +public class EzyHazelcastConfigsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyHazelcastConfigs.class; + } + +} diff --git a/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyMapServiceAutoImplAnnotationsTest.java b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyMapServiceAutoImplAnnotationsTest.java new file mode 100644 index 00000000..5a89117b --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/java/com/tvd12/ezyfoxserver/hazelcast/testing/util/EzyMapServiceAutoImplAnnotationsTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.hazelcast.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.hazelcast.annotation.EzyMapServiceAutoImpl; +import com.tvd12.ezyfoxserver.hazelcast.util.EzyMapServiceAutoImplAnnotations; +import com.tvd12.test.base.BaseTest; + +public class EzyMapServiceAutoImplAnnotationsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyMapServiceAutoImplAnnotations.class; + } + + @Test + public void test() { + assert EzyMapServiceAutoImplAnnotations.getBeanName(A.class).equals("x"); + assert EzyMapServiceAutoImplAnnotations.getBeanName(B.class).equals("b"); + } + + @EzyMapServiceAutoImpl(value = "d", name = "x") + public static interface A { + + } + + @EzyMapServiceAutoImpl(value = "d") + public static interface B { + + } +} + diff --git a/ezyfox-server-hazelcast/src/test/resources/AllTests.tng.xml b/ezyfox-server-hazelcast/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..70ead40d --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/resources/AllTests.tng.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-hazelcast/src/test/resources/hazelcast.xml b/ezyfox-server-hazelcast/src/test/resources/hazelcast.xml new file mode 100644 index 00000000..6ca0e4de --- /dev/null +++ b/ezyfox-server-hazelcast/src/test/resources/hazelcast.xml @@ -0,0 +1,24 @@ + + + http://localhost:8080/mancenter + + + dev + dev-pass + + + + true + slf4j + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-httpserver/assembly.xml b/ezyfox-server-httpserver/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-httpserver/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-httpserver/pom.xml b/ezyfox-server-httpserver/pom.xml new file mode 100644 index 00000000..8cc8135e --- /dev/null +++ b/ezyfox-server-httpserver/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-httpserver + 1.0.0 + ezyfox-server-httpserver + http://www.tvd12.com/java/projects/ezyfox-server + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-webapi + ${ezy.webapi.version} + + + + \ No newline at end of file diff --git a/ezyfox-server-httpserver/src/main/java/com/tvd12/ezyfoxserver/EzyComplexHttpBootstrap.java b/ezyfox-server-httpserver/src/main/java/com/tvd12/ezyfoxserver/EzyComplexHttpBootstrap.java new file mode 100644 index 00000000..9c1648ed --- /dev/null +++ b/ezyfox-server-httpserver/src/main/java/com/tvd12/ezyfoxserver/EzyComplexHttpBootstrap.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver; + +import com.tvd12.ezyfoxserver.webapi.EzySpringHttpBootstrap; + +public class EzyComplexHttpBootstrap extends EzySpringHttpBootstrap { +} diff --git a/ezyfox-server-httpserver/src/test/resources/AllTests.tng.xml b/ezyfox-server-httpserver/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-httpserver/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-io/.gitignore b/ezyfox-server-io/.gitignore new file mode 100644 index 00000000..7af81372 --- /dev/null +++ b/ezyfox-server-io/.gitignore @@ -0,0 +1,6 @@ +/\/ +/\/ +/\/ +/\/ +/test/ +/ diff --git a/ezyfox-server-io/pom.xml b/ezyfox-server-io/pom.xml index f5d936ec..34434e5c 100644 --- a/ezyfox-server-io/pom.xml +++ b/ezyfox-server-io/pom.xml @@ -1,15 +1,28 @@ - 4.0.0 com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-io - 0.0.2 + 1.0.0 + ezyfox-server-io http://maven.apache.org + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-util + ${ezy.util.version} + + + diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/exception/EzyFileNotFoundException.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/exception/EzyFileNotFoundException.java new file mode 100644 index 00000000..82c22f56 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/exception/EzyFileNotFoundException.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.exception; + +import java.io.File; + +public class EzyFileNotFoundException extends IllegalArgumentException { + private static final long serialVersionUID = 8543271843235809091L; + + public EzyFileNotFoundException(Throwable e) { + super(e); + } + + public EzyFileNotFoundException(String msg) { + super(msg); + } + + public EzyFileNotFoundException(File file) { + super(file.getAbsolutePath() + " not found!"); + } + + public EzyFileNotFoundException(String msg, Throwable e) { + super(msg, e); + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyAnywayFileFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyAnywayFileFetcher.java new file mode 100644 index 00000000..d0012c56 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyAnywayFileFetcher.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; + +public class EzyAnywayFileFetcher extends EzyClassPathFileFetcher { + + protected EzyFileFetcher firstFetcher; + + protected EzyAnywayFileFetcher(Builder builder) { + super(builder); + this.firstFetcher = builder.newFirstFetcher(); + } + + @Override + public File get(String filePath) { + File file = tryFirstFetch(filePath); + return file != null ? file : super.get(filePath); + } + + protected File tryFirstFetch(String filePath) { + return firstFetcher.get(filePath); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyClassPathFileFetcher.Builder { + + @Override + public EzyClassPathFileFetcher build() { + return new EzyAnywayFileFetcher(this); + } + + protected EzyFileFetcher newFirstFetcher() { + return EzySimpleFileFetcher.builder() + .throwException(false) + .build(); + } + + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyClassPathFileFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyClassPathFileFetcher.java new file mode 100644 index 00000000..c0a5ceb7 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyClassPathFileFetcher.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; +import java.net.URL; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzyClassPathFileFetcher implements EzyFileFetcher { + + protected ClassLoader classLoader; + + protected EzyClassPathFileFetcher(Builder builder) { + this.classLoader = builder.classLoader; + } + + @Override + public File get(String filePath) { + File file = firstGet(filePath); + return file != null ? file : secondGet(filePath); + } + + protected File firstGet(String filePath) { + URL url = classLoader.getResource(filePath); + return url != null ? new File(url.getFile()) : null; + } + + protected File secondGet(String filePath) { + return firstGet(File.separator + filePath); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected ClassLoader classLoader = getClass().getClassLoader(); + + public Builder context(Class context) { + return classLoader(context.getClassLoader()); + } + + public Builder classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + @Override + public EzyFileFetcher build() { + return new EzyClassPathFileFetcher(this); + } + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileFetcher.java new file mode 100644 index 00000000..0bc85c4f --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileFetcher.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; + +public interface EzyFileFetcher { + + File get(String filePath); + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileReader.java new file mode 100644 index 00000000..ef0fbd01 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileReader.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; +import java.util.Collection; + +public interface EzyFileReader { + + byte[] readBytes(File file); + + Collection readLines(File file, String charset); + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileWriter.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileWriter.java new file mode 100644 index 00000000..a4eee7f9 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzyFileWriter.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; +import java.io.InputStream; +import java.nio.charset.Charset; + +public interface EzyFileWriter { + + void write(File file, byte[] data); + + void write(File file, InputStream stream); + + void write(File file, CharSequence data, String charset); + + void write(File file, CharSequence data, Charset charset); + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileFetcher.java new file mode 100644 index 00000000..e1ab527f --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileFetcher.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.exception.EzyFileNotFoundException; + +public class EzySimpleFileFetcher implements EzyFileFetcher { + + protected boolean throwException; + + protected EzySimpleFileFetcher(Builder builder) { + this.throwException = builder.throwException; + } + + @Override + public File get(String filePath) { + File file = new File(filePath); + if(file.exists()) + return file; + if(isThrowException()) + throw new EzyFileNotFoundException(file); + return null; + } + + protected boolean isThrowException() { + return throwException; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected boolean throwException = true; + + public Builder throwException(boolean throwException) { + this.throwException = throwException; + return this; + } + + @Override + public EzyFileFetcher build() { + return new EzySimpleFileFetcher(this); + } + } +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileReader.java new file mode 100644 index 00000000..e164065b --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileReader.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.file; + +import static com.tvd12.ezyfoxserver.util.EzyReturner.returnWithIllegalArgumentException; +import java.io.File; +import java.util.Collection; + +import org.apache.commons.io.FileUtils; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzySimpleFileReader implements EzyFileReader { + + protected EzySimpleFileReader(Builder builder) { + } + + @Override + public byte[] readBytes(File file) { + return returnWithIllegalArgumentException(() -> FileUtils.readFileToByteArray(file)); + } + + @Override + public Collection readLines(File file, String charset) { + return returnWithIllegalArgumentException(() -> FileUtils.readLines(file, charset)); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyFileReader build() { + return new EzySimpleFileReader(this); + } + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileWriter.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileWriter.java new file mode 100644 index 00000000..e1276e21 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/file/EzySimpleFileWriter.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.file; + +import java.io.File; +import java.io.InputStream; +import java.nio.charset.Charset; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import static com.tvd12.ezyfoxserver.util.EzyProcessor.processWithIllegalArgumentException; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzySimpleFileWriter implements EzyFileWriter { + + protected EzySimpleFileWriter(Builder builder) { + } + + @Override + public void write(File file, byte[] data) { + processWithIllegalArgumentException(() -> FileUtils.writeByteArrayToFile(file, data)); + } + + @Override + public void write(File file, InputStream stream) { + processWithIllegalArgumentException(() -> write(file, IOUtils.toByteArray(stream))); + } + + @Override + public void write(File file, CharSequence data, Charset charset) { + processWithIllegalArgumentException(() -> FileUtils.write(file, data, charset)); + } + + @Override + public void write(File file, CharSequence data, String charset) { + write(file, data, Charset.forName(charset)); + } + + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyFileWriter build() { + return new EzySimpleFileWriter(this); + } + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyClassesFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyClassesFetcher.java new file mode 100644 index 00000000..ee9b4d91 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyClassesFetcher.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.List; +import java.util.Set; + +public interface EzyClassesFetcher { + + @SuppressWarnings("rawtypes") + Set asSet(String filePath); + + @SuppressWarnings("rawtypes") + List asList(String filePath); + +} \ No newline at end of file diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileReader.java deleted file mode 100644 index 169a8121..00000000 --- a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileReader.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.io.File; - -public interface EzyFileReader { - - byte[] readBytes(File file); - -} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileWriter.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileWriter.java deleted file mode 100644 index 13d2f6d4..00000000 --- a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzyFileWriter.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.io.File; - -public interface EzyFileWriter { - - void write(byte[] data, File file); - -} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileReader.java deleted file mode 100644 index 6f8324a0..00000000 --- a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileReader.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.io.File; - -import org.apache.commons.io.FileUtils; - -public class EzySimpleFileReader implements EzyFileReader { - - @Override - public byte[] readBytes(File file) { - try { - return FileUtils.readFileToByteArray(file); - } - catch(Exception e) { - throw new IllegalArgumentException(e); - } - } - - - -} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileWriter.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileWriter.java deleted file mode 100644 index c0c61fa0..00000000 --- a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleFileWriter.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.tvd12.ezyfoxserver.io; - -import java.io.File; - -import org.apache.commons.io.FileUtils; - -public class EzySimpleFileWriter implements EzyFileWriter { - - @Override - public void write(byte[] data, File file) { - try { - FileUtils.writeByteArrayToFile(file, data); - } - catch(Exception e) { - throw new IllegalArgumentException(e); - } - } - -} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyAnywayInputStreamLoader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyAnywayInputStreamLoader.java new file mode 100644 index 00000000..2366e52b --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyAnywayInputStreamLoader.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.InputStream; + +public class EzyAnywayInputStreamLoader extends EzyClassPathInputStreamLoader { + + protected EzyInputStreamLoader firstLoader; + + protected EzyAnywayInputStreamLoader(Builder builder) { + super(builder); + this.firstLoader = builder.newFirstLoader(); + } + + @Override + public InputStream load(String filePath) { + InputStream stream = tryFirstLoad(filePath); + return stream != null ? stream : super.load(filePath); + } + + protected InputStream tryFirstLoad(String filePath) { + return firstLoader.load(filePath); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyClassPathInputStreamLoader.Builder { + + @Override + public EzyAnywayInputStreamLoader build() { + return new EzyAnywayInputStreamLoader(this); + } + + protected EzyInputStreamLoader newFirstLoader() { + return EzySimpleInputStreamLoader.builder() + .throwException(false) + .build(); + } + + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyClassPathInputStreamLoader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyClassPathInputStreamLoader.java new file mode 100644 index 00000000..df807a55 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyClassPathInputStreamLoader.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.File; +import java.io.InputStream; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzyClassPathInputStreamLoader implements EzyInputStreamLoader { + + protected ClassLoader classLoader; + + protected EzyClassPathInputStreamLoader(Builder builder) { + this.classLoader = builder.classLoader; + } + + @Override + public InputStream load(String filePath) { + InputStream stream = firstLoad(filePath); + return stream != null ? stream : secondLoad(filePath); + } + + protected InputStream firstLoad(String filePath) { + return classLoader.getResourceAsStream(filePath); + } + + protected InputStream secondLoad(String filePath) { + return firstLoad(File.separator + filePath); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected ClassLoader classLoader = getClass().getClassLoader(); + + public Builder context(Class context) { + return classLoader(context.getClassLoader()); + } + + public Builder classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + @Override + public EzyInputStreamLoader build() { + return new EzyClassPathInputStreamLoader(this); + } + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamLoader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamLoader.java new file mode 100644 index 00000000..3d9ca4c2 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamLoader.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.InputStream; + +public interface EzyInputStreamLoader { + + InputStream load(String filePath); + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamReader.java new file mode 100644 index 00000000..21976a51 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyInputStreamReader.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.InputStream; +import java.util.Collection; + +public interface EzyInputStreamReader { + + byte[] readBytes(InputStream stream); + + char[] readChars(InputStream stream, String charset); + + String readString(InputStream stream, String charset); + + Collection readLines(InputStream stream, String charset); + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamLoader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamLoader.java new file mode 100644 index 00000000..77b2f2b7 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamLoader.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.exception.EzyFileNotFoundException; +import com.tvd12.ezyfoxserver.file.EzyFileFetcher; +import com.tvd12.ezyfoxserver.file.EzySimpleFileFetcher; + +public class EzySimpleInputStreamLoader implements EzyInputStreamLoader { + + protected EzyFileFetcher fileFetcher; + + protected EzySimpleInputStreamLoader(Builder builder) { + this.fileFetcher = builder.newFileFecher(); + } + + @Override + public InputStream load(String filePath) { + try { + File file = getFile(filePath); + return file != null ? new FileInputStream(file) : null; + } catch (Exception e) { + throw processException(e); + } + } + + protected RuntimeException processException(Exception e) { + if(e instanceof EzyFileNotFoundException) + return (EzyFileNotFoundException)e; + if(e instanceof FileNotFoundException) + return new EzyFileNotFoundException(e); + throw new IllegalArgumentException(e); + } + + protected File getFile(String filePath) throws FileNotFoundException { + return fileFetcher.get(filePath); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + implements EzyBuilder { + + protected boolean throwException = true; + + public Builder throwException(boolean throwException) { + this.throwException = throwException; + return this; + } + + @Override + public EzyInputStreamLoader build() { + return new EzySimpleInputStreamLoader(this); + } + + protected EzyFileFetcher newFileFecher() { + return EzySimpleFileFetcher.builder() + .throwException(throwException) + .build(); + } + } +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamReader.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamReader.java new file mode 100644 index 00000000..56a5a013 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzySimpleInputStreamReader.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.stream; + +import static com.tvd12.ezyfoxserver.util.EzyReturner.returnWithIllegalArgumentException; + +import java.io.InputStream; +import java.util.Collection; + +import org.apache.commons.io.IOUtils; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzySimpleInputStreamReader implements EzyInputStreamReader { + + protected EzySimpleInputStreamReader(Builder builder) { + } + + @Override + public byte[] readBytes(InputStream stream) { + return returnWithIllegalArgumentException(() -> IOUtils.toByteArray(stream)); + } + + @Override + public String readString(InputStream stream, String charset) { + return returnWithIllegalArgumentException(() -> new String(readBytes(stream), charset)); + } + + @Override + public char[] readChars(InputStream stream, String charset) { + return readString(stream, charset).toCharArray(); + } + + @Override + public Collection readLines(InputStream stream, String charset) { + return returnWithIllegalArgumentException(() -> IOUtils.readLines(stream, charset)); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + @Override + public EzyInputStreamReader build() { + return new EzySimpleInputStreamReader(this); + } + } + +} diff --git a/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyStreamClassesFetcher.java b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyStreamClassesFetcher.java new file mode 100644 index 00000000..81327c14 --- /dev/null +++ b/ezyfox-server-io/src/main/java/com/tvd12/ezyfoxserver/stream/EzyStreamClassesFetcher.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.stream; + +import java.io.InputStream; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.io.EzyClassesFetcher; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; + +public class EzyStreamClassesFetcher implements EzyClassesFetcher { + + protected ClassLoader classLoader; + + protected EzyStreamClassesFetcher(Builder builder) { + this.classLoader = builder.classLoader; + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.file.EzyClassesFetcher#asSet() + */ + @Override + @SuppressWarnings("rawtypes") + public Set asSet(String filePath) { + return new HashSet<>(asList(filePath)); + } + + /* (non-Javadoc) + * @see com.tvd12.ezyfoxserver.file.EzyClassesFetcher#asList() + */ + @Override + @SuppressWarnings("rawtypes") + public List asList(String filePath) { + Collection classNames = getClassNames(filePath); + return EzyLists.newArrayList(classNames, this::getClass); + } + + @SuppressWarnings("rawtypes") + protected Class getClass(String className) { + return EzyClasses.getClass(className, classLoader); + } + + protected Collection getClassNames(String filePath) { + InputStream stream = loadInputStream(filePath); + EzyInputStreamReader reader = newInputStreamReader(); + return reader.readLines(stream, "UTF-8"); + } + + protected EzyInputStreamReader newInputStreamReader() { + return new EzySimpleInputStreamReader.Builder() + .build(); + } + + protected InputStream loadInputStream(String filePath) { + EzyInputStreamLoader loader = newInputStreamLoader(); + return loader.load(filePath); + } + + protected EzyInputStreamLoader newInputStreamLoader() { + return new EzyAnywayInputStreamLoader.Builder() + .classLoader(classLoader) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + protected ClassLoader classLoader; + + public Builder context(Class context) { + return classLoader(context.getClassLoader()); + } + + public Builder classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + @Override + public EzyClassesFetcher build() { + return new EzyStreamClassesFetcher(this); + } + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyFileNotFoundExceptionTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyFileNotFoundExceptionTest.java new file mode 100644 index 00000000..9b7167f6 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyFileNotFoundExceptionTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.exception; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyFileNotFoundException; +import com.tvd12.test.base.BaseTest; + +public class EzyFileNotFoundExceptionTest extends BaseTest { + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test1() { + throw new EzyFileNotFoundException(new Exception()); + } + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test2() { + throw new EzyFileNotFoundException(new Exception().toString()); + } + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test3() { + throw new EzyFileNotFoundException("", new Exception()); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyAnywayFileFetcherTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyAnywayFileFetcherTest.java new file mode 100644 index 00000000..247251dd --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyAnywayFileFetcherTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.testing.file; + +import java.io.File; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyAnywayFileFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzyAnywayFileFetcherTest extends BaseTest { + + @Test + public void test1() { + File file = EzyAnywayFileFetcher.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .get("AllTests.tng.xml"); + assert file != null; + } + + @Test + public void test2() { + File file = EzyAnywayFileFetcher.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .get("pom.xml"); + assert file != null; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyClassPathFileFetcherTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyClassPathFileFetcherTest.java new file mode 100644 index 00000000..b4dc7116 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzyClassPathFileFetcherTest.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.testing.file; + +import java.io.File; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyClassPathFileFetcher; +import com.tvd12.ezyfoxserver.file.EzyFileFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzyClassPathFileFetcherTest extends BaseTest { + + @Test + public void test1() { + File file = EzyClassPathFileFetcher.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .get("AllTests.tng.xml"); + assert file != null; + } + + @Test + public void test2() { + File file = new EzyClassPathFileFetcher.Builder() { + public EzyFileFetcher build() { + return new EzyClassPathFileFetcher(this) { + protected File firstGet(String filePath) { + return null; + } + }; + + } + } + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .get("AllTests.tng.xml"); + assert file == null; + } + + @Test + public void test3() { + File file = EzyClassPathFileFetcher.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .get("safsdf.tng.xml"); + assert file == null; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileFetcherTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileFetcherTest.java new file mode 100644 index 00000000..6bfb8afd --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileFetcherTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.file; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyFileNotFoundException; +import com.tvd12.ezyfoxserver.file.EzySimpleFileFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleFileFetcherTest extends BaseTest { + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test1() { + EzySimpleFileFetcher.builder().build().get("fsadfsaf.csdf"); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileReaderTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileReaderTest.java new file mode 100644 index 00000000..0c24cd23 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileReaderTest.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.testing.file; + +import java.io.File; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleFileReaderTest extends BaseTest { + + private File directory = new File("test"); + private EzyFileWriter writer = EzySimpleFileWriter.builder().build(); + private EzyFileReader reader = EzySimpleFileReader.builder().build(); + + public EzySimpleFileReaderTest() { + super(); + directory.mkdirs(); + } + + @Test + public void test() { + File file = new File(directory.getAbsolutePath() + File.separator + "EzySimpleFileWriterTest.txt"); + writer.write(file, new byte[] {'a', 'b', 'c'}); + reader.readBytes(file); + reader.readLines(file, "UTF-8"); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + reader.readBytes(new File("\\/xfav")); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileWriterTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileWriterTest.java new file mode 100644 index 00000000..2ca18f88 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/file/EzySimpleFileWriterTest.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.testing.file; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleFileWriterTest extends BaseTest { + + private File directory = new File("test"); + private EzyFileWriter writer = EzySimpleFileWriter.builder().build(); + + public EzySimpleFileWriterTest() { + super(); + directory.mkdirs(); + } + + @Test + public void test() { + File file = new File(directory.getAbsolutePath() + File.separator + "EzySimpleFileWriterTest.txt"); + writer.write(file, new byte[] {'a', 'b', 'c'}); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() throws IOException { + File file = new File("test/cant_write.txt"); + file.createNewFile(); + file.setWritable(false); + writer.write(file, new byte[] {'a', 'b', 'c'}); + } + + @Test + public void test2() { + File file = new File(directory.getAbsolutePath() + File.separator + "EzySimpleFileWriterTest.txt"); + writer.write(file, new InputStream() { + int index = 0; + private byte[] bytes = new byte[] {1, 2, 3}; + @Override + public int read() throws IOException { + if(index >= bytes.length) + return -1; + return bytes[index ++]; + } + }); + } + + @Test + public void test3() { + File file = new File(directory.getAbsolutePath() + File.separator + "EzySimpleFileWriterTest.txt"); + writer.write(file, "abc", "UTF-8"); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyClassesFetcherTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyClassesFetcherTest.java new file mode 100644 index 00000000..ba3d93b3 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyClassesFetcherTest.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.testing.io; + +public class EzyClassesFetcherTest { + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java new file mode 100644 index 00000000..2b8224dc --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyBytesCopyTest.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.testing.performance; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.test.performance.Performance; + +public class EzyBytesCopyTest { + + @Test + public void test1() { + byte[][] bytess = new byte[][] { + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4} + }; + long time = Performance.create() + .loop(1000000) + .test(()-> { + EzyBytes.copy(bytess); + }) + .getTime(); + System.out.println("test1 elapsed time = " + time); + } + + @Test + public void test2() { + byte[][] bytess = new byte[][] { + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4}, + {1,2},{3,4}, {3,4}, {3,4}, {3,4}, {3,4}, {3,4} + }; + long time = Performance.create() + .loop(1000000) + .test(()-> { + int passed = 0; + byte[] bytes = new byte[EzyBytes.totalBytes(bytess)]; + for(int i = 0 ; i < bytess.length ; i++) { + System.arraycopy(bytess[i], 0, bytes, passed, bytess[i].length); + passed += bytess[i].length; + } + }) + .getTime(); + System.out.println("test2 elapsed time = " + time); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyMapsTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyMapsTest.java new file mode 100644 index 00000000..d3c7131c --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/performance/EzyMapsTest.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.testing.performance; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.test.performance.Performance; + +public class EzyMapsTest { + + @SuppressWarnings("rawtypes") + public static void main(String[] args) { + Map map = new HashMap<>(); + map.put(A.class, new E()); + long time = Performance.create() + .loop(1000000) + .test(() -> EzyMaps.getValue(map, A.class)) + .getTime(); + System.out.println(time); + } + + public static interface A { + } + + public static interface B extends A { + + } + + public static interface C extends A { + + } + + public static class D implements C { + + } + + public static class E extends D { + + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyAnywayInputStreamLoaderTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyAnywayInputStreamLoaderTest.java new file mode 100644 index 00000000..d7ade55d --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyAnywayInputStreamLoaderTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.io.InputStream; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.stream.EzyAnywayInputStreamLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyAnywayInputStreamLoaderTest extends BaseTest { + + @Test + public void test1() { + InputStream stream = EzyAnywayInputStreamLoader.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .load("AllTests.tng.xml"); + assert stream != null; + } + + @Test + public void test2() { + InputStream stream = EzyAnywayInputStreamLoader.builder() + .classLoader(getClass().getClassLoader()) + .context(getClass()) + .build() + .load("pom.xml"); + assert stream != null; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyClassPathInputStreamLoaderTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyClassPathInputStreamLoaderTest.java new file mode 100644 index 00000000..9fd10927 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyClassPathInputStreamLoaderTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.stream.EzyClassPathInputStreamLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyClassPathInputStreamLoaderTest extends BaseTest { + + @Test + public void test1() { + assert EzyClassPathInputStreamLoader.builder() + .context(getClass()) + .build() + .load("fasfasdf.afdsf") == null; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamLoaderTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamLoaderTest.java new file mode 100644 index 00000000..aeac1316 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamLoaderTest.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.io.FileNotFoundException; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyFileNotFoundException; +import com.tvd12.ezyfoxserver.stream.EzySimpleInputStreamLoader; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleInputStreamLoaderTest extends BaseTest { + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test1() { + EzySimpleInputStreamLoader.builder() + .throwException(true) + .build() + .load("ffsadfs.afasdf"); + } + + @Test(expectedExceptions = {EzyFileNotFoundException.class}) + public void test2() { + new EzySimpleInputStreamLoader.Builder() { + public com.tvd12.ezyfoxserver.stream.EzyInputStreamLoader build() { + return new EzySimpleInputStreamLoader(this) { + protected java.io.File getFile(String filePath) throws FileNotFoundException { + throw new FileNotFoundException(); + }; + }; + }; + } + .throwException(true) + .build() + .load("ffsadfs.afasdf"); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + new EzySimpleInputStreamLoader.Builder() { + public com.tvd12.ezyfoxserver.stream.EzyInputStreamLoader build() { + return new EzySimpleInputStreamLoader(this) { + protected java.io.File getFile(String filePath) throws FileNotFoundException { + throw new NullPointerException(); + }; + }; + }; + } + .throwException(true) + .build() + .load("ffsadfs.afasdf"); + } + + public void test4() { + assert new EzySimpleInputStreamLoader.Builder() { + public com.tvd12.ezyfoxserver.stream.EzyInputStreamLoader build() { + return new EzySimpleInputStreamLoader(this) { + protected java.io.File getFile(String filePath) throws FileNotFoundException { + throw new NullPointerException(); + }; + }; + }; + } + .throwException(false) + .build() + .load("ffsadfs.afasdf") == null; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamReaderTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamReaderTest.java new file mode 100644 index 00000000..9be5622d --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzySimpleInputStreamReaderTest.java @@ -0,0 +1,62 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.io.IOException; +import java.io.InputStream; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.stream.EzyInputStreamReader; +import com.tvd12.ezyfoxserver.stream.EzySimpleInputStreamReader; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleInputStreamReaderTest extends BaseTest { + + @Test + public void test() { + EzyInputStreamReader reader = EzySimpleInputStreamReader.builder() + .build(); + reader.readBytes(new InputStream() { + int index = 0; + private byte[] bytes = new byte[] {1, 2, 3}; + @Override + public int read() throws IOException { + if(index >= bytes.length) + return -1; + return bytes[index ++]; + } + }); + } + + @Test + public void test1() { + EzyInputStreamReader reader = EzySimpleInputStreamReader.builder() + .build(); + reader.readString(new InputStream() { + int index = 0; + private byte[] bytes = new byte[] {1, 2, 3}; + @Override + public int read() throws IOException { + if(index >= bytes.length) + return -1; + return bytes[index ++]; + } + }, "UTF-8"); + } + + @Test + public void test2() { + EzyInputStreamReader reader = EzySimpleInputStreamReader.builder() + .build(); + reader.readChars(new InputStream() { + int index = 0; + private byte[] bytes = new byte[] {1, 2, 3}; + @Override + public int read() throws IOException { + if(index >= bytes.length) + return -1; + return bytes[index ++]; + } + }, "UTF-8"); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyStreamClassesFetcherTest.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyStreamClassesFetcherTest.java new file mode 100644 index 00000000..10cffeea --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/EzyStreamClassesFetcherTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.util.Set; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyClassesFetcher; +import com.tvd12.ezyfoxserver.stream.EzyStreamClassesFetcher; +import com.tvd12.test.base.BaseTest; + +public class EzyStreamClassesFetcherTest extends BaseTest { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void test() { + Set set = EzyStreamClassesFetcher.builder() + .context(getClass()) + .build() + .asSet("classes.txt"); + Class first = set.iterator().next(); + assert first.getClassLoader() == EzyClassesFetcher.class.getClassLoader(); + assert first == EzyClassesFetcher.class; + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamExample.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamExample.java new file mode 100644 index 00000000..7245c321 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamExample.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +public class JavaInputStreamExample { + + public static void main(String[] args) throws IOException { + InputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + assert stream.markSupported(); + assert stream.available() == 10; + byte[] bytes = new byte[2]; + stream.read(bytes); + assert stream.available() == 8; + assert stream.skip(2) == 2L; + stream.mark(8); + assert stream.available() == 6; + stream.read(bytes); + assert stream.available() == 4; + stream.read(bytes); + assert stream.available() == 2; + stream.read(bytes); + assert stream.available() == 0; + stream.reset(); + assert stream.available() == 10; + System.err.println(Arrays.toString(bytes)); + stream.mark(2); + stream.read(bytes, 0, 2); + System.err.println(Arrays.toString(bytes)); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample.java new file mode 100644 index 00000000..4ef11ddb --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import static org.testng.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +public class JavaInputStreamMarkExample { + + public static void main(String[] args) throws IOException { + InputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}); + assert stream.markSupported(); + assert stream.available() == 10; + byte[] bytes = new byte[2]; + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 13); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 11); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 9); + stream.mark(3); + System.err.println("========== after set mark ========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + stream.reset(); + System.err.println("========== after reset ========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample2.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample2.java new file mode 100644 index 00000000..f232978d --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample2.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import static org.testng.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +public class JavaInputStreamMarkExample2 { + + public static void main(String[] args) throws IOException { + InputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}); + assert stream.markSupported(); + assert stream.available() == 10; + byte[] bytes = new byte[2]; + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 13); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 11); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 9); + stream.mark(3); + System.err.println("========== after set mark ========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + stream.reset(); + System.err.println("========== after reset ========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + System.err.println("=========== set mark 2 ==========="); + stream.mark(3); + System.err.println("=========== after set mark 2 ==========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + stream.reset(); + System.err.println("========== after reset 2 ========="); + System.err.println("available: " + stream.available()); + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample3.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample3.java new file mode 100644 index 00000000..8fcc6993 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamMarkExample3.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; + +public class JavaInputStreamMarkExample3 { + + @SuppressWarnings("resource") + public static void main(String[] args) throws IOException { + InputStream stream = new FileInputStream(new File("src/test/resources/example.txt")); + assert stream.markSupported(); + assert stream.available() == 10; + byte[] bytes = new byte[3]; + stream.read(bytes); + System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); +// assertEquals(stream.available(), 13); + stream.mark(2); + System.err.println("========== after set mark ========="); + stream.reset(); +// System.err.println("========== after reset ========="); +// stream.read(bytes); +// System.err.println("bytes: " + Arrays.toString(bytes)); + System.err.println("available: " + stream.available()); + + } + +} diff --git a/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamSkipExample.java b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamSkipExample.java new file mode 100644 index 00000000..44ab1302 --- /dev/null +++ b/ezyfox-server-io/src/test/java/com/tvd12/ezyfoxserver/testing/stream/JavaInputStreamSkipExample.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.testing.stream; + +import static org.testng.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +public class JavaInputStreamSkipExample { + + public static void main(String[] args) throws IOException { + InputStream stream = new ByteArrayInputStream(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}); + assert stream.markSupported(); + assert stream.available() == 10; + byte[] bytes = new byte[2]; + stream.read(bytes); + System.err.println("before skip"); + System.err.println("available: " + stream.available()); + stream.skip(2); + System.err.println("after skip"); + System.err.println("available: " + stream.available()); + System.err.println("before reset"); + stream.reset(); + System.err.println("after reset"); + System.err.println("available: " + stream.available()); + assertEquals(stream.available(), 10); + } + +} diff --git a/ezyfox-server-io/src/test/resources/AllTests.tng.xml b/ezyfox-server-io/src/test/resources/AllTests.tng.xml index 3f571ed5..e933217b 100644 --- a/ezyfox-server-io/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-io/src/test/resources/AllTests.tng.xml @@ -6,4 +6,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-io/src/test/resources/classes.txt b/ezyfox-server-io/src/test/resources/classes.txt new file mode 100644 index 00000000..7c66655a --- /dev/null +++ b/ezyfox-server-io/src/test/resources/classes.txt @@ -0,0 +1 @@ +com.tvd12.ezyfoxserver.io.EzyClassesFetcher \ No newline at end of file diff --git a/ezyfox-server-io/src/test/resources/example.docx b/ezyfox-server-io/src/test/resources/example.docx new file mode 100644 index 00000000..dec8d744 Binary files /dev/null and b/ezyfox-server-io/src/test/resources/example.docx differ diff --git a/ezyfox-server-io/src/test/resources/example.txt b/ezyfox-server-io/src/test/resources/example.txt new file mode 100644 index 00000000..402476b0 --- /dev/null +++ b/ezyfox-server-io/src/test/resources/example.txt @@ -0,0 +1 @@ +ABCDE \ No newline at end of file diff --git a/ezyfox-server-jackson/pom.xml b/ezyfox-server-jackson/pom.xml index cb8d2149..84977558 100644 --- a/ezyfox-server-jackson/pom.xml +++ b/ezyfox-server-jackson/pom.xml @@ -6,28 +6,22 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-jackson - 0.0.2 + 1.0.0 ezyfox-server-jackson http://maven.apache.org - 1.0.0 - 1.0.0 + 1.0.0 - - com.tvd12 - ezyfox-server-common - ${common.version} - com.tvd12 ezyfox-server-codec - ${codec.version} + ${ezy.codec.version} diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonArraySerializer.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonArraySerializer.java new file mode 100644 index 00000000..07074dd4 --- /dev/null +++ b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonArraySerializer.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.codec; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class JacksonArraySerializer extends StdSerializer { + private static final long serialVersionUID = 47227884568344818L; + + public JacksonArraySerializer(Class t) { + super(t); + } + + @Override + public void serialize(EzyArray value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.getCodec().writeValue(gen, value.toList()); + } + + + +} diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperBuilder.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperBuilder.java new file mode 100644 index 00000000..cab4bf24 --- /dev/null +++ b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperBuilder.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.codec; + +import com.fasterxml.jackson.databind.Module; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class JacksonObjectMapperBuilder implements EzyBuilder { + + public static JacksonObjectMapperBuilder newInstance() { + return new JacksonObjectMapperBuilder(); + } + + @Override + public ObjectMapper build() { + return new ObjectMapper() + .registerModule(newModule()); + } + + protected Module newModule() { + SimpleModule module = new SimpleModule(); + module.addSerializer(new JacksonArraySerializer(EzyArray.class)); + module.addSerializer(new JacksonObjectSerializer(EzyObject.class)); + return module; + } + +} diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperSetter.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperSetter.java deleted file mode 100644 index e9dafae6..00000000 --- a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectMapperSetter.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import lombok.AllArgsConstructor; - -@AllArgsConstructor -public class JacksonObjectMapperSetter { - - protected ObjectMapper objectMapper; - -} diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectSerializer.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectSerializer.java new file mode 100644 index 00000000..18d73751 --- /dev/null +++ b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonObjectSerializer.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.codec; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class JacksonObjectSerializer extends StdSerializer { + private static final long serialVersionUID = 1033303749441882688L; + + public JacksonObjectSerializer(Class t) { + super(t); + } + + @Override + public void serialize(EzyObject value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.getCodec().writeValue(gen, value.toMap()); + } + +} diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleDeserializer.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleDeserializer.java index ed4fd5c3..9372170e 100644 --- a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleDeserializer.java +++ b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleDeserializer.java @@ -1,6 +1,5 @@ package com.tvd12.ezyfoxserver.codec; -import java.io.IOException; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.Map.Entry; @@ -11,15 +10,22 @@ import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; import com.tvd12.ezyfoxserver.io.EzyByteBuffers; +import com.tvd12.ezyfoxserver.util.EzyLiteEntityBuilders; public class JacksonSimpleDeserializer - extends JacksonObjectMapperSetter + extends EzyLiteEntityBuilders implements EzyMessageDeserializer { + protected ObjectMapper objectMapper; + public JacksonSimpleDeserializer(ObjectMapper objectMapper) { - super(objectMapper); + this.objectMapper = objectMapper; + } + + @Override + public T deserialize(ByteBuffer buffer) { + return deserialize(EzyByteBuffers.getBytes(buffer)); } @SuppressWarnings("unchecked") @@ -28,6 +34,12 @@ public T deserialize(byte[] data) { return (T) parse(readTree(data)); } + @SuppressWarnings("unchecked") + @Override + public T deserialize(String text) { + return (T) parse(readTree(text)); + } + protected JsonNode readTree(byte[] data) { try { return objectMapper.readTree(data); @@ -36,17 +48,25 @@ protected JsonNode readTree(byte[] data) { } } + protected JsonNode readTree(String text) { + try { + return objectMapper.readTree(text); + } catch (Exception e) { + throw new IllegalArgumentException("read tree error", e); + } + } + protected Object parse(JsonNode node) { - if(node.isBinary()) - return parseBinary(node); - else if(node.isArray()) + if(node.isArray()) return parseArray(node); - else if(node.isObject()) + if(node.isObject()) return parseObject(node); - else if(node.isBoolean()) + if(node.isBoolean()) return parseBoolean(node); - else if(node.isNumber()) + if(node.isNumber()) return parseNumber(node); + if(node.isNull()) + return null; return parseText(node); } @@ -62,14 +82,6 @@ protected boolean parseBoolean(JsonNode node) { return node.asBoolean(); } - protected byte[] parseBinary(JsonNode node) { - try { - return node.binaryValue(); - } catch (IOException e) { - throw new IllegalStateException("parse binary error", e); - } - } - protected EzyArray parseArray(JsonNode node) { EzyArrayBuilder arrayBuilder = newArrayBuilder(); Iterator iterator = node.iterator(); @@ -88,17 +100,4 @@ protected EzyObject parseObject(JsonNode node) { return objectBuilder.build(); } - private EzyArrayBuilder newArrayBuilder() { - return EzyEntityFactory.create(EzyArrayBuilder.class); - } - - private EzyObjectBuilder newObjectBuilder() { - return EzyEntityFactory.create(EzyObjectBuilder.class); - } - - @Override - public T deserialize(ByteBuffer buffer) { - return deserialize(EzyByteBuffers.getBytes(buffer)); - } - } diff --git a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleSerializer.java b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleSerializer.java index 61f8b7c9..bcece51d 100644 --- a/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleSerializer.java +++ b/ezyfox-server-jackson/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonSimpleSerializer.java @@ -1,5 +1,6 @@ package com.tvd12.ezyfoxserver.codec; +import java.nio.ByteBuffer; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -10,7 +11,7 @@ import com.tvd12.ezyfoxserver.function.EzyParser; public class JacksonSimpleSerializer - extends EzyAbstractSerializer + extends EzyAbstractByTypeSerializer implements EzyMessageSerializer { protected ObjectMapper objectMapper; @@ -18,33 +19,29 @@ public class JacksonSimpleSerializer public JacksonSimpleSerializer(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } + + @SuppressWarnings("unchecked") + @Override + protected T parseNil(Class outType) { + return (T) writeValueAsBytes(null); + } + @SuppressWarnings("unchecked") @Override - protected byte[] parseNil() { - return null; + protected T parseWithNoParsers(Object value, Class outType) { + return (T) writeValueAsBytes(value); } + @SuppressWarnings("unchecked") @Override - protected byte[] parseWithNoParser(Object value) { - return writeValueAsBytes(value); + protected T parseWithNoParser(Object value, Class outType) { + return (T)writeValueAsBytes(value); } protected byte[] parseObject(Object obj) { return parseObject((EzyObject)obj); } - protected byte[] parseObject(EzyObject obj) { - return writeValueAsBytes(obj.toMap()); - } - - protected byte[] parseArray(Object obj) { - return parseArray((EzyArray)obj); - } - - protected byte[] parseArray(EzyArray array) { - return writeValueAsBytes(array.toList()); - } - protected byte[] writeValueAsBytes(Object obj) { try { return objectMapper.writeValueAsBytes(obj); @@ -53,15 +50,58 @@ protected byte[] writeValueAsBytes(Object obj) { } } - protected Map, EzyParser> defaultParsers() { - Map, EzyParser> parsers = new ConcurrentHashMap<>(); - addParsers(parsers); - return parsers; + protected String writeValueAsString(Object obj) { + try { + return objectMapper.writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new IllegalArgumentException("write value as bytes error", e); + } } - protected void addParsers(Map, EzyParser> parsers) { - parsers.put(EzyObject.class, this::parseObject); - parsers.put(EzyArray.class, this::parseArray); + @SuppressWarnings("rawtypes") + @Override + protected void addParserss(Map, Map, EzyParser>> parserss) { + Map, EzyParser> objectParsers = new ConcurrentHashMap<>(); + parserss.put(EzyObject.class, objectParsers); + objectParsers.put(byte[].class, new EzyParser() { + @Override + public byte[] parse(EzyObject input) { + return writeValueAsBytes(input.toMap()); + } + }); + objectParsers.put(String.class, new EzyParser() { + @Override + public String parse(EzyObject input) { + return writeValueAsString(input.toMap()); + } + }); + objectParsers.put(ByteBuffer.class, new EzyParser() { + @Override + public ByteBuffer parse(EzyObject input) { + return ByteBuffer.wrap(writeValueAsBytes(input.toMap())); + } + }); + + Map, EzyParser> arrayParsers = new ConcurrentHashMap<>(); + parserss.put(EzyArray.class, arrayParsers); + arrayParsers.put(byte[].class, new EzyParser() { + @Override + public byte[] parse(EzyArray input) { + return writeValueAsBytes(input.toList()); + } + }); + arrayParsers.put(String.class, new EzyParser() { + @Override + public String parse(EzyArray input) { + return writeValueAsString(input.toList()); + } + }); + arrayParsers.put(ByteBuffer.class, new EzyParser() { + @Override + public ByteBuffer parse(EzyArray input) { + return ByteBuffer.wrap(writeValueAsBytes(input.toList())); + } + }); } } diff --git a/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonDetectTypeTest.java b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonDetectTypeTest.java new file mode 100644 index 00000000..b33557ab --- /dev/null +++ b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonDetectTypeTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.util.Arrays; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.tvd12.test.base.BaseTest; + +public class JacksonDetectTypeTest extends BaseTest { + + public static void main(String[] args) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + System.out.println(Arrays.toString(objectMapper.writeValueAsBytes(null))); + } + +} diff --git a/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleDeserializerTest.java b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleDeserializerTest.java new file mode 100644 index 00000000..83eaadca --- /dev/null +++ b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleDeserializerTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleDeserializer; +import com.tvd12.test.base.BaseTest; + +public class JacksonSimpleDeserializerTest extends BaseTest { + + private ObjectMapper objectMapper + = new ObjectMapper(); + private EzyMessageDeserializer deserializer + = new JacksonSimpleDeserializer(objectMapper); + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + deserializer.deserialize(ByteBuffer.wrap(new byte[] {1, 2, 3})); + } + +} diff --git a/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializer2Test.java b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializer2Test.java new file mode 100644 index 00000000..33c68aab --- /dev/null +++ b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializer2Test.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageByTypeSerializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonObjectMapperBuilder; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; +import com.tvd12.test.performance.Performance; + +public class JacksonSimpleSerializer2Test extends BaseTest { + + private ObjectMapper objectMapper = newObjectMapper(); + private EzyMessageByTypeSerializer serializer + = new JacksonSimpleSerializer(objectMapper); + private EzyMessageDeserializer deserializer + = new JacksonSimpleDeserializer(objectMapper); + + @SuppressWarnings("unchecked") + @Test + public void test() throws JsonProcessingException { + EzyArray origin = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("a", 1) + .append("b", 2) + .append("c", 3) + .append(EzyEntityFactory.create(EzyArrayBuilder.class)) + .build(); + byte[] bytes = serializer.serialize(origin); + EzyArray array = deserializer.deserialize(bytes); + System.out.println(array); + } + + @SuppressWarnings({ "unchecked", "unused" }) + @Test + public void test2() { + EzyArray origin = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("a", 1) + .append("b", 2) + .append("c", 3) + .append(EzyEntityFactory.create(EzyArrayBuilder.class)) + .build(); + long time = Performance.create() + .loop(100000) + .test(() -> { + byte[] bytes = serializer.serialize(origin); + String text = serializer.serialize(origin, String.class); + ByteBuffer buffer = serializer.serialize(origin, ByteBuffer.class); + }) + .getTime(); + System.out.println("test2 time = : " + time); + } + + private ObjectMapper newObjectMapper() { + return JacksonObjectMapperBuilder.newInstance().build(); + } + +} diff --git a/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializerTest.java b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializerTest.java new file mode 100644 index 00000000..014df80b --- /dev/null +++ b/ezyfox-server-jackson/src/test/java/com/tvd12/ezyfoxserver/codec/testing/JacksonSimpleSerializerTest.java @@ -0,0 +1,141 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; + +import org.testng.annotations.Test; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.test.base.BaseTest; + +import lombok.Data; + +public class JacksonSimpleSerializerTest extends BaseTest { + + private ObjectMapper objectMapper + = new ObjectMapper(); + private EzyMessageSerializer serializer + = new JacksonSimpleSerializer(objectMapper); + private EzyMessageDeserializer deserializer + = new JacksonSimpleDeserializer(objectMapper); + + @Test + public void test() throws JsonProcessingException { + assertEquals(serializer.serialize(null), objectMapper.writeValueAsBytes(null)); + byte[] bytes = serializer.serialize(new ClassA()); + EzyObject object = deserializer.deserialize(bytes); + assert object.size() == 14; + assert object.get("name").equals("abc"); + assert object.get("value", Long.class) == 123; + assertEquals(object.get("parents", String[].class), + new String[] {"dungtv", "tuyennc", "hunglq"}); + assert object.get("yesNo", boolean.class); + System.out.println(Arrays.toString(object.get("bytes", byte[].class))); + assertEquals(object.get("bytes", byte[].class), new byte[] {1, 2, 3, 4, 5}); + assertEquals(object.get("longValue", Long.class), null); + assertEquals(object.get("chs", char[].class), new char[] {'1', '2', '3'}); + assertEquals(object.get("doubleValue", Double.class), 123.456D); + assertEquals(object.get("classC", EzyObject.class).get("name"), "dungtv"); + assertEquals(object.get("strs", String[].class), new String[] {"a", "b", "c"}); + assertEquals(object.get("byteList", byte[][].class), new byte[][] {{1, 2,3}}); + } + + @Test + public void test1() { + EzyObject origin = EzyEntityFactory.create(EzyObjectBuilder.class) + .append("a", 1) + .append("b", 2) + .append("c", 3) + .build(); + byte[] bytes = serializer.serialize(origin); + EzyObject after = deserializer.deserialize(bytes); + assert after.size() == 3; + assert after.get("a", int.class) == 1; + assert after.get("b", byte.class) == 2; + assert after.get("c", short.class) == 3; + } + + @Test + public void test2() { + EzyArray origin = EzyEntityFactory.create(EzyArrayBuilder.class) + .append(1, 2, 3) + .build(); + byte[] bytes = serializer.serialize(origin); + EzyArray after = deserializer.deserialize(ByteBuffer.wrap(bytes)); + assert after.size() == 3; + assert after.get(0, int.class) == 1; + assert after.get(1, byte.class) == 2; + assert after.get(2, short.class) == 3; + } + + @Test(expectedExceptions = {InvocationTargetException.class}) + public void test3() throws Exception { + Method method = JacksonSimpleSerializer + .class.getDeclaredMethod("writeValueAsBytes", Object.class); + method.setAccessible(true); + method.invoke(serializer, new ClassB()); + } + + public void test5() { + EzyArray array = EzyEntityFactory.create(EzyArrayBuilder.class) + .append((Long)null) + .append(1L) + .append(new byte[] {1, 2, 3}) + .build(); + byte[] bytes = serializer.serialize(array); + EzyArray after = deserializer.deserialize(bytes); + assertEquals(after.get(0, Long.class), null); + assertEquals(after.get(1, Long.class), new Long(1L)); + assertEquals(after.get(2), new byte[] {1, 2, 3}); + } + + @Data + public static class ClassA { + private String name = "abc"; + private long value = 123; + private String[] parents = {"dungtv", "tuyennc", "hunglq"}; + private boolean yesNo = true; + private byte[] bytes = new byte[] {1, 2, 3, 4, 5}; + private Long longValue; + private char[] chs = {'1', '2', '3'}; + private double doubleValue = 123.456D; + private ClassC classC = new ClassC(); + private List strs = Lists.newArrayList("a", "b", "c"); + private List byteList = Lists.newArrayList(new byte[] {1, 2, 3}); + private List classCs = Lists.newArrayList(new ClassC()); + private byte[] base64Bytes = EzyBase64.encode("base64"); + private String base64String = EzyBase64.encodeUtf("base64"); + } + + public static class ClassB { + + @JsonProperty("name") + public String getName() { + throw new RuntimeException(); + } + } + + @Data + public static class ClassC { + private String name = "dungtv"; + } + +} diff --git a/ezyfox-server-jackson/src/test/resources/AllTests.tng.xml b/ezyfox-server-jackson/src/test/resources/AllTests.tng.xml index 1de16472..30d2fb28 100644 --- a/ezyfox-server-jackson/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-jackson/src/test/resources/AllTests.tng.xml @@ -3,7 +3,7 @@ - + \ No newline at end of file diff --git a/ezyfox-server-kafka/pom.xml b/ezyfox-server-kafka/pom.xml new file mode 100644 index 00000000..2b92e16b --- /dev/null +++ b/ezyfox-server-kafka/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-kafka + ezyfox-server-kafka + http://maven.apache.org + 1.0.0 + \ No newline at end of file diff --git a/ezyfox-server-mapping/pom.xml b/ezyfox-server-mapping/pom.xml new file mode 100644 index 00000000..f6748c59 --- /dev/null +++ b/ezyfox-server-mapping/pom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-mapping + 1.0.0 + ezyfox-server-mapping + http://maven.apache.org + + + 1.0.0 + + + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + + \ No newline at end of file diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyArraySerializer.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyArraySerializer.java new file mode 100644 index 00000000..3cede63f --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyArraySerializer.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class EzyArraySerializer extends StdSerializer { + private static final long serialVersionUID = 47227884568344818L; + + public EzyArraySerializer(Class t) { + super(t); + } + + @Override + public void serialize(EzyArray value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.getCodec().writeValue(gen, value.toList()); + } + + + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonMapper.java new file mode 100644 index 00000000..fa243b6f --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonMapper.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +public interface EzyJsonMapper extends EzyJsonReader, EzyJsonWriter { +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonReader.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonReader.java new file mode 100644 index 00000000..dbd36b0f --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonReader.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +public interface EzyJsonReader { + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonWriter.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonWriter.java new file mode 100644 index 00000000..dcacd5e4 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyJsonWriter.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +public interface EzyJsonWriter { + + String writeAsString(Object object); + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectMapperBuilder.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectMapperBuilder.java new file mode 100644 index 00000000..0f002c7b --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectMapperBuilder.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +import com.fasterxml.jackson.databind.Module; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class EzyObjectMapperBuilder implements EzyBuilder { + + public static EzyObjectMapperBuilder newInstance() { + return new EzyObjectMapperBuilder(); + } + + @Override + public ObjectMapper build() { + return new ObjectMapper() + .registerModule(newModule()); + } + + protected Module newModule() { + SimpleModule module = new SimpleModule(); + module.addSerializer(new EzyArraySerializer(EzyArray.class)); + module.addSerializer(new EzyObjectSerializer(EzyObject.class)); + return module; + } + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectSerializer.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectSerializer.java new file mode 100644 index 00000000..2b5cf5f1 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzyObjectSerializer.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +import java.io.IOException; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +public class EzyObjectSerializer extends StdSerializer { + private static final long serialVersionUID = 1033303749441882688L; + + public EzyObjectSerializer(Class t) { + super(t); + } + + @Override + public void serialize(EzyObject value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.getCodec().writeValue(gen, value.toMap()); + } + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzySimpleJsonMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzySimpleJsonMapper.java new file mode 100644 index 00000000..3edc1173 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jackson/EzySimpleJsonMapper.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.mapping.jackson; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleJsonMapper + extends EzyLoggable implements EzyJsonMapper { + + private final ObjectMapper mapper; + + protected EzySimpleJsonMapper(Builder builder) { + this.mapper = EzyObjectMapperBuilder.newInstance().build(); + this.mapper.enable(SerializationFeature.INDENT_OUTPUT); + this.mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + } + + @Override + public String writeAsString(Object object) { + try { + return mapper.writeValueAsString(object); + } catch (JsonProcessingException e) { + getLogger().error("can not read object " + object, e); + return null; + } + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + public EzySimpleJsonMapper build() { + return new EzySimpleJsonMapper(this); + } + + } + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzySimplXmlMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzySimplXmlMapper.java new file mode 100644 index 00000000..a656d82c --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzySimplXmlMapper.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.mapping.jaxb; + +import java.io.File; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +public class EzySimplXmlMapper implements EzyXmlMapper { + + private Unmarshaller unmarshaller; + + private EzySimplXmlMapper(Builder builder) { + this.unmarshaller = builder.newUnmarshaller(); + } + + @Override + public T read(File xmlFile, Class outputType) { + try { + return unmarshaller.unmarshal(new StreamSource(xmlFile), outputType).getValue(); + } catch (JAXBException e) { + throw new IllegalArgumentException("Can not read xml file " + xmlFile.getAbsolutePath() + " with " + outputType, e); + } + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private String contextPath; + private ClassLoader classLoader; + + public Builder contextClass(Class clazz) { + this.classLoader = clazz.getClassLoader(); + this.contextPath = clazz.getPackage().getName(); + return this; + } + + public Builder contextPath(String contextPath) { + this.contextPath = contextPath; + return this; + } + + public Builder classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + protected Unmarshaller newUnmarshaller() { + try { + return newJAXBContext().createUnmarshaller(); + } catch (JAXBException e) { + throw new IllegalArgumentException(e); + } + } + + public EzySimplXmlMapper build() { + return new EzySimplXmlMapper(this); + } + + protected JAXBContext newJAXBContext() throws JAXBException { + return JAXBContext.newInstance(contextPath, classLoader); + } + } + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlMapper.java new file mode 100644 index 00000000..4c5394f0 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlMapper.java @@ -0,0 +1,4 @@ +package com.tvd12.ezyfoxserver.mapping.jaxb; + +public interface EzyXmlMapper extends EzyXmlReader, EzyXmlWriter { +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlReader.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlReader.java new file mode 100644 index 00000000..0f8e32e1 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlReader.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.mapping.jaxb; + +import java.io.File; + +public interface EzyXmlReader { + + T read(File xmlFile, Class outputType); + + default T read(String filePath, Class outputType) { + return read(new File(filePath), outputType); + } + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlWriter.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlWriter.java new file mode 100644 index 00000000..02310741 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/jaxb/EzyXmlWriter.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.mapping.jaxb; + +public interface EzyXmlWriter { + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileMapper.java new file mode 100644 index 00000000..df20878a --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileMapper.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.mapping.properties; + +public interface EzyPropertiesFileMapper extends EzyPropertiesFileReader { + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileReader.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileReader.java new file mode 100644 index 00000000..c5b74904 --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzyPropertiesFileReader.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.mapping.properties; + +public interface EzyPropertiesFileReader { + + T read(String filePath, Class valueType); + +} diff --git a/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzySimplePropertiesFileMapper.java b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzySimplePropertiesFileMapper.java new file mode 100644 index 00000000..434e5a4d --- /dev/null +++ b/ezyfox-server-mapping/src/main/java/com/tvd12/ezyfoxserver/mapping/properties/EzySimplePropertiesFileMapper.java @@ -0,0 +1,59 @@ +package com.tvd12.ezyfoxserver.mapping.properties; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.properties.file.mapping.PropertiesMapper; +import com.tvd12.properties.file.reader.BaseFileReader; +import com.tvd12.properties.file.reader.FileReader; + +import lombok.Setter; + +@Setter +public class EzySimplePropertiesFileMapper + extends EzyLoggable + implements EzyPropertiesFileMapper { + + @SuppressWarnings("rawtypes") + protected Class context; + + @Override + public T read(String filePath, Class valueType) { + return new PropertiesMapper() + .context(context) + .clazz(valueType) + .file(filePath) + .reader(newFileReader()) + .map(); + } + + protected FileReader newFileReader() { + return new BaseFileReader(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + @SuppressWarnings("rawtypes") + protected Class context = getClass(); + + @SuppressWarnings("rawtypes") + public Builder context(Class context) { + this.context = context; + return this; + } + + @Override + public EzyPropertiesFileMapper build() { + EzySimplePropertiesFileMapper answer = newProduct(); + answer.setContext(context); + return answer; + } + + protected EzySimplePropertiesFileMapper newProduct() { + return new EzySimplePropertiesFileMapper(); + } + } + +} diff --git a/ezyfox-server-mapping/src/test/resources/AllTests.tng.xml b/ezyfox-server-mapping/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-mapping/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-mongodb/assembly.xml b/ezyfox-server-mongodb/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-mongodb/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-mongodb/pom.xml b/ezyfox-server-mongodb/pom.xml new file mode 100644 index 00000000..7ad05252 --- /dev/null +++ b/ezyfox-server-mongodb/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-mongodb + ezyfox-server-mongodb + 1.0.0 + http://maven.apache.org + + 3.4.0 + 1.0.0 + 1.0.0 + 1.0.0 + + + + com.tvd12 + ezyfox-server-database + ${ezy.database.version} + + + com.tvd12 + ezyfox-server-io + ${ezy.io.version} + + + org.mongodb + mongo-java-driver + ${mongodb.version} + + + com.tvd12 + ezyfox-server-bean + ${ezy.bean.version} + test + + + diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoClientAware.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoClientAware.java new file mode 100644 index 00000000..4f463628 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoClientAware.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.mongodb; + +import com.mongodb.MongoClient; + +public interface EzyMongoClientAware { + + void setMongoClient(MongoClient mongoClient); + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoCollectionAware.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoCollectionAware.java new file mode 100644 index 00000000..d7d04478 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoCollectionAware.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.mongodb; + +import org.bson.Document; + +import com.mongodb.client.MongoCollection; + +public interface EzyMongoCollectionAware { + + void setCollection(MongoCollection collection); + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoDatabaseAware.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoDatabaseAware.java new file mode 100644 index 00000000..4fc8c609 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoDatabaseAware.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.mongodb; + +import com.mongodb.client.MongoDatabase; + +public interface EzyMongoDatabaseAware { + + void setDatabase(MongoDatabase database); + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoRepository.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoRepository.java new file mode 100644 index 00000000..640352f9 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/EzyMongoRepository.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.mongodb; + +import com.tvd12.ezyfoxserver.database.repository.EzyEmptyRepository; +import com.tvd12.ezyfoxserver.database.service.EzyCrudService; + +public interface EzyMongoRepository + extends EzyEmptyRepository, EzyCrudService { + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzyRepositoriesImplementor.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzyRepositoriesImplementor.java new file mode 100644 index 00000000..f529f749 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzyRepositoriesImplementor.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.mongodb.bean; + +import java.util.Map; + +public interface EzyRepositoriesImplementor { + + public abstract EzyRepositoriesImplementor scan(String packageName); + + public abstract EzyRepositoriesImplementor scan(String... packageNames); + + public abstract EzyRepositoriesImplementor scan(Iterable packageNames); + + public abstract EzyRepositoriesImplementor repositoryInterface(Class itf); + + public abstract EzyRepositoriesImplementor repositoryInterfaces(Class... itfs); + + public abstract EzyRepositoriesImplementor repositoryInterfaces(Iterable> itfs); + + public abstract Map, Object> implement(Object template); + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoriesImplementor.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoriesImplementor.java new file mode 100644 index 00000000..6f22728c --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoriesImplementor.java @@ -0,0 +1,100 @@ +package com.tvd12.ezyfoxserver.mongodb.bean; + +import java.lang.reflect.Modifier; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzySimpleRepositoriesImplementor + extends EzyLoggable + implements EzyRepositoriesImplementor { + + protected Set> autoImplInterfaces; + + public EzySimpleRepositoriesImplementor() { + this.autoImplInterfaces = new HashSet<>(); + } + + public EzyRepositoriesImplementor scan(String packageName) { + autoImplInterfaces.addAll(getAutoImplRepoInterfaces(packageName)); + return this; + } + + public EzyRepositoriesImplementor scan(String... packageNames) { + return scan(Sets.newHashSet(packageNames)); + } + + public EzyRepositoriesImplementor scan(Iterable packageNames) { + packageNames.forEach(this::scan); + return this; + } + + @Override + public EzyRepositoriesImplementor repositoryInterface(Class itf) { + if(!Modifier.isInterface(itf.getModifiers())) { + getLogger().warn("class {} is not an interface, ignore its", itf.getSimpleName()); + } + else if(!EzyMongoRepository.class.isAssignableFrom(itf)) { + getLogger().warn("interface {} doestn't extends {}, ignore its", + itf.getSimpleName(), EzyMongoRepository.class.getSimpleName()); + } + else { + autoImplInterfaces.add(itf); + } + return this; + } + + @Override + public EzyRepositoriesImplementor repositoryInterfaces(Class... itfs) { + return repositoryInterfaces(Sets.newHashSet(itfs)); + } + + @Override + public EzyRepositoriesImplementor repositoryInterfaces(Iterable> itfs) { + itfs.forEach(this::repositoryInterface); + return this; + } + + @Override + public Map, Object> implement(Object template) { + Map, Object> repositories = new ConcurrentHashMap<>(); + for(Class itf : autoImplInterfaces) { + Object repo = implementRepoInterface(itf, template); + repositories.put(itf, repo); + } + return repositories; + } + + private Object implementRepoInterface(Class itf, Object template) { + EzySimpleRepositoryImplementor implementor = newRepoImplementor(itf); + return implementor.implement(template); + } + + protected abstract EzySimpleRepositoryImplementor newRepoImplementor(Class itf); + + private Set> getRepoInterfaces(String packageName) { + return EzyPackages.getExtendsClasses(packageName, EzyMongoRepository.class); + } + + private Collection> getAutoImplRepoInterfaces(String packageName) { + Set> classes = getRepoInterfaces(packageName); + return EzyLists.filter(classes, this::isAutoImplRepoInterface); + } + + private boolean isAutoImplRepoInterface(Class clazz) { + return clazz.isAnnotationPresent(EzyAutoImpl.class) && + Modifier.isPublic(clazz.getModifiers()) && + Modifier.isInterface(clazz.getModifiers()); + + } + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoryImplementor.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoryImplementor.java new file mode 100644 index 00000000..2d6f9232 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/bean/EzySimpleRepositoryImplementor.java @@ -0,0 +1,89 @@ +package com.tvd12.ezyfoxserver.mongodb.bean; + +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicInteger; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyMethods; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtNewMethod; + +public abstract class EzySimpleRepositoryImplementor { + + private final EzyClass clazz; + + protected static final AtomicInteger COUNT = new AtomicInteger(0); + + public EzySimpleRepositoryImplementor(Class clazz) { + this(new EzyClass(clazz)); + } + + public EzySimpleRepositoryImplementor(EzyClass clazz) { + this.clazz = clazz; + } + + public Object implement(Object template) { + try { + return doimplement(template); + } + catch(Exception e) { + throw new IllegalStateException(e); + } + } + + @SuppressWarnings("rawtypes") + protected Object doimplement(Object template) throws Exception { + ClassPool pool = ClassPool.getDefault(); + String implClassName = getImplClassName(); + CtClass implClass = pool.makeClass(implClassName); + EzyClass superClass = new EzyClass(getSuperClass()); + Class[] idAndEntityTypes = getIdAndEntityTypes(); + Class entityType = idAndEntityTypes[1]; + String getEntityTypeMethodContent = makeGetEntityTypeMethodContent(entityType); + implClass.addMethod(CtNewMethod.make(getEntityTypeMethodContent, implClass)); + implClass.setInterfaces(new CtClass[] { pool.get(clazz.getName()) }); + implClass.setSuperclass(pool.get(superClass.getName())); + Class answerClass = implClass.toClass(); + implClass.detach(); + Object repo = answerClass.newInstance(); + setRepoComponent(repo, template); + return repo; + } + + protected abstract void setRepoComponent(Object repo, Object template); + + @SuppressWarnings("rawtypes") + protected String makeGetEntityTypeMethodContent(Class entityType) { + return new EzyFunction(getEntityTypeMethod()) + .body() + .append(new EzyInstruction("\t", "\n") + .answer() + .clazz(entityType, true)) + .function() + .toString(); + } + + protected EzyMethod getEntityTypeMethod() { + Method method = EzyMethods.getMethod(getSuperClass(), "getEntityType"); + return new EzyMethod(method); + } + + protected abstract Class getSuperClass(); + + protected String getImplClassName() { + return clazz.getName() + "$EzyMongoRepository$EzyAutoImpl$" + COUNT.incrementAndGet(); + } + + @SuppressWarnings("rawtypes") + protected Class[] getIdAndEntityTypes() { + return EzyGenerics.getGenericInterfacesArguments(clazz.getClazz(), EzyMongoRepository.class, 2); + } + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyFileMongoClientLoader.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyFileMongoClientLoader.java new file mode 100644 index 00000000..c898d39b --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyFileMongoClientLoader.java @@ -0,0 +1,68 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.mongodb.loader; + +import java.io.File; +import java.io.FileInputStream; +import java.util.Map; +import java.util.Properties; + +import com.mongodb.MongoClient; +import com.tvd12.properties.file.reader.BaseFileReader; + + + +/** + * @author dung.tv@zinza.com.vn + * + */ +public class EzyFileMongoClientLoader extends EzyPropertiesMongoClientLoader { + + private File file; + + public static MongoClient load(File file) { + return new EzyFileMongoClientLoader() + .file(file) + .load(); + } + + public static MongoClient load(String filePath) { + return load(new File(filePath)); + } + + public EzyFileMongoClientLoader file(File file) { + this.file = file; + return this; + } + + public EzyFileMongoClientLoader filePath(String filePath) { + return file(new File(filePath)); + } + + @SuppressWarnings({ "rawtypes" }) + @Override + public EzyFileMongoClientLoader properties(Map map) { + return (EzyFileMongoClientLoader) super.properties(map); + } + + @Override + public EzyFileMongoClientLoader property(String name, Object value) { + return (EzyFileMongoClientLoader) super.property(name, value); + } + + @Override + protected void preload() { + getLogger().info("load mongo client config from file: {}", file.getAbsolutePath()); + this.properties.putAll(loadInputStream()); + } + + private Properties loadInputStream() { + try { + return new BaseFileReader().loadInputStream(new FileInputStream(file)); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + } + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyInputStreamMongoClientLoader.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyInputStreamMongoClientLoader.java new file mode 100644 index 00000000..5d5731cd --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyInputStreamMongoClientLoader.java @@ -0,0 +1,47 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.mongodb.loader; + +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; + +import com.tvd12.properties.file.reader.BaseFileReader; + + +/** + * + * @author tavandung12 + * + */ +public class EzyInputStreamMongoClientLoader extends EzyPropertiesMongoClientLoader { + + private InputStream inputStream; + + public EzyInputStreamMongoClientLoader inputStream(InputStream inputStream) { + this.inputStream = inputStream; + return this; + } + + @SuppressWarnings({ "rawtypes" }) + @Override + public EzyInputStreamMongoClientLoader properties(Map map) { + return (EzyInputStreamMongoClientLoader) super.properties(map); + } + + @Override + public EzyInputStreamMongoClientLoader property(String name, Object value) { + return (EzyInputStreamMongoClientLoader) super.property(name, value); + } + + @Override + protected void preload() { + this.properties.putAll(loadInputStream()); + } + + private Properties loadInputStream() { + return new BaseFileReader().loadInputStream(inputStream); + } + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyMongoClientLoader.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyMongoClientLoader.java new file mode 100644 index 00000000..c62ce347 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyMongoClientLoader.java @@ -0,0 +1,24 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.mongodb.loader; + +import com.mongodb.MongoClient; + +/** + * @author dung.tv@zinza.com.vn + * + */ +public interface EzyMongoClientLoader { + + String URI = "database.mongo.uri"; + String HOST = "database.mongo.host"; + String PORT = "database.mongo.port"; + String USERNAME = "database.mongo.username"; + String PASSWORD = "database.mongo.password"; + String DATABASE = "database.mongo.database"; + String COLLECTION = "database.mongo.collection"; + + MongoClient load(); + +} diff --git a/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyPropertiesMongoClientLoader.java b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyPropertiesMongoClientLoader.java new file mode 100644 index 00000000..4d1ec174 --- /dev/null +++ b/ezyfox-server-mongodb/src/main/java/com/tvd12/ezyfoxserver/mongodb/loader/EzyPropertiesMongoClientLoader.java @@ -0,0 +1,91 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.mongodb.loader; + +import java.util.Map; +import java.util.Properties; + +import com.google.common.collect.Lists; +import com.mongodb.MongoClient; +import com.mongodb.MongoCredential; +import com.mongodb.ServerAddress; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +/** + * @author dung.tv@zinza.com.vn + * + */ +public class EzyPropertiesMongoClientLoader + extends EzyLoggable + implements EzyMongoClientLoader { + + protected Properties properties; + + public EzyPropertiesMongoClientLoader() { + this.properties = new Properties(); + } + + public static MongoClient load(Properties properties) { + return new EzyPropertiesMongoClientLoader() + .properties(properties) + .load(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public EzyPropertiesMongoClientLoader properties(Map map) { + this.properties.putAll(map); + return this; + } + + public EzyPropertiesMongoClientLoader property(String name, Object value) { + this.properties.put(name, value); + return this; + } + + /* (non-Javadoc) + * @see com.lagente.base.db.util.MongoClientLoader#load() + */ + @Override + public MongoClient load() { + this.preload(); + return this.createMongoClient(); + } + + protected void preload() { + } + + protected MongoClient createMongoClient() { + return new MongoClient( + new ServerAddress(getHost(), getPort()), + Lists.newArrayList(createCredential())); + } + + protected MongoCredential createCredential() { + return MongoCredential.createCredential( + getUsername(), + getDatabase(), + getPassword().toCharArray()); + } + + protected String getHost() { + return (String) properties.get(EzyMongoClientLoader.HOST); + } + + protected int getPort() { + return Integer.valueOf((String) properties.get(EzyMongoClientLoader.PORT)); + } + + protected String getUsername() { + return (String) properties.get(EzyMongoClientLoader.USERNAME); + } + + protected String getPassword(){ + return (String) properties.get(EzyMongoClientLoader.PASSWORD); + } + + protected String getDatabase() { + return (String) properties.get(EzyMongoClientLoader.DATABASE); + } + +} diff --git a/ezyfox-server-mongodb/src/test/resources/AllTests.tng.xml b/ezyfox-server-mongodb/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..6bc4857a --- /dev/null +++ b/ezyfox-server-mongodb/src/test/resources/AllTests.tng.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-mongodb/src/test/resources/mongodb_config.properties b/ezyfox-server-mongodb/src/test/resources/mongodb_config.properties new file mode 100644 index 00000000..d8c3d5c9 --- /dev/null +++ b/ezyfox-server-mongodb/src/test/resources/mongodb_config.properties @@ -0,0 +1,5 @@ +database.mongo.host=127.0.0.1 +database.mongo.port=27017 +database.mongo.database=test +database.mongo.username=root +database.mongo.password=123456 \ No newline at end of file diff --git a/ezyfox-server-monitor/pom.xml b/ezyfox-server-monitor/pom.xml new file mode 100644 index 00000000..59fb21be --- /dev/null +++ b/ezyfox-server-monitor/pom.xml @@ -0,0 +1,9 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-monitor + \ No newline at end of file diff --git a/ezyfox-server-monitor/src/test/resources/AllTests.tng.xml b/ezyfox-server-monitor/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..139c152d --- /dev/null +++ b/ezyfox-server-monitor/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-morphia/assembly.xml b/ezyfox-server-morphia/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-morphia/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-morphia/pom.xml b/ezyfox-server-morphia/pom.xml new file mode 100644 index 00000000..8e8c0464 --- /dev/null +++ b/ezyfox-server-morphia/pom.xml @@ -0,0 +1,37 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-morphia + ezyfox-server-morphia + 1.0.0 + http://maven.apache.org + + 1.3.2 + 1.0.0 + 1.0.0 + + + + com.tvd12 + ezyfox-server-mongodb + ${ezy.mongodb.version} + + + org.mongodb.morphia + morphia + ${morphia.version} + + + com.tvd12 + ezyfox-server-bean + ${ezy.bean.version} + test + + + diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDataStoreBuilder.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDataStoreBuilder.java new file mode 100644 index 00000000..986a28bf --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDataStoreBuilder.java @@ -0,0 +1,81 @@ +package com.tvd12.ezyfoxserver.morphia; + +import java.lang.annotation.Annotation; +import java.util.HashSet; +import java.util.Set; + +import org.mongodb.morphia.Datastore; +import org.mongodb.morphia.Morphia; +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.mapping.Mapper; + +import com.google.common.collect.Sets; +import com.mongodb.MongoClient; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings("rawtypes") +public class EzyDataStoreBuilder + extends EzyLoggable + implements EzyBuilder { + + protected String databaseName; + protected MongoClient mongoClient; + protected Set entityClasses; + + public EzyDataStoreBuilder() { + this.entityClasses = new HashSet<>(); + } + + public static EzyDataStoreBuilder dataStoreBuilder() { + return new EzyDataStoreBuilder(); + } + + public EzyDataStoreBuilder databaseName(String databaseName) { + this.databaseName = databaseName; + return this; + } + + public EzyDataStoreBuilder mongoClient(MongoClient mongoClient) { + this.mongoClient = mongoClient; + return this; + } + + public EzyDataStoreBuilder scan(String packageName) { + this.entityClasses.addAll(getAnnotatedClasses(packageName, Entity.class)); + return this; + } + + public EzyDataStoreBuilder addEntityClass(Class entityClass) { + this.entityClasses.add(entityClass); + return this; + } + + public EzyDataStoreBuilder addEntityClasses(Class... classes) { + return addEntityClasses(Sets.newHashSet(classes)); + } + + public EzyDataStoreBuilder addEntityClasses(Iterable classes) { + classes.forEach(this::addEntityClass); + return this; + } + + @Override + public Datastore build() { + Mapper mapper = new Mapper(); + Datastore datastore = newDataStore(mapper); + return datastore; + } + + private Datastore newDataStore(Mapper mapper) { + Morphia morphia = new Morphia(mapper, entityClasses); + return morphia.createDatastore(mongoClient, databaseName); + } + + private Set> getAnnotatedClasses( + String packageName, Class annClass) { + return EzyPackages.getAnnotatedClasses(packageName, annClass); + } + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDatastoreAware.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDatastoreAware.java new file mode 100644 index 00000000..55649f7e --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/EzyDatastoreAware.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.morphia; + +import org.mongodb.morphia.Datastore; + +public interface EzyDatastoreAware { + + void setDatastore(Datastore datastore); + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/bean/EzyMorphiaRepositories.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/bean/EzyMorphiaRepositories.java new file mode 100644 index 00000000..3932c3b7 --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/bean/EzyMorphiaRepositories.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.morphia.bean; + +import com.tvd12.ezyfoxserver.morphia.impl.EzyMorphiaRepositoriesImplementor; + +public final class EzyMorphiaRepositories { + + private EzyMorphiaRepositories() { + } + + public static EzyMorphiaRepositoriesImplementor newRepositoriesImplementor() { + return new EzyMorphiaRepositoriesImplementor(); + } + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoriesImplementor.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoriesImplementor.java new file mode 100644 index 00000000..dd063e73 --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoriesImplementor.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.morphia.impl; + +import com.tvd12.ezyfoxserver.mongodb.bean.EzySimpleRepositoriesImplementor; +import com.tvd12.ezyfoxserver.mongodb.bean.EzySimpleRepositoryImplementor; + +public class EzyMorphiaRepositoriesImplementor + extends EzySimpleRepositoriesImplementor { + + @Override + protected EzySimpleRepositoryImplementor newRepoImplementor(Class itf) { + return new EzyMorphiaRepositoryImplementor(itf); + } + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoryImplementor.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoryImplementor.java new file mode 100644 index 00000000..8aea755b --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/impl/EzyMorphiaRepositoryImplementor.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.morphia.impl; + +import org.mongodb.morphia.Datastore; + +import com.tvd12.ezyfoxserver.mongodb.bean.EzySimpleRepositoryImplementor; +import com.tvd12.ezyfoxserver.morphia.EzyDatastoreAware; +import com.tvd12.ezyfoxserver.morphia.repository.EzyDatastoreRepository; + +public class EzyMorphiaRepositoryImplementor extends EzySimpleRepositoryImplementor { + + public EzyMorphiaRepositoryImplementor(Class clazz) { + super(clazz); + } + + @Override + protected void setRepoComponent(Object repo, Object template) { + Datastore datastore = (Datastore)template; + EzyDatastoreAware datastoreAware = (EzyDatastoreAware)repo; + datastoreAware.setDatastore(datastore); + } + + @Override + protected Class getSuperClass() { + return EzyDatastoreRepository.class; + } + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleFindAndModifyOptions.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleFindAndModifyOptions.java new file mode 100644 index 00000000..55838afe --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleFindAndModifyOptions.java @@ -0,0 +1,63 @@ +package com.tvd12.ezyfoxserver.morphia.query.impl; + +import java.util.concurrent.TimeUnit; + +import org.mongodb.morphia.FindAndModifyOptions; + +import com.tvd12.ezyfoxserver.database.query.EzyFindAndModifyOptions; + +public final class EzySimpleFindAndModifyOptions implements EzyFindAndModifyOptions { + + private final FindAndModifyOptions options; + + public EzySimpleFindAndModifyOptions(FindAndModifyOptions options) { + this.options = options; + } + + @Override + public boolean isRemove() { + return options.isRemove(); + } + + @Override + public EzyFindAndModifyOptions remove(boolean remove) { + options.remove(remove); + return this; + } + + @Override + public boolean isUpsert() { + return options.isUpsert(); + } + + @Override + public EzyFindAndModifyOptions upsert(boolean upsert) { + options.upsert(upsert); + return this; + } + + @Override + public boolean isReturnNew() { + return options.isReturnNew(); + } + + @Override + public EzyFindAndModifyOptions returnNew(boolean returnNew) { + options.returnNew(returnNew); + return this; + } + + @Override + public long getMaxTime(TimeUnit timeUnit) { + return options.getMaxTime(timeUnit); + } + + @Override + public EzyFindAndModifyOptions maxTime(long maxTime, TimeUnit timeUnit) { + options.maxTime(maxTime, timeUnit); + return this; + } + + + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimplePushOptions.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimplePushOptions.java new file mode 100644 index 00000000..488755b2 --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimplePushOptions.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.morphia.query.impl; + +import org.mongodb.morphia.query.PushOptions; + +import com.tvd12.ezyfoxserver.database.query.EzyPushOptions; + +public final class EzySimplePushOptions implements EzyPushOptions { + + private final PushOptions options; + + public EzySimplePushOptions(PushOptions options) { + this.options = options; + } + + @Override + public EzyPushOptions position(int position) { + options.position(position); + return this; + } + + @Override + public EzyPushOptions slice(int slice) { + options.slice(slice); + return this; + } + + @Override + public EzyPushOptions sort(int sort) { + options.sort(sort); + return this; + } + + @Override + public EzyPushOptions sort(String field, int direction) { + options.sort(field, direction); + return this; + } + + + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleUpdateOperations.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleUpdateOperations.java new file mode 100644 index 00000000..5023f975 --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/query/impl/EzySimpleUpdateOperations.java @@ -0,0 +1,165 @@ +package com.tvd12.ezyfoxserver.morphia.query.impl; + +import java.util.List; + +import org.mongodb.morphia.query.PushOptions; +import org.mongodb.morphia.query.UpdateOperations; + +import com.tvd12.ezyfoxserver.database.query.EzyPushOptions; +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; + +public final class EzySimpleUpdateOperations implements EzyUpdateOperations { + + private final UpdateOperations operations; + + public EzySimpleUpdateOperations(UpdateOperations operations) { + this.operations = operations; + } + + @Override + public EzyUpdateOperations addToSet(String field, Object value) { + operations.addToSet(field, value); + return this; + } + + @Override + public EzyUpdateOperations addToSet(String field, List values) { + operations.addToSet(field, values); + return this; + } + + @Override + public EzyUpdateOperations dec(String field) { + operations.dec(field); + return this; + } + + @Override + public EzyUpdateOperations dec(String field, Number value) { + operations.dec(field, value); + return this; + } + + @Override + public EzyUpdateOperations disableValidation() { + operations.disableValidation(); + return this; + } + + @Override + public EzyUpdateOperations enableValidation() { + operations.enableValidation(); + return this; + } + + @Override + public EzyUpdateOperations inc(String field) { + operations.inc(field); + return this; + } + + @Override + public EzyUpdateOperations inc(String field, Number value) { + operations.inc(field, value); + return this; + } + + @Override + public EzyUpdateOperations isolated() { + operations.isolated(); + return this; + } + + @Override + public boolean isIsolated() { + return operations.isIsolated(); + } + + @Override + public EzyUpdateOperations max(String field, Number value) { + operations.max(field, value); + return this; + } + + @Override + public EzyUpdateOperations min(String field, Number value) { + operations.min(field, value); + return this; + } + + @Override + public EzyUpdateOperations push(String field, Object value) { + operations.push(field, value); + return this; + } + + @Override + public EzyUpdateOperations push(String field, Object value, EzyApply options) { + PushOptions real = new PushOptions(); + EzyPushOptions proxy = new EzySimplePushOptions(real); + options.apply(proxy); + operations.push(field, value, real); + return this; + } + + @Override + public EzyUpdateOperations push(String field, List values) { + operations.push(field, values); + return this; + } + + @Override + public EzyUpdateOperations push(String field, List values, EzyApply options) { + PushOptions real = new PushOptions(); + EzyPushOptions proxy = new EzySimplePushOptions(real); + options.apply(proxy); + operations.push(field, values, real); + return this; + } + + @Override + public EzyUpdateOperations removeAll(String field, Object value) { + operations.removeAll(field, value); + return this; + } + + @Override + public EzyUpdateOperations removeAll(String field, List values) { + operations.removeAll(field, values); + return this; + } + + @Override + public EzyUpdateOperations removeFirst(String field) { + operations.removeFirst(field); + return this; + } + + @Override + public EzyUpdateOperations removeLast(String field) { + operations.removeLast(field); + return this; + } + + @Override + public EzyUpdateOperations set(String field, Object value) { + operations.set(field, value); + return this; + } + + @Override + public EzyUpdateOperations setOnInsert(String field, Object value) { + operations.setOnInsert(field, value); + return this; + } + + @Override + public EzyUpdateOperations unset(String field) { + operations.unset(field); + return this; + } + + + +} diff --git a/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/repository/EzyDatastoreRepository.java b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/repository/EzyDatastoreRepository.java new file mode 100644 index 00000000..6f5fa729 --- /dev/null +++ b/ezyfox-server-morphia/src/main/java/com/tvd12/ezyfoxserver/morphia/repository/EzyDatastoreRepository.java @@ -0,0 +1,205 @@ +package com.tvd12.ezyfoxserver.morphia.repository; + +import java.util.Collection; +import java.util.List; + +import org.mongodb.morphia.Datastore; +import org.mongodb.morphia.DeleteOptions; +import org.mongodb.morphia.FindAndModifyOptions; +import org.mongodb.morphia.UpdateOptions; +import org.mongodb.morphia.query.FindOptions; +import org.mongodb.morphia.query.Query; +import org.mongodb.morphia.query.UpdateOperations; + +import com.mongodb.WriteResult; +import com.tvd12.ezyfoxserver.database.query.EzyFindAndModifyOptions; +import com.tvd12.ezyfoxserver.database.query.EzyUpdateOperations; +import com.tvd12.ezyfoxserver.function.EzyApply; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.EzyDatastoreAware; +import com.tvd12.ezyfoxserver.morphia.query.impl.EzySimpleFindAndModifyOptions; +import com.tvd12.ezyfoxserver.morphia.query.impl.EzySimpleUpdateOperations; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +public abstract class EzyDatastoreRepository + extends EzyLoggable + implements EzyMongoRepository, EzyDatastoreAware { + + @Setter + protected Datastore datastore; + + protected abstract Class getEntityType(); + + @Override + public long count() { + return datastore.getCount(getEntityType()); + } + + @Override + public void save(E entity) { + datastore.save(entity); + } + + @Override + public void save(Iterable entities) { + datastore.save(entities); + } + + @Override + public E findById(I id) { + return findByField("_id", id); + } + + @Override + public E findByField(String field, Object value) { + return newQuery(field, value).get(); + } + + @Override + public List findListByIds(Collection ids) { + return newQuery().field("_id").in(ids).asList(); + } + + @Override + public List findListByField(String field, Object value) { + return newQuery(field, value).asList(); + } + + @Override + public List findListByField(String field, Object value, int skip, int limit) { + FindOptions options = new FindOptions().skip(skip).limit(limit); + return newQuery(field, value).asList(options); + } + + @Override + public List findAll() { + return newQuery().asList(); + } + + @Override + public List findAll(int skip, int limit) { + FindOptions options = new FindOptions().skip(skip).limit(limit); + return newQuery().asList(options); + } + + @Override + public void updateOneById(I id, E entity) { + updateOneById(id, entity, false); + } + + @Override + public void updateOneById(I id, E entity, boolean upsert) { + datastore.updateFirst(newQuery("_id", id), entity, upsert); + } + + @Override + public void updateOneById(I id, EzyApply> operations) { + updateOneById(id, operations, false); + } + + @Override + public void updateOneById(I id, EzyApply> operations, boolean upsert) { + updateOneByQuery(newQuery("_id", id), operations, upsert); + } + + @Override + public void updateOneByField(String field, Object value, E entity) { + updateOneByField(field, value, entity, false); + } + + @Override + public void updateOneByField(String field, Object value, E entity, boolean upsert) { + datastore.updateFirst(newQuery(field, value), entity, upsert); + } + + @Override + public void updateOneByField(String field, Object value, EzyApply> operations) { + updateOneByField(field, value, operations, false); + } + + @Override + public void updateOneByField(String field, Object value, EzyApply> operations, boolean upsert) { + updateOneByQuery(newQuery(field, value), operations, upsert); + } + + @Override + public void updateManyByField(String field, Object value, EzyApply> operations) { + UpdateOperations realOperations = datastore.createUpdateOperations(getEntityType()); + EzyUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + operations.apply(proxyOperations); + UpdateOptions realOptions = new UpdateOptions().multi(true).upsert(false); + datastore.update(newQuery(field, value), realOperations, realOptions); + } + + private void updateOneByQuery(Query query, EzyApply> operations, boolean upsert) { + UpdateOperations realOperations = datastore.createUpdateOperations(getEntityType()); + EzyUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + operations.apply(proxyOperations); + datastore.updateFirst(query, realOperations, upsert); + } + + @Override + public E findAndModifyById(I id, EzyApply> operations) { + return findAndModifyByQuery(newQuery("_id", id), operations); + } + + @Override + public E findAndModifyById(I id, EzyApply> operations, EzyApply options) { + return findAndModifyByQuery(newQuery("_id", id), operations, options); + } + + @Override + public E findAndModifyByField(String field, Object value, EzyApply> operations) { + return findAndModifyByQuery(newQuery(field, value), operations); + } + + @Override + public E findAndModifyByField(String field, Object value, EzyApply> operations, + EzyApply options) { + return findAndModifyByQuery(newQuery(field, value), operations, options); + } + + private E findAndModifyByQuery(Query query, EzyApply> operations) { + UpdateOperations realOperations = datastore.createUpdateOperations(getEntityType()); + EzyUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + operations.apply(proxyOperations); + return datastore.findAndModify(query, realOperations); + } + + private E findAndModifyByQuery(Query query, EzyApply> operations, EzyApply options) { + UpdateOperations realOperations = datastore.createUpdateOperations(getEntityType()); + EzyUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + FindAndModifyOptions realOptions = new FindAndModifyOptions(); + EzyFindAndModifyOptions proxyOptions = new EzySimpleFindAndModifyOptions(realOptions); + operations.apply(proxyOperations); + options.apply(proxyOptions); + return datastore.findAndModify(query, realOperations, realOptions); + } + + @Override + public void delete(I id) { + datastore.delete(newQuery("_id", id), new DeleteOptions().copy()); + } + + @Override + public int deleteByIds(Collection ids) { + WriteResult result = datastore.delete(newQuery().field("_id").in(ids), new DeleteOptions().copy()); + return result.getN(); + } + + @Override + public int deleteAll() { + WriteResult result = datastore.delete(newQuery()); + return result.getN(); + } + + protected Query newQuery() { + return datastore.createQuery(getEntityType()); + } + + protected Query newQuery(String field, Object value) { + return newQuery().field(field).equal(value); + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/BaseMongoDBTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/BaseMongoDBTest.java new file mode 100644 index 00000000..148e20f8 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/BaseMongoDBTest.java @@ -0,0 +1,69 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.io.InputStream; +import java.util.Map; + +import org.mongodb.morphia.Datastore; + +import com.mongodb.MongoClient; +import com.tvd12.ezyfoxserver.bean.EzyBeanContext; +import com.tvd12.ezyfoxserver.bean.EzyBeanContextBuilder; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.mongodb.bean.EzyRepositoriesImplementor; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyInputStreamMongoClientLoader; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyMongoClientLoader; +import com.tvd12.ezyfoxserver.morphia.EzyDataStoreBuilder; +import com.tvd12.ezyfoxserver.morphia.bean.EzyMorphiaRepositories; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.stream.EzyAnywayInputStreamLoader; +import com.tvd12.test.base.BaseTest; + +public class BaseMongoDBTest extends BaseTest { + + protected static final MongoClient MONGO_CLIENT = newMongoClient(); + protected static final Datastore DATASTORE = newDataStore(); + protected static final EzyBeanContext BEAN_CONTEXT = newBeanContext(); + + static { + Runtime.getRuntime().addShutdownHook(new Thread(() -> MONGO_CLIENT.close())); + } + + private static EzyBeanContext newBeanContext() { + EzyBeanContextBuilder builder = EzyBeanContext.builder() + .addSingleton("datastore", DATASTORE) + .scan("com.tvd12.ezyfoxserver.morphia.testing.repo") + .scan("com.tvd12.ezyfoxserver.morphia.testing.service"); + EzyRepositoriesImplementor implementor = EzyMorphiaRepositories.newRepositoriesImplementor() + .scan("com.tvd12.ezyfoxserver.morphia.testing.repo", "com.tvd12.ezyfoxserver.morphia.testing.repo1"); + Map, Object> repos = implementor.implement(DATASTORE); + for(Class key : repos.keySet()) { + builder.addSingleton(EzyClasses.getVariableName(key), repos.get(key)); + } + return builder.build(); + } + + private static Datastore newDataStore() { + return EzyDataStoreBuilder.dataStoreBuilder() + .mongoClient(MONGO_CLIENT) + .databaseName("test") + .scan("com.tvd12.ezyfoxserver.morphia.testing.data") + .addEntityClasses(Pig.class, Duck.class) + .build(); + } + + private static MongoClient newMongoClient() { + return new EzyInputStreamMongoClientLoader() + .inputStream(getMongoConfigInputStream()) + .property(EzyMongoClientLoader.DATABASE, "test") + .properties(EzyMaps.newHashMap(EzyMongoClientLoader.DATABASE, "test")) + .load(); + } + + private static InputStream getMongoConfigInputStream() { + return EzyAnywayInputStreamLoader.builder() + .context(BaseMongoDBTest.class) + .build() + .load("mongodb_config.properties"); + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/CombineTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/CombineTest.java new file mode 100644 index 00000000..772cdc28 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/CombineTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.repo.CatRepo; + +public class CombineTest extends BaseMongoDBTest { + + @Test + public void test() { + CatRepo repo = (CatRepo) BEAN_CONTEXT.getBean(CatRepo.class); + repo.save(new Cat()); + } + + + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Duck.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Duck.java new file mode 100644 index 00000000..a4dae0bf --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Duck.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@EqualsAndHashCode +@Entity(value = "ezyfox.mongodb.testing.duck", noClassnameStored = true) +public class Duck { + + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "cat#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String fixedValue = "fixedValue"; + + public Duck(Long id) { + this.id = id; + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDataStoreBuilderTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDataStoreBuilderTest.java new file mode 100644 index 00000000..b716113c --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDataStoreBuilderTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.data.Person; + +public class EzyDataStoreBuilderTest extends BaseMongoDBTest { + + @Test + public void test() { + DATASTORE.save(new Cat()); + DATASTORE.save(new Person()); + } + + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDatastoreRepositoryTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDatastoreRepositoryTest.java new file mode 100644 index 00000000..b565bd7e --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyDatastoreRepositoryTest.java @@ -0,0 +1,97 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.repo.CatRepo; +import com.tvd12.ezyfoxserver.morphia.testing.repo.DuckRepo; + +public class EzyDatastoreRepositoryTest extends BaseMongoDBTest { + + @Test + public void test() { + CatRepo repo = (CatRepo) BEAN_CONTEXT.getBean(CatRepo.class); + System.out.println("cat#count: " + repo.count()); + repo.deleteAll(); + assert repo.count() == 0; + Cat cat1 = new Cat(); + Cat cat2 = new Cat(); + repo.save(Lists.newArrayList(cat1, cat2)); + assert cat1.equals(repo.findById(cat1.getId())); + assert repo.findListByIds(Sets.newHashSet(cat1.getId(), cat2.getId())).size() == 2; + assert repo.findListByField("fixedValue", "fixedValue").size() == 2; + assert repo.findListByField("fixedValue", "fixedValue", 0, 1).size() == 1; + assert repo.findAll().size() == 2; + assert repo.findAll(0, 1).size() == 1; + cat1.setName("updated name"); + repo.updateOneById(cat1.getId(), cat1); + repo.delete(cat2.getId()); + assert repo.count() == 1; + repo.save(cat2); + assert repo.count() == 2; + repo.deleteByIds(Lists.newArrayList(cat2.getId())); + assert repo.count() == 1; + Cat cat3 = new Cat(); + cat3.setId(cat1.getId() + 1); + + repo.findAndModifyById(cat1.getId(), + operations -> { + operations + .set("name", "cat#1#findAndModify") + .set("fixedValue", "fixedValue"); + } + ); + + repo.findAndModifyById(cat3.getId(), + operations -> { + operations + .set("name", "cat#3#findAndModify") + .set("fixedValue", "fixedValue"); + }, + options -> { + options.upsert(true); + } + ); + + DuckRepo duckRepo = (DuckRepo) BEAN_CONTEXT.getBean(DuckRepo.class); + duckRepo.deleteAll(); + Duck duck1 = new Duck(); + duck1.setName("duck1"); + duckRepo.save(duck1); + duckRepo.updateOneById(duck1.getId(), op -> op.set("name", "duck1#hasupdated")); + + Duck duck2 = new Duck(duck1.getId() + 1); + duck2.setName("duck2"); + duckRepo.save(duck2); + duck2.setName("duck2#updated"); + duckRepo.updateOneByField("name", "duck2", duck2); + + Duck duck3 = new Duck(duck2.getId() + 1); + duck3.setName("duck3"); + duckRepo.save(duck3); + duckRepo.updateOneByField("name", "duck3", op -> op.set("name", "duck3#updated")); + + Duck duck4 = new Duck(duck3.getId() + 1); + duck4.setName("duck4"); + + duckRepo.findAndModifyByField("name", "duck4", + operations -> operations + .set("_id", duck4.getId()) + .set("name", duck4.getName()) + .set("fixedValue", "duck4FixedValue"), + options -> options + .upsert(true)); + + Duck duck5 = new Duck(duck4.getId() + 1); + duck5.setName("duck5"); + duckRepo.save(duck5); + duckRepo.findAndModifyByField("name", "duck5", + operations -> operations.set("name", "duck5#updated")); + + duckRepo.updateManyByField("fixedValue", "fixedValue", op -> op.set("fixedValue", "newFixedValue")); + + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyFileMongoClientLoaderTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyFileMongoClientLoaderTest.java new file mode 100644 index 00000000..c1d06b64 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyFileMongoClientLoaderTest.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyFileMongoClientLoader; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyMongoClientLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyFileMongoClientLoaderTest extends BaseTest { + + @Test + public void test() { + EzyFileMongoClientLoader loader = new EzyFileMongoClientLoader() + .filePath("src/test/resources/mongodb_config.properties") + .property(EzyMongoClientLoader.DATABASE, "test") + .properties(EzyMaps.newHashMap(EzyMongoClientLoader.DATABASE, "test")); + loader.load().close(); + EzyFileMongoClientLoader.load("src/test/resources/mongodb_config.properties").close(); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyFileMongoClientLoader.load("src/test/resources/mongodb_config.propertieszzzz"); + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyPropertiesMongoClientLoaderTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyPropertiesMongoClientLoaderTest.java new file mode 100644 index 00000000..15b19283 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyPropertiesMongoClientLoaderTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.util.Properties; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.mongodb.loader.EzyMongoClientLoader; +import com.tvd12.ezyfoxserver.mongodb.loader.EzyPropertiesMongoClientLoader; +import com.tvd12.test.base.BaseTest; + +public class EzyPropertiesMongoClientLoaderTest extends BaseTest { + + @Test + public void test() { + Properties properties = new Properties(); + properties.setProperty(EzyMongoClientLoader.HOST, "127.0.0.1"); + properties.setProperty(EzyMongoClientLoader.PORT, "27017"); + properties.setProperty(EzyMongoClientLoader.USERNAME, "root"); + properties.setProperty(EzyMongoClientLoader.PASSWORD, "123456"); + properties.setProperty(EzyMongoClientLoader.DATABASE, "test"); + EzyPropertiesMongoClientLoader.load(properties).close(); + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyRepositoryImplementorTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyRepositoryImplementorTest.java new file mode 100644 index 00000000..9623045c --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzyRepositoryImplementorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.morphia.impl.EzyMorphiaRepositoryImplementor; + +public class EzyRepositoryImplementorTest extends BaseMongoDBTest { + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test() { + new EzyMorphiaRepositoryImplementor(ClassA.class).implement(DATASTORE); + } + + public static class ClassA { + + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzySimpleRepositoriesImplementorTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzySimpleRepositoriesImplementorTest.java new file mode 100644 index 00000000..20dafd24 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/EzySimpleRepositoriesImplementorTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.impl.EzyMorphiaRepositoriesImplementor; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; + +public class EzySimpleRepositoriesImplementorTest extends BaseMongoDBTest { + + @Test + public void test() { + EzyMorphiaRepositoriesImplementor implementor = new EzyMorphiaRepositoriesImplementor(); + implementor.repositoryInterfaces(Object.class); + implementor.repositoryInterfaces(InterfaceA.class); + implementor.repositoryInterfaces(CatXRepo.class); + Map, Object> map = implementor.implement(DATASTORE); + assert map.containsKey(CatXRepo.class); + } + + public static interface InterfaceA { + + } + + public static interface CatXRepo extends EzyMongoRepository { + + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/GenericsTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/GenericsTest.java new file mode 100644 index 00000000..9f2a2876 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/GenericsTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Arrays; + +import com.tvd12.ezyfoxserver.database.repository.EzyEmptyRepository; + +public class GenericsTest { + + public static void main(String[] args) { + Type[] genericInterfaces = InterfaceB.class.getGenericInterfaces(); + for (Type genericInterface : genericInterfaces) { + if (genericInterface instanceof ParameterizedType) { + System.out.println(genericInterface); + Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments(); + for (Type genericType : genericTypes) { + System.out.println("Generic type: " + genericType); + } + Class clazz = (Class)((ParameterizedType)genericInterface).getRawType(); + System.out.println(Arrays.toString(clazz.getGenericInterfaces())); + } + } + } + + public static class ClassA { + } + + public static interface InterfaceA extends EzyEmptyRepository { + } + + public static interface InterfaceB extends InterfaceA, InterfaceC { + + } + + public static interface InterfaceC { + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Pig.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Pig.java new file mode 100644 index 00000000..497fb26a --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/Pig.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.morphia.testing; + +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@EqualsAndHashCode +@Entity(value = "ezyfox.mongodb.testing.pig", noClassnameStored = true) +public class Pig { + + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "cat#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String fixedValue = "fixedValue"; + + public Pig(Long id) { + this.id = id; + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Cat.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Cat.java new file mode 100644 index 00000000..1540da2c --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Cat.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.morphia.testing.data; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@EqualsAndHashCode +@Entity(value = "ezyfox.mongodb.testing.cat", noClassnameStored = true) +public class Cat { + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "cat#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String fixedValue = "fixedValue"; + private Set valueSet = new HashSet<>(); + public int age = 10; + private List kitties = new ArrayList<>(); + private List valueList = new ArrayList<>(); + private int free; + private String unset = "100"; + + public Cat(Long id) { + this.id = id; + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Chickend.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Chickend.java new file mode 100644 index 00000000..2e8b83fb --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Chickend.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.morphia.testing.data; + +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@Entity(value = "ezyfox.mongodb.testing.chicken", noClassnameStored = true) +public class Chickend { + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "cat#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + + public Chickend(Long id) { + this.id = id; + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Kitty.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Kitty.java new file mode 100644 index 00000000..e9493326 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Kitty.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.morphia.testing.data; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@EqualsAndHashCode +@Entity(value = "ezyfox.mongodb.testing.kitty", noClassnameStored = true) +public class Kitty { + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "cat#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String fixedValue = "fixedValue"; + private Set set = new HashSet<>(); + public int age = 10; + + public Kitty(Long id) { + this.id = id; + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Monkey.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Monkey.java new file mode 100644 index 00000000..7662c18a --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Monkey.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.morphia.testing.data; + +import java.util.concurrent.ThreadLocalRandom; + +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString +@NoArgsConstructor +@Entity(value = "ezyfox.mongodb.testing.monkey", noClassnameStored = true) +public class Monkey { + @Id + private Long id = (long) ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String name = "monkey#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + + public Monkey(Long id) { + this.id = id; + } +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Person.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Person.java new file mode 100644 index 00000000..7dc1047b --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/data/Person.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.morphia.testing.data; + +import java.io.Serializable; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import org.bson.types.ObjectId; +import org.mongodb.morphia.annotations.Entity; +import org.mongodb.morphia.annotations.Id; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +@Entity(value = "ezyfox.mongodb.testing.person", noClassnameStored = true) +public class Person implements Serializable { + private static final long serialVersionUID = 903502360552527690L; + + @Id + private ObjectId id; + private String name = "name#" + ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE); + private String password = UUID.randomUUID().toString(); + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperations2Test.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperations2Test.java new file mode 100644 index 00000000..933380c6 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperations2Test.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.morphia.testing.query; + +import java.util.concurrent.TimeUnit; + +import org.mongodb.morphia.FindAndModifyOptions; +import org.mongodb.morphia.query.UpdateOperations; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.morphia.query.impl.EzySimpleFindAndModifyOptions; +import com.tvd12.ezyfoxserver.morphia.query.impl.EzySimpleUpdateOperations; +import com.tvd12.ezyfoxserver.morphia.testing.BaseMongoDBTest; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.data.Kitty; + +public class EzySimpleUpdateOperations2Test extends BaseMongoDBTest { + + @Test + public void test() { + UpdateOperations realOperations = DATASTORE.createUpdateOperations(Cat.class); + EzySimpleUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + + proxyOperations.disableValidation(); + proxyOperations.enableValidation(); + proxyOperations.inc("age", 10); + assert !proxyOperations.isIsolated(); + proxyOperations.isolated(); + assert proxyOperations.isIsolated(); + proxyOperations.push("valueSet", Lists.newArrayList("e", "f")); + proxyOperations.push("kitties", new Kitty(100L), options -> options.sort("age", 1)); + proxyOperations.removeAll("valueList", Lists.newArrayList("a", "b", "c")); + proxyOperations.setOnInsert("free", 100); + proxyOperations.unset("unset"); + + + FindAndModifyOptions realOptions = new FindAndModifyOptions(); + EzySimpleFindAndModifyOptions proxyOptions = new EzySimpleFindAndModifyOptions(realOptions); + proxyOptions.upsert(true) + .maxTime(10, TimeUnit.SECONDS) + .remove(false) + .returnNew(true); + assert !proxyOptions.isRemove(); + assert proxyOptions.isReturnNew(); + assert proxyOptions.isUpsert(); + assert proxyOptions.getMaxTime(TimeUnit.SECONDS) == 10; + + Cat cat = new Cat(); + DATASTORE.delete(DATASTORE.createQuery(Cat.class)); + DATASTORE.findAndModify(DATASTORE.createQuery( + Cat.class).field("id").equal(cat.getId()), + realOperations, + realOptions); + + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperationsTest.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperationsTest.java new file mode 100644 index 00000000..978ed253 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/query/EzySimpleUpdateOperationsTest.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.morphia.testing.query; + +import org.mongodb.morphia.query.UpdateOperations; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.morphia.query.impl.EzySimpleUpdateOperations; +import com.tvd12.ezyfoxserver.morphia.testing.BaseMongoDBTest; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.data.Kitty; + +public class EzySimpleUpdateOperationsTest extends BaseMongoDBTest { + + @Test + public void test() { + UpdateOperations realOperations = DATASTORE.createUpdateOperations(Cat.class); + EzySimpleUpdateOperations proxyOperations = new EzySimpleUpdateOperations<>(realOperations); + + proxyOperations.addToSet("valueSet", "a"); + proxyOperations.addToSet("valueSet", Lists.newArrayList("b", "c")); + proxyOperations.dec("age"); + proxyOperations.dec("age", 3); + proxyOperations.disableValidation(); + proxyOperations.enableValidation(); + proxyOperations.inc("age"); + proxyOperations.inc("age", 10); + assert !proxyOperations.isIsolated(); + proxyOperations.isolated(); + assert proxyOperations.isIsolated(); + proxyOperations.max("age", 100); + proxyOperations.min("age", 0); + proxyOperations.push("valueSet", "d"); + proxyOperations.push("valueSet", Lists.newArrayList("e", "f")); + proxyOperations.push("age", Lists.newArrayList("g", "h"), options -> options.sort(1).slice(5).position(0)); + proxyOperations.push("kitties", new Kitty(100L), options -> options.sort("age", 1)); + proxyOperations.removeAll("valueList", "d"); + proxyOperations.removeAll("valueList", Lists.newArrayList("a", "b", "c")); + proxyOperations.removeFirst("valueList"); + proxyOperations.removeLast("valueList"); + proxyOperations.setOnInsert("free", 100); + proxyOperations.unset("unset"); + + + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/CatRepo.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/CatRepo.java new file mode 100644 index 00000000..acae8565 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/CatRepo.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; + +@EzyAutoImpl +public interface CatRepo extends EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/ChickendRepo.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/ChickendRepo.java new file mode 100644 index 00000000..03f4a62b --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/ChickendRepo.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.data.Chickend; + +@EzyAutoImpl +public interface ChickendRepo extends EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/DuckRepo.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/DuckRepo.java new file mode 100644 index 00000000..8f74a041 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/DuckRepo.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.Duck; + +@EzyAutoImpl +public interface DuckRepo extends EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/MonkeyRepo.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/MonkeyRepo.java new file mode 100644 index 00000000..b14fc9e5 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/MonkeyRepo.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo; + +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.data.Monkey; + +public interface MonkeyRepo extends EzyMongoRepository { + + void save2Monkey(Monkey monkey1, Monkey monkey2); + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try1.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try1.java new file mode 100644 index 00000000..7c7a4524 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try1.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo.autoimpl; + +import com.tvd12.ezyfoxserver.morphia.impl.EzyMorphiaRepositoryImplementor; +import com.tvd12.ezyfoxserver.morphia.testing.BaseMongoDBTest; +import com.tvd12.ezyfoxserver.morphia.testing.data.Cat; +import com.tvd12.ezyfoxserver.morphia.testing.repo.CatRepo; + +public class Try1 extends BaseMongoDBTest { + + public static void main(String[] args) throws Exception { + EzyMorphiaRepositoryImplementor implementor = + new EzyMorphiaRepositoryImplementor(CatRepo.class); + CatRepo repo = (CatRepo) implementor.implement(DATASTORE); + Cat cat = repo.findById(2019072087L); + System.out.println(cat); + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try2.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try2.java new file mode 100644 index 00000000..87c1ada9 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/autoimpl/Try2.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo.autoimpl; + +import com.tvd12.ezyfoxserver.morphia.testing.BaseMongoDBTest; +import com.tvd12.ezyfoxserver.morphia.testing.data.Monkey; +import com.tvd12.ezyfoxserver.morphia.testing.service.CatChickendService; + +public class Try2 extends BaseMongoDBTest { + + public static void main(String[] args) throws Exception { + CatChickendService service = + (CatChickendService) BEAN_CONTEXT.getBean(CatChickendService.class); + service.printAllCatAndChickend(); + service.save2Monkey(new Monkey(), new Monkey()); + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/impl/MonkeyRepoImpl.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/impl/MonkeyRepoImpl.java new file mode 100644 index 00000000..45bbecca --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo/impl/MonkeyRepoImpl.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo.impl; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.morphia.repository.EzyDatastoreRepository; +import com.tvd12.ezyfoxserver.morphia.testing.data.Monkey; +import com.tvd12.ezyfoxserver.morphia.testing.repo.MonkeyRepo; + +@EzySingleton +public class MonkeyRepoImpl + extends EzyDatastoreRepository + implements MonkeyRepo { + + @Override + public void save2Monkey(Monkey monkey1, Monkey monkey2) { + datastore.save(Lists.newArrayList(monkey1, monkey2)); + } + + @Override + protected Class getEntityType() { + return Monkey.class; + } + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo.java new file mode 100644 index 00000000..501725f6 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo1; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.Pig; + +@EzyAutoImpl +public interface PigRepo extends EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo2.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo2.java new file mode 100644 index 00000000..3648bf31 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo2.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo1; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.Pig; + +@EzyAutoImpl +public abstract class PigRepo2 implements EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo3.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo3.java new file mode 100644 index 00000000..41e760ad --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/repo1/PigRepo3.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.morphia.testing.repo1; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.mongodb.EzyMongoRepository; +import com.tvd12.ezyfoxserver.morphia.testing.Pig; + +@EzyAutoImpl +abstract class PigRepo3 implements EzyMongoRepository { + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/CatChickendService.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/CatChickendService.java new file mode 100644 index 00000000..c4b76656 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/CatChickendService.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.morphia.testing.service; + +import com.tvd12.ezyfoxserver.morphia.testing.data.Monkey; + +public interface CatChickendService { + + void printAllCatAndChickend(); + + void save2Monkey(Monkey monkey1, Monkey monkey2); + +} diff --git a/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/impl/CatChickendServiceImpl.java b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/impl/CatChickendServiceImpl.java new file mode 100644 index 00000000..392e50c1 --- /dev/null +++ b/ezyfox-server-morphia/src/test/java/com/tvd12/ezyfoxserver/morphia/testing/service/impl/CatChickendServiceImpl.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.morphia.testing.service.impl; + +import com.tvd12.ezyfoxserver.bean.annotation.EzyAutoBind; +import com.tvd12.ezyfoxserver.bean.annotation.EzySingleton; +import com.tvd12.ezyfoxserver.morphia.testing.data.Monkey; +import com.tvd12.ezyfoxserver.morphia.testing.repo.CatRepo; +import com.tvd12.ezyfoxserver.morphia.testing.repo.ChickendRepo; +import com.tvd12.ezyfoxserver.morphia.testing.repo.MonkeyRepo; +import com.tvd12.ezyfoxserver.morphia.testing.service.CatChickendService; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@Setter +@EzySingleton +public class CatChickendServiceImpl + extends EzyLoggable + implements CatChickendService { + + @EzyAutoBind + private CatRepo catRepo; + + @EzyAutoBind + private MonkeyRepo monkeyRepo; + + @EzyAutoBind + private ChickendRepo chickendRepo; + + @Override + public void printAllCatAndChickend() { + System.out.println("all cat: " + catRepo.findAll()); + System.out.println("all chickend: " + chickendRepo.findAll()); + System.out.println("all monkey: " + monkeyRepo.findAll()); + } + + @Override + public void save2Monkey(Monkey monkey1, Monkey monkey2) { + monkeyRepo.save2Monkey(monkey1, monkey2); + } + +} diff --git a/ezyfox-server-morphia/src/test/resources/AllTests.tng.xml b/ezyfox-server-morphia/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..6bc4857a --- /dev/null +++ b/ezyfox-server-morphia/src/test/resources/AllTests.tng.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-morphia/src/test/resources/mongodb_config.properties b/ezyfox-server-morphia/src/test/resources/mongodb_config.properties new file mode 100644 index 00000000..d8c3d5c9 --- /dev/null +++ b/ezyfox-server-morphia/src/test/resources/mongodb_config.properties @@ -0,0 +1,5 @@ +database.mongo.host=127.0.0.1 +database.mongo.port=27017 +database.mongo.database=test +database.mongo.username=root +database.mongo.password=123456 \ No newline at end of file diff --git a/ezyfox-server-msgpack/pom.xml b/ezyfox-server-msgpack/pom.xml index 3917717d..0b31e067 100644 --- a/ezyfox-server-msgpack/pom.xml +++ b/ezyfox-server-msgpack/pom.xml @@ -6,27 +6,21 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-msgpack - 0.0.2 + 1.0.0 ezyfox-server-msgpack http://maven.apache.org 0.6.12 - 0.0.1 - 0.0.1 + 1.0.0 - - com.tvd12 - ezyfox-server-common - ${common.version} - com.tvd12 ezyfox-server-codec - ${codec.version} + ${ezy.codec.version} org.msgpack diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackArrayTemplate.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackArrayTemplate.java index df7183c3..64ca3e29 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackArrayTemplate.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackArrayTemplate.java @@ -2,56 +2,38 @@ import java.io.IOException; -import org.msgpack.MessageTypeException; import org.msgpack.packer.Packer; import org.msgpack.template.AbstractTemplate; import org.msgpack.unpacker.Unpacker; import com.tvd12.ezyfoxserver.entity.EzyArray; -public class MsgPackArrayTemplate extends AbstractTemplate { - - private static final EzyMessageSerializer SERIALIZER; - private static final EzyMessageDeserializer DESERIALIZER; - - static { - SERIALIZER = new MsgPackSimpleSerializer(); - DESERIALIZER = new MsgPackSimpleDeserializer(); - } - - @Override +public class MsgPackArrayTemplate extends AbstractTemplate { + + @Override public void write(Packer pk, EzyArray target, boolean required) throws IOException { if(target != null) writeNotNull(pk, target); - else + else writeNull(pk, required); - - } - + + } + private void writeNull(Packer pk, boolean required) throws IOException { if (!required) pk.writeNil(); - else - throw new MessageTypeException("Attempted to write null"); - } - + else + throw new NullPointerException("Attempted to write null"); + } + private void writeNotNull(Packer pk, EzyArray target) throws IOException { -// pk.write(SERIALIZER.serialize(target)); pk.write(target.toList()); - } - - @Override + } + + @Override public EzyArray read(Unpacker u, EzyArray to, boolean required) throws IOException { - return getDerializer().deserialize(u.readByteArray()); - } - - protected EzyMessageSerializer getSerializer() { - return SERIALIZER; - } - - protected EzyMessageDeserializer getDerializer() { - return DESERIALIZER; - } - -} \ No newline at end of file + throw new UnsupportedOperationException(); + } + +} diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackConstant.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackConstant.java index 517065e3..109904aa 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackConstant.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackConstant.java @@ -1,8 +1,9 @@ package com.tvd12.ezyfoxserver.codec; +import com.tvd12.ezyfoxserver.io.EzyInts; import com.tvd12.ezyfoxserver.io.EzyMath; -public abstract class MsgPackConstant { +public final class MsgPackConstant { private MsgPackConstant() { } @@ -28,4 +29,7 @@ private MsgPackConstant() { public static final int MAX_BIN8_SIZE = EzyMath.bin2int(8); public static final int MAX_BIN16_SIZE = EzyMath.bin2int(16); public static final int MAX_BIN32_SIZE = EzyMath.bin2int(31); + + public static final int MAX_SMALL_MESSAGE_SIZE = EzyInts.bin2int(16); + } diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectTemplate.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectTemplate.java index 5009a066..b298247d 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectTemplate.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectTemplate.java @@ -2,7 +2,6 @@ import java.io.IOException; -import org.msgpack.MessageTypeException; import org.msgpack.packer.Packer; import org.msgpack.template.AbstractTemplate; import org.msgpack.unpacker.Unpacker; @@ -11,14 +10,6 @@ public class MsgPackObjectTemplate extends AbstractTemplate { - private static final EzyMessageSerializer SERIALIZER; - private static final EzyMessageDeserializer DESERIALIZER; - - static { - SERIALIZER = new MsgPackSimpleSerializer(); - DESERIALIZER = new MsgPackSimpleDeserializer(); - } - @Override public void write(Packer pk, EzyObject target, boolean required) throws IOException { @@ -26,22 +17,21 @@ public void write(Packer pk, EzyObject target, boolean required) writeNotNull(pk, target); else writeNull(pk, required); - } + private void writeNotNull(Packer pk, EzyObject target) throws IOException { + pk.write(target.toMap()); + } + private void writeNull(Packer pk, boolean required) throws IOException { if (!required) pk.writeNil(); else - throw new MessageTypeException("Attempted to write null"); + throw new NullPointerException("Attempted to write null"); } - private void writeNotNull(Packer pk, EzyObject target) throws IOException { - pk.write(SERIALIZER.serialize(target)); - } - @Override public EzyObject read(Unpacker u, EzyObject to, boolean required) throws IOException { - return DESERIALIZER.deserialize(u.readByteArray()); + throw new UnsupportedOperationException(); } } diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectToMessage.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectToMessage.java index 9391b9b8..c4995670 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectToMessage.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackObjectToMessage.java @@ -18,7 +18,7 @@ private byte[] convertObject(Object object) { } private EzyMessage convert(byte[] content) { - return EzyMessageBuilder.messageBuilder() + return EzyMessageBuilder.newInstance() .size(content.length) .content(content) .header(newHeader(content)) @@ -26,13 +26,17 @@ private EzyMessage convert(byte[] content) { } private EzyMessageHeader newHeader(byte[] content) { - return EzyMessageBuilder.headerBuilder() - .bigSize(true) + return EzyMessageHeaderBuilder.newInstance() + .bigSize(isBigMessage(content)) + .encrypted(false) .compressed(false) - .encrypted(true) .build(); } + private boolean isBigMessage(byte[] content) { + return content.length > MsgPackConstant.MAX_SMALL_MESSAGE_SIZE; + } + public static Builder builder() { return new Builder(); } diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer.java index 900dcaaf..af42bcce 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer.java @@ -8,35 +8,22 @@ import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; -import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; import com.tvd12.ezyfoxserver.function.EzyParser; import com.tvd12.ezyfoxserver.io.EzyBytes; import com.tvd12.ezyfoxserver.io.EzyInts; import com.tvd12.ezyfoxserver.io.EzyLongs; import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.util.EzyLiteEntityBuilders; -public class MsgPackSimpleDeserializer implements EzyMessageDeserializer { +public class MsgPackSimpleDeserializer + extends EzyLiteEntityBuilders + implements EzyMessageDeserializer { - private MsgPackTypeParser typeParser; - private Map> parsers; - - private MapSizeDeserializer mapSizeDeserializer; - private ArraySizeDeserializer arraySizeDeserializer; - private StringSizeDeserializer stringSizeDeserializer; - - { - parsers = defaultParsers(); - typeParser = new MsgPackTypeParser(); - mapSizeDeserializer = new MapSizeDeserializer(); - arraySizeDeserializer = new ArraySizeDeserializer(); - stringSizeDeserializer = new StringSizeDeserializer(); - } - - @SuppressWarnings("unchecked") - @Override - public T deserialize(byte[] data) { - return (T) deserialize(ByteBuffer.wrap(data)); - } + private MsgPackTypeParser typeParser = new MsgPackTypeParser(); + private MapSizeDeserializer mapSizeDeserializer = new MapSizeDeserializer(); + private ArraySizeDeserializer arraySizeDeserializer = new ArraySizeDeserializer(); + private StringSizeDeserializer stringSizeDeserializer = new StringSizeDeserializer(); + private Map> parsers = defaultParsers(); @SuppressWarnings("unchecked") public Object deserialize(ByteBuffer buffer) { @@ -100,7 +87,7 @@ protected Object parseFloat64(ByteBuffer buffer) { } protected Object parseBin32(ByteBuffer buffer) { - return parseBin(buffer, getBinLength(buffer, 5)); + return parseBin(buffer, getBinLength(buffer, 4)); } protected Object parseBin16(ByteBuffer buffer) { @@ -113,10 +100,7 @@ protected Object parseBin8(ByteBuffer buffer) { protected int getBinLength(ByteBuffer buffer, int size) { buffer.get(); - int result = 0; - for(int i = 0 ; i < size ; i++) - result += buffer.get() & 0xff; - return result; + return EzyInts.bin2uint(buffer, size); } protected Object parseBin(ByteBuffer buffer, int length) { @@ -180,7 +164,7 @@ protected String parseFixStr(ByteBuffer buffer) { } protected String parseString(ByteBuffer buffer, int nbytes) { - return EzyStrings.newUTF(buffer, parseStringSize(buffer, nbytes)); + return EzyStrings.newUtf(buffer, parseStringSize(buffer, nbytes)); } protected int parseStringSize(ByteBuffer buffer, int nbytes) { @@ -268,14 +252,6 @@ protected EzyArray parseArray(ByteBuffer buffer, int size) { return builder.build(); } - protected EzyObjectBuilder newObjectBuilder() { - return EzyEntityFactory.create(EzyObjectBuilder.class); - } - - protected EzyArrayBuilder newArrayBuilder() { - return EzyEntityFactory.create(EzyArrayBuilder.class); - } - protected MsgPackType getDataType(int type) { return typeParser.parse(type); } diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleSerializer.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleSerializer.java index 5d145af0..6c9ae8ae 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleSerializer.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleSerializer.java @@ -32,9 +32,9 @@ import com.tvd12.ezyfoxserver.function.EzyCastIntToByte; import com.tvd12.ezyfoxserver.function.EzyParser; import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.ezyfoxserver.io.EzyDataConverter; import com.tvd12.ezyfoxserver.io.EzyStrings; import com.tvd12.ezyfoxserver.util.EzyBoolsIterator; -import com.tvd12.ezyfoxserver.util.EzyDataConverter; import com.tvd12.ezyfoxserver.util.EzyDoublesIterator; import com.tvd12.ezyfoxserver.util.EzyFloatsIterator; import com.tvd12.ezyfoxserver.util.EzyIntsIterator; @@ -47,23 +47,13 @@ public class MsgPackSimpleSerializer extends EzyAbstractSerializer implements EzyCastIntToByte { - protected IntSerializer intSerializer; - protected FloatSerializer floatSerializer; - protected DoubleSerializer doubleSerializer; - protected BinSizeSerializer binSizeSerializer; - protected MapSizeSerializer mapSizeSerializer; - protected ArraySizeSerializer arraySizeSerializer; - protected StringSizeSerializer stringSizeSerializer; - - { - intSerializer = new IntSerializer(); - floatSerializer = new FloatSerializer(); - doubleSerializer = new DoubleSerializer(); - binSizeSerializer = new BinSizeSerializer(); - mapSizeSerializer = new MapSizeSerializer(); - arraySizeSerializer = new ArraySizeSerializer(); - stringSizeSerializer = new StringSizeSerializer(); - } + protected IntSerializer intSerializer = new IntSerializer(); + protected FloatSerializer floatSerializer = new FloatSerializer(); + protected DoubleSerializer doubleSerializer = new DoubleSerializer(); + protected BinSizeSerializer binSizeSerializer = new BinSizeSerializer(); + protected MapSizeSerializer mapSizeSerializer = new MapSizeSerializer(); + protected ArraySizeSerializer arraySizeSerializer = new ArraySizeSerializer(); + protected StringSizeSerializer stringSizeSerializer = new StringSizeSerializer(); @Override protected void addParsers(Map, EzyParser> parsers) { @@ -283,7 +273,7 @@ protected byte[] parseDouble(Double value) { } protected byte[] parseFloat(Object value) { - return parseDouble((Float)value); + return parseFloat((Float)value); } protected byte[] parseFloat(Float value) { @@ -295,7 +285,7 @@ protected byte[] parseInt(Object value) { } protected byte[] parseShort(Object value) { - return parseInt((Short)value); + return parseShort((Short)value); } protected byte[] parseShort(Short value) { @@ -358,10 +348,9 @@ protected byte[] parseBinSize(int size) { } protected byte[] parseString(String string) { - int size = string.length(); byte[][] bytess = new byte[2][]; - bytess[0] = parseStringSize(size); - bytess[1] = EzyStrings.getUTFBytes(string); + bytess[1] = EzyStrings.getUtfBytes(string); + bytess[0] = parseStringSize(bytess[1].length); return EzyBytes.copy(bytess); } @@ -508,14 +497,14 @@ private byte[] parse16(int size) { } private byte[] parse32(int size) { - return EzyBytes.getBytes(0xde, size, 2); + return EzyBytes.getBytes(0xdf, size, 4); } } class IntSerializer implements EzyCastIntToByte { public byte[] serialize(long value) { - return value > 0 + return value >= 0 ? parsePositive(value) : parseNegative(value); } diff --git a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackTypeParser.java b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackTypeParser.java index ec55e7fb..ddbbc649 100644 --- a/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackTypeParser.java +++ b/ezyfox-server-msgpack/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackTypeParser.java @@ -3,8 +3,6 @@ public class MsgPackTypeParser { public MsgPackType parse(int type) { - if(type == 0xc4) - return MsgPackType.BIN8; if (0x00 <= type && type <= 0x7f) return MsgPackType.POSITIVE_FIXINT; if (0x80 <= type && type <= 0x8f) @@ -21,6 +19,8 @@ public MsgPackType parse(int type) { return MsgPackType.FALSE; if(type == 0xc3) return MsgPackType.TRUE; + if(type == 0xc4) + return MsgPackType.BIN8; if(type == 0xc5) return MsgPackType.BIN16; if(type == 0xc6) @@ -74,7 +74,7 @@ public MsgPackType parse(int type) { if(type == 0xde) return MsgPackType.MAP16; if(type == 0xdf) - return MsgPackType.ARRAY32; + return MsgPackType.MAP32; if (0xe0 <= type && type <= 0xff) return MsgPackType.NEGATIVE_FIXINT; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/CodecBaseTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/CodecBaseTest.java deleted file mode 100644 index 0ebdd530..00000000 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/CodecBaseTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; -import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; -import com.tvd12.ezyfoxserver.factory.EzyFactory; - -public class CodecBaseTest { - - public EzyArrayBuilder newArrayBuilder() { - return EzyFactory.create(EzyArrayBuilder.class); - } - - public EzyObjectBuilder newObjectBuilder() { - return EzyFactory.create(EzyObjectBuilder.class); - } - -} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer6Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer6Test.java deleted file mode 100644 index c602f446..00000000 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer6Test.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import java.io.IOException; - -import org.testng.annotations.Test; - -import com.tvd12.ezyfoxserver.entity.EzyArray; - -public class MsgPackMySimpleDeserializer6Test extends MsgPackCodecTest { - - @Test - public void test1() throws IOException { - EzyMessageSerializer serializer = new MsgPackSimpleSerializer(); - EzyArray request = newArrayBuilder() - .append(-1) - .build(); - byte[] bytes = serializer.serialize(request); - MsgPackSimpleDeserializer deserializer = new MsgPackSimpleDeserializer(); - EzyArray answer = deserializer.deserialize(bytes); - getLogger().info("answer = {}", answer); - } - -} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/CodecBaseTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/CodecBaseTest.java new file mode 100644 index 00000000..3691f959 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/CodecBaseTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class CodecBaseTest extends BaseTest { + + public EzyArrayBuilder newArrayBuilder() { + return EzyEntityFactory.create(EzyArrayBuilder.class); + } + + public EzyObjectBuilder newObjectBuilder() { + return EzyEntityFactory.create(EzyObjectBuilder.class); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/GetParameterTypeTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/GetParameterTypeTest.java similarity index 97% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/GetParameterTypeTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/GetParameterTypeTest.java index 6ab51795..7aae5768 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/GetParameterTypeTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/GetParameterTypeTest.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackArrayTemplateTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackArrayTemplateTest.java new file mode 100644 index 00000000..8d27334d --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackArrayTemplateTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.msgpack.MessagePack; +import org.msgpack.packer.Packer; +import org.msgpack.unpacker.Unpacker; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.MsgPackArrayTemplate; +import com.tvd12.test.base.BaseTest; + +public class MsgPackArrayTemplateTest extends BaseTest { + + private MessagePack messagePack = new MessagePack(); + private MsgPackArrayTemplate template = new MsgPackArrayTemplate(); + + @Test + public void test() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Packer packer = messagePack.createPacker(stream); + template.write(packer, null, false); + } + + @Test(expectedExceptions = {NullPointerException.class}) + public void test1() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Packer packer = messagePack.createPacker(stream); + template.write(packer, null, true); + } + + @Test(expectedExceptions = {UnsupportedOperationException.class}) + public void test2() throws IOException { + Unpacker unpacker = messagePack.createBufferUnpacker(); + template.read(unpacker, null); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackCodecTest.java similarity index 77% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackCodecTest.java index 748d92df..6e9c9af3 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackCodecTest.java @@ -1,9 +1,11 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import org.msgpack.MessagePack; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.tvd12.ezyfoxserver.codec.MsgPackArrayTemplate; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectTemplate; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.entity.EzyObject; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackConstantTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackConstantTest.java new file mode 100644 index 00000000..c682ed96 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackConstantTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import com.tvd12.ezyfoxserver.codec.MsgPackConstant; +import com.tvd12.test.base.BaseTest; + +public class MsgPackConstantTest extends BaseTest { + + @Override + public Class getTestClass() { + return MsgPackConstant.class; + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer2Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer2Test.java similarity index 85% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer2Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer2Test.java index 080e2283..7586556f 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer2Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer2Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; import java.util.Arrays; @@ -6,6 +6,9 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer3Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer3Test.java similarity index 86% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer3Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer3Test.java index b062e05e..a10961f3 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer3Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer3Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; import java.util.Arrays; @@ -6,6 +6,9 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer4Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer4Test.java similarity index 79% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer4Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer4Test.java index ff8e1490..00ab39d9 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer4Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer4Test.java @@ -1,10 +1,13 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; import static org.testng.Assert.*; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer5Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer5Test.java similarity index 79% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer5Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer5Test.java index 196e75e7..f8ba0b67 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializer5Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer5Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; @@ -6,6 +6,9 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer6Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer6Test.java new file mode 100644 index 00000000..60958a62 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializer6Test.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.io.IOException; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public class MsgPackMySimpleDeserializer6Test extends MsgPackCodecTest { + + @Test + public void test1() throws IOException { + EzyMessageSerializer serializer = new MsgPackSimpleSerializer(); + EzyArray request = newArrayBuilder() + .append(-1) + .build(); + byte[] bytes = serializer.serialize(request); + MsgPackSimpleDeserializer deserializer = new MsgPackSimpleDeserializer(); + EzyArray answer = deserializer.deserialize(bytes); + getLogger().info("answer = {}", answer); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializerTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializerTest.java similarity index 90% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializerTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializerTest.java index 6bb27969..3af61d16 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackMySimpleDeserializerTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackMySimpleDeserializerTest.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; @@ -6,6 +6,9 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyInts; import com.tvd12.ezyfoxserver.io.EzyLongs; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectTemplateTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectTemplateTest.java new file mode 100644 index 00000000..fd000533 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectTemplateTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.msgpack.MessagePack; +import org.msgpack.packer.Packer; +import org.msgpack.unpacker.Unpacker; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.MsgPackObjectTemplate; +import com.tvd12.test.base.BaseTest; + +public class MsgPackObjectTemplateTest extends BaseTest { + + private MessagePack messagePack = new MessagePack(); + private MsgPackObjectTemplate template = new MsgPackObjectTemplate(); + + @Test + public void test() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Packer packer = messagePack.createPacker(stream); + template.write(packer, null, false); + } + + @Test(expectedExceptions = {NullPointerException.class}) + public void test1() throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + Packer packer = messagePack.createPacker(stream); + template.write(packer, null, true); + } + + @Test(expectedExceptions = {UnsupportedOperationException.class}) + public void test2() throws IOException { + Unpacker unpacker = messagePack.createBufferUnpacker(); + template.read(unpacker, null); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToBytesTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToBytesTest.java new file mode 100644 index 00000000..4d751613 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToBytesTest.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectToBytes; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectToBytes.MsgPackObjectToBytesBuilder; +import com.tvd12.test.base.BaseTest; + +public class MsgPackObjectToBytesTest extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + MsgPackObjectToBytesBuilder builder = + MsgPackObjectToBytes.builder(); + builder.toString(); + MsgPackObjectToBytes.builder() + .serializer(new EzyMessageSerializer() { + + @Override + public byte[] serialize(Object value) { + throw new RuntimeException(); + } + }) + .build() + .convert(null); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToMessageTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToMessageTest.java new file mode 100644 index 00000000..be8a33e6 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackObjectToMessageTest.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyObjectToMessage; +import com.tvd12.ezyfoxserver.codec.MsgPackConstant; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectToMessage; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.test.base.BaseTest; + +public class MsgPackObjectToMessageTest extends BaseTest { + + @Test + public void test() { + EzyObjectToMessage converter = newMsgPackObjectToMessage(); + EzyArray params = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("clientId") + .append("token") + .append(1) + .build(); + EzyMessage message = converter.convert(params); + assert !message.getHeader().isBigSize(); + assert !message.getHeader().isCompressed(); + assert !message.getHeader().isEncrypted(); + assert !message.hasBigSize(); + assert message.getContent().length > 0; + assert message.getSize() > 0; + assert message.getSizeLength() == 2; + + } + + @Test + public void test2() { + EzyObjectToMessage converter = newMsgPackObjectToMessage(); + EzyArray params = EzyEntityFactory.create(EzyArrayBuilder.class) + .append("clientId") + .append("token") + .append(1) + .append(new int[MsgPackConstant.MAX_BIN16_SIZE]) + .build(); + EzyMessage message = converter.convert(params); + assert message.getHeader().isBigSize(); + assert message.getSizeLength() == 4; + + } + + private EzyObjectToMessage newMsgPackObjectToMessage() { + return MsgPackObjectToMessage.builder().build(); + } +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer2Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer2Test.java similarity index 91% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer2Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer2Test.java index dc2fa74f..0703d7f8 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer2Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer2Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; import java.util.Arrays; @@ -6,6 +6,7 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer3Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer3Test.java similarity index 88% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer3Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer3Test.java index 3577cc28..bc6dde6c 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer3Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer3Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; @@ -6,6 +6,7 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer4Test.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer4Test.java similarity index 88% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer4Test.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer4Test.java index 708e99ac..5f6df633 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializer4Test.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializer4Test.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; @@ -6,6 +6,7 @@ import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyMath; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializerTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializerTest.java similarity index 93% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializerTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializerTest.java index eae75c33..583dd942 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/MsgPackSimpleDeserializerTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleDeserializerTest.java @@ -1,10 +1,11 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.codec.testing; import java.io.IOException; import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.builder.EzyObjectBuilder; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; import com.tvd12.ezyfoxserver.entity.EzyArray; import com.tvd12.ezyfoxserver.io.EzyInts; import com.tvd12.ezyfoxserver.io.EzyLongs; diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleSerializerAllTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleSerializerAllTest.java new file mode 100644 index 00000000..34ada582 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackSimpleSerializerAllTest.java @@ -0,0 +1,206 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.codec.MsgPackConstant; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.entity.EzyObject; + +import static org.testng.Assert.*; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +public class MsgPackSimpleSerializerAllTest extends CodecBaseTest { + + private MsgPackSimpleSerializer serializer + = new MsgPackSimpleSerializer(); + private MsgPackSimpleDeserializer deserializer + = new MsgPackSimpleDeserializer(); + + @Test + public void test() { + Boolean[] value = new Boolean[] {true, false, true}; + byte[] bytes = serializer.serialize(value); + assertEquals(bytes, new byte[] {(byte) (0x90 | 3), (byte) 0xc3, (byte) 0xc2, (byte) 0xc3}); + EzyArray array = deserializer.deserialize(bytes); + assertEquals(value, array.toArray(Boolean.class)); + } + + @Test + public void test1() { + byte[] bytes = serializer.serialize(new boolean[] {true, false, true}); + EzyArray array = deserializer.deserialize(bytes); + assertEquals(array.toArray(boolean.class), new boolean[] {true, false, true}); + + bytes = serializer.serialize(new char[] {'1', 'b', 'c'}); + byte[] bytes1 = deserializer.deserialize(bytes); + assertEquals(bytes1, new byte[] {'1', 'b', 'c'}); + + bytes = serializer.serialize(new double[] {1D, 2D, 3D}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(double.class), new double[] {1D, 2D, 3D}); + + bytes = serializer.serialize(new float[] {1F, 2F, 3F}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(float.class), new float[] {1F, 2F, 3F}); + + bytes = serializer.serialize(new int[] {1, 2, 3}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(int.class), new int[] {1, 2, 3}); + + bytes = serializer.serialize(new long[] {1L, 2L, 3L}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(long.class), new long[] {1L, 2L, 3L}); + + bytes = serializer.serialize(new short[] {(short)1, (short)2, (short)3}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(short.class), new short[] {(short)1, (short)2, (short)3}); + + bytes = serializer.serialize(new String[] {"1", "2", "3"}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(String.class), new String[] {"1", "2", "3"}); + } + + @Test + public void test2() { + byte[] bytes = serializer.serialize(new Boolean[] {true, false, true}); + EzyArray array = deserializer.deserialize(bytes); + assertEquals(array.toArray(Boolean.class), new Boolean[] {true, false, true}); + + bytes = serializer.serialize(new Byte[] {'1', 'b', 'c'}); + byte[] bytes1 = deserializer.deserialize(bytes); + assertEquals(bytes1, new byte[] {'1', 'b', 'c'}); + + bytes = serializer.serialize(new Character[] {'1', 'b', 'c'}); + byte[] bytes2 = deserializer.deserialize(bytes); + assertEquals(bytes2, new byte[] {'1', 'b', 'c'}); + + bytes = serializer.serialize(new Double[] {1D, 2D, 3D}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(double.class), new double[] {1D, 2D, 3D}); + + bytes = serializer.serialize(new Float[] {1F, 2F, 3F}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(float.class), new float[] {1F, 2F, 3F}); + + bytes = serializer.serialize(new Integer[] {1, 2, 3}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(int.class), new int[] {1, 2, 3}); + + bytes = serializer.serialize(new Long[] {1L, 2L, 3L}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(long.class), new long[] {1L, 2L, 3L}); + + bytes = serializer.serialize(new Short[] {(short)1, (short)2, (short)3}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(short.class), new short[] {(short)1, (short)2, (short)3}); + + bytes = serializer.serialize(new String[] {"1", "2", "3"}); + array = deserializer.deserialize(bytes); + assertEquals(array.toArray(String.class), new String[] {"1", "2", "3"}); + } + + @Test + public void test3() { + byte[] bytes = serializer.serialize((byte)12); + Number number = deserializer.deserialize(bytes); + assertEquals((Byte)number.byteValue(), new Byte((byte)12)); + + bytes = serializer.serialize('a'); + number = deserializer.deserialize(bytes); + assertEquals((char)number.byteValue(), 'a'); + + bytes = serializer.serialize(new Short((short)10)); + number = deserializer.deserialize(bytes); + assertEquals(number.shortValue(), (short)10); + + Map map = new HashMap<>(); + map.put("a", 1L); + map.put("b", 2L); + bytes = serializer.serialize(map); + EzyObject obj = deserializer.deserialize(bytes); + assertEquals(obj.size(), 2); + assertEquals(obj.get("a", Long.class), new Long(1L)); + assertEquals(obj.get("b", Long.class), new Long(2L)); + + Collection coll = Lists.newArrayList("a", "b", "c"); + bytes = serializer.serialize(coll); + EzyArray arr = deserializer.deserialize(bytes); + assertEquals(arr.toList(String.class), Lists.newArrayList("a", "b", "c")); + } + + @Test + public void test4() { + byte[] bytes = new byte[MsgPackConstant.MAX_BIN16_SIZE]; + bytes[123] = 5; + byte[] bs1 = serializer.serialize(bytes); + byte[] bs2 = deserializer.deserialize(bs1); + assertEquals(bs2, bytes); + } + + @Test + public void test5() { + int[] ints = new int[MsgPackConstant.MAX_ARRAY16_SIZE + 1]; + ints[12] = 5; + byte[] bs1 = serializer.serialize(ints); + EzyArray array = deserializer.deserialize(bs1); + assertEquals(array.size(), ints.length); + assertEquals(array.get(12, int.class), new Integer(5)); + assertTrue(Arrays.equals(array.toArray(int.class), ints)); + assertEquals(array.toArray(int.class), ints); + } + + @Test + public void test6() { + byte[] bytes = serializer.serialize(0); + assertEquals(bytes, new byte[] {0}); + } + + @Test + public void test7() { + Map map = new HashMap<>(); + for(int i = 0 ; i < MsgPackConstant.MAX_MAP16_SIZE + 1 ; i++) + map.put(String.valueOf(i), i); + byte[] bytes = serializer.serialize(map); + EzyObject object = deserializer.deserialize(bytes); + assertEquals(object.size(), map.size()); + for(Object key : map.keySet()) + assertEquals(object.get(key), map.get(key)); + } + + @Test + public void test8() { + Map map = new HashMap<>(); + for(int i = 0 ; i < MsgPackConstant.MAX_MAP16_SIZE ; i++) + map.put(String.valueOf(i), i); + byte[] bytes = serializer.serialize(map); + EzyObject object = deserializer.deserialize(bytes); + assertEquals(object.size(), map.size()); + for(Object key : map.keySet()) + assertEquals(object.get(key), map.get(key)); + } + + @Test + public void test9() { + StringBuilder builder = new StringBuilder(); + for(int i = 0 ; i < MsgPackConstant.MAX_STR8_SIZE + 1 ; i++) + builder.append(i); + String str = builder.toString(); + long startTime = System.currentTimeMillis(); + byte[] bs1 = serializer.serialize(str); + String str2 = deserializer.deserialize(bs1); + long endTime = System.currentTimeMillis(); + System.err.println("time = " + (endTime - startTime)); + assertEquals(str2, str); + } + + public static void main(String[] args) { + new MsgPackSimpleSerializerAllTest().test9(); + } +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeParserTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeParserTest.java new file mode 100644 index 00000000..618930ff --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeParserTest.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.MsgPackType; +import com.tvd12.ezyfoxserver.codec.MsgPackTypeParser; + +public class MsgPackTypeParserTest { + + private MsgPackTypeParser parser = new MsgPackTypeParser(); + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test0() { + parser.parse(-1); + } + + @Test + public void test1() { + assert parser.parse(0x00) == MsgPackType.POSITIVE_FIXINT; + assert parser.parse(0x00 + 1) == MsgPackType.POSITIVE_FIXINT; + assert parser.parse(0x7f) == MsgPackType.POSITIVE_FIXINT; + assert parser.parse(0x7f - 1) == MsgPackType.POSITIVE_FIXINT; + } + + @Test + public void test2() { + assert parser.parse(0xc1) == MsgPackType.NEVER_USED; + assert parser.parse(0xd4) == MsgPackType.FIXEXT1; + assert parser.parse(0xd5) == MsgPackType.FIXEXT2; + assert parser.parse(0xd6) == MsgPackType.FIXEXT4; + assert parser.parse(0xd7) == MsgPackType.FIXEXT8; + assert parser.parse(0xd8) == MsgPackType.FIXEXT16; + + assert parser.parse(0xc7) == MsgPackType.EXT8; + assert parser.parse(0xc8) == MsgPackType.EXT16; + assert parser.parse(0xc9) == MsgPackType.EXT32; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + parser.parse(256); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeTest.java new file mode 100644 index 00000000..a4995719 --- /dev/null +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/MsgPackTypeTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.codec.testing; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.codec.MsgPackType; +import com.tvd12.test.base.BaseTest; + +public class MsgPackTypeTest extends BaseTest { + + @Test + public void test() { + assert MsgPackType.POSITIVE_FIXINT.getId() == 0; + assert MsgPackType.POSITIVE_FIXINT.getName().equals("POSITIVE_FIXINT"); + MsgPackType.values(); + MsgPackType.valueOf("POSITIVE_FIXINT"); + } + +} diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/DeserializeArrayTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/DeserializeArrayTest.java similarity index 81% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/DeserializeArrayTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/DeserializeArrayTest.java index 0dae7e2c..15c9f285 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/DeserializeArrayTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/DeserializeArrayTest.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec.performance; +package com.tvd12.ezyfoxserver.codec.testing.performance; import org.testng.annotations.Test; @@ -8,7 +8,7 @@ import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.factory.EzyFactory; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; import com.tvd12.test.base.BaseTest; import com.tvd12.test.performance.Performance; @@ -16,8 +16,8 @@ public class DeserializeArrayTest extends BaseTest { @Test public void test1() { - EzyFactory.create(EzyArrayBuilder.class); - EzyArrayBuilder builder = EzyFactory.create(EzyArrayBuilder.class); + EzyEntityFactory.create(EzyArrayBuilder.class); + EzyArrayBuilder builder = EzyEntityFactory.create(EzyArrayBuilder.class); builder.append((Object)null); builder.append(""); builder.append(1); diff --git a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/SerializeArrayTest.java b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/SerializeArrayTest.java similarity index 76% rename from ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/SerializeArrayTest.java rename to ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/SerializeArrayTest.java index 8405acad..1eb6701f 100644 --- a/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/performance/SerializeArrayTest.java +++ b/ezyfox-server-msgpack/src/test/java/com/tvd12/ezyfoxserver/codec/testing/performance/SerializeArrayTest.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec.performance; +package com.tvd12.ezyfoxserver.codec.testing.performance; import org.testng.annotations.Test; @@ -6,7 +6,7 @@ import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.factory.EzyFactory; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; import com.tvd12.test.base.BaseTest; import com.tvd12.test.performance.Performance; @@ -14,8 +14,8 @@ public class SerializeArrayTest extends BaseTest { @Test public void test1() { - EzyFactory.create(EzyArrayBuilder.class); - EzyArrayBuilder builder = EzyFactory.create(EzyArrayBuilder.class); + EzyEntityFactory.create(EzyArrayBuilder.class); + EzyArrayBuilder builder = EzyEntityFactory.create(EzyArrayBuilder.class); builder.append((Object)null); builder.append(""); builder.append(1); diff --git a/ezyfox-server-msgpack/src/test/resources/AllTests.tng.xml b/ezyfox-server-msgpack/src/test/resources/AllTests.tng.xml index 1de16472..dd5a6f08 100644 --- a/ezyfox-server-msgpack/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-msgpack/src/test/resources/AllTests.tng.xml @@ -3,7 +3,12 @@ - + + + + + + \ No newline at end of file diff --git a/ezyfox-server-netty/pom.xml b/ezyfox-server-netty/pom.xml index 19adc69b..f8b06b6d 100644 --- a/ezyfox-server-netty/pom.xml +++ b/ezyfox-server-netty/pom.xml @@ -6,21 +6,23 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-netty 1.0.0 ezyfox-server-netty http://maven.apache.org + - 1.0.0 + 1.0.0 4.1.8.Final + com.tvd12 - ezyfox-server-core - ${core.version} + ezyfox-server-boot + ${ezy.boot.version} io.netty diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyStarter.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyStarter.java deleted file mode 100644 index 8a58d834..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyStarter.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.tvd12.ezyfoxserver; - -import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; -import com.tvd12.ezyfoxserver.builder.impl.EzyNettyServerBootstrapBuilderImpl; -import com.tvd12.ezyfoxserver.wrapper.EzyManagers; -import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; -import com.tvd12.ezyfoxserver.wrapper.impl.EzyNettySessionManagerImpl; - -public class EzyNettyStarter extends EzyStarter { - - protected EzyNettyStarter(Builder builder) { - super(builder); - } - - @Override - protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { - return new EzyNettyServerBootstrapBuilderImpl(); - } - - @Override - public EzyManagers newManagers() { - EzyManagers mngs = super.newManagers(); - mngs.addManager(EzySessionManager.class, EzyNettySessionManagerImpl.builder().build()); - return mngs; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyStarter.Builder { - @Override - public EzyStarter build() { - return new EzyNettyStarter(this); - } - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/EzyNettyServerBootstrapBuilder.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/EzyNettyServerBootstrapBuilder.java deleted file mode 100644 index 7c3d8677..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/EzyNettyServerBootstrapBuilder.java +++ /dev/null @@ -1,4 +0,0 @@ -package com.tvd12.ezyfoxserver.builder; - -public interface EzyNettyServerBootstrapBuilder extends EzyServerBootstrapBuilder { -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyChannelInitializer.java deleted file mode 100644 index 52f1a6dd..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyChannelInitializer.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; -import com.tvd12.ezyfoxserver.codec.EzyCombinedCodec; -import com.tvd12.ezyfoxserver.creator.EzyDataHandlerCreator; - -import io.netty.channel.Channel; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelInboundHandler; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOutboundHandler; -import io.netty.channel.ChannelPipeline; - -class EzyChannelInitializer extends ChannelInitializer { - - protected EzyCodecCreator codecCreator; - protected EzyDataHandlerCreator dataHandlerCreator; - - protected EzyChannelInitializer(Builder builder) { - this.codecCreator = builder.codecCreator; - this.dataHandlerCreator = builder.dataHandlerCreator; - } - - @Override - protected void initChannel(Channel ch) throws Exception { - initChannel(ch, newEncoder(), newDecoder()); - } - - protected void initChannel(Channel ch, - ChannelOutboundHandler encoder, - ChannelInboundHandler decoder) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); - pipeline.addLast(newDataHandler()); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); - } - - protected ChannelHandler newDataHandler() { - return dataHandlerCreator.newHandler(); - } - - protected ChannelOutboundHandler newEncoder() { - return codecCreator.newEncoder(); - } - - protected ChannelInboundHandler newDecoder() { - return codecCreator.newDecoder(); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - - private EzyCodecCreator codecCreator; - private EzyDataHandlerCreator dataHandlerCreator; - - public Builder codecCreator(EzyCodecCreator codecCreator) { - this.codecCreator = codecCreator; - return this; - } - - public Builder dataHandlerCreator(EzyDataHandlerCreator dataHandlerCreator) { - this.dataHandlerCreator = dataHandlerCreator; - return this; - } - - public EzyChannelInitializer build() { - return new EzyChannelInitializer(this); - } - - } -} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyContextBuilderImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyContextBuilderImpl.java deleted file mode 100644 index 2c1b9bf4..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyContextBuilderImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.ExecutorService; - -import com.tvd12.ezyfoxserver.EzyServer; -import com.tvd12.ezyfoxserver.builder.EzyContextBuilder; -import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; -import com.tvd12.ezyfoxserver.config.EzyApp; -import com.tvd12.ezyfoxserver.config.EzyPlugin; -import com.tvd12.ezyfoxserver.context.EzyAppContext; -import com.tvd12.ezyfoxserver.context.EzyContext; -import com.tvd12.ezyfoxserver.context.EzyPluginContext; -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.context.EzySimpleAppContext; -import com.tvd12.ezyfoxserver.context.EzySimpleContext; -import com.tvd12.ezyfoxserver.context.EzySimplePluginContext; -import com.tvd12.ezyfoxserver.service.EzyResponseSerializer; -import com.tvd12.ezyfoxserver.service.impl.EzyResponseSerializerImpl; - -public class EzyContextBuilderImpl implements EzyContextBuilder { - - private EzyServer boss; - - public static EzyContextBuilderImpl builder() { - return new EzyContextBuilderImpl(); - } - - @Override - public EzyServerContext build() { - EzySimpleContext context = new EzySimpleContext(); - context.setBoss(boss); - context.setWorkerExecutor(newWorkerExecutor()); - context.addAppContexts(newAppContexts(context)); - context.addPluginContexts(newPluginContexts(context)); - context.setProperty(EzyResponseSerializer.class, newResponseSerializer()); - return context; - } - - protected ExecutorService newWorkerExecutor() { - String threadName = "worker"; - int nthreads = boss.getSettings().getNumThreads(); - return EzyExecutors.newFixedThreadPool(nthreads, threadName); - } - - protected Collection newAppContexts(EzyContext parent) { - Collection contexts = new ArrayList<>(); - for(Integer appId : boss.getAppIds()) - contexts.add(newAppContext(parent, boss.getAppById(appId))); - return contexts; - } - - protected EzyAppContext newAppContext(EzyContext parent, EzyApp app) { - EzySimpleAppContext appContext = new EzySimpleAppContext(); - appContext.setApp(app); - appContext.setParent(parent); - appContext.setWorkerExecutor(newAppWorkerExecutor(app)); - return appContext; - } - - protected Collection newPluginContexts(EzyContext parent) { - Collection contexts = new ArrayList<>(); - for(Integer appId : boss.getPluginIds()) - contexts.add(newPluginContext(parent, boss.getPluginById(appId))); - return contexts; - } - - protected EzyPluginContext newPluginContext(EzyContext parent, EzyPlugin plugin) { - EzySimplePluginContext pluginContext = new EzySimplePluginContext(); - pluginContext.setPlugin(plugin); - pluginContext.setParent(parent); - pluginContext.setWorkerExecutor(newPluginWorkerExecutor(plugin)); - return pluginContext; - } - - protected ExecutorService newAppWorkerExecutor(EzyApp app) { - String threadName = "app-worker"; - int nthreads = app.getNumThreads(); - return EzyExecutors.newFixedThreadPool(nthreads, threadName); - } - - protected ExecutorService newPluginWorkerExecutor(EzyPlugin plugin) { - String threadName = "plugin-worker"; - int nthreads = plugin.getNumThreads(); - return EzyExecutors.newFixedThreadPool(nthreads, threadName); - } - - protected EzyResponseSerializer newResponseSerializer() { - return EzyResponseSerializerImpl.builder().build(); - } - - @Override - public EzyContextBuilderImpl boss(EzyServer boss) { - this.boss = boss; - return this; - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyNettyServerBootstrapBuilderImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyNettyServerBootstrapBuilderImpl.java deleted file mode 100644 index 9ea44038..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyNettyServerBootstrapBuilderImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.EzyNettyServerBootstrap; -import com.tvd12.ezyfoxserver.EzyServerBootstrap; -import com.tvd12.ezyfoxserver.builder.EzyAbtractServerBootstrapBuilder; -import com.tvd12.ezyfoxserver.builder.EzyNettyServerBootstrapBuilder; -import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; -import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.reflect.EzyClassUtil; - -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslContextBuilder; -import io.netty.handler.ssl.util.SelfSignedCertificate; - -public class EzyNettyServerBootstrapBuilderImpl - extends EzyAbtractServerBootstrapBuilder - implements EzyNettyServerBootstrapBuilder { - - private EventLoopGroup childGroup; - private EventLoopGroup parentGroup; - - @Override - protected EzyServerBootstrap build(EzyServerContext ctx) { - prebuild(ctx); - return doBuild(ctx); - } - - protected void prebuild(EzyServerContext ctx) { - this.childGroup = newChildEventLoopGroup(); - this.parentGroup = newParentEventLoopGroup(); - } - - protected EzyServerBootstrap doBuild(EzyServerContext ctx) { - EzyNettyServerBootstrap answer = new EzyNettyServerBootstrap(); - answer.setContext(ctx); - answer.setChildGroup(newParentEventLoopGroup()); - answer.setParentGroup(newChildEventLoopGroup()); - answer.setLocalBootstrap(newLocalBoostrap(ctx)); - answer.setServerBootstrap(createServerBootstrap(ctx)); - answer.setWsServerBootstrap(createWsServerBootstrap(ctx)); - return answer; - } - - protected EzyServerContext newContext() { - return EzyContextBuilderImpl.builder().boss(boss).build(); - } - - protected ServerBootstrap createServerBootstrap(EzyServerContext ctx) { - return createServerBootstrap(newServerBootstrapCreator(), ctx); - } - - protected ServerBootstrap createWsServerBootstrap(EzyServerContext ctx) { - return createServerBootstrap(newWsServerBootstrapCreator(), ctx); - } - - protected EzyServerBootstrapCreator newServerBootstrapCreator() { - return EzyServerBootstrapCreator.newInstance() - .port(port) - .codecCreator(newCodecCreator()); - } - - protected EzyWsServerBootstrapCreator newWsServerBootstrapCreator() { - return EzyWsServerBootstrapCreator.newInstance() - .port(wsport) - .codecCreator(newWsCodecCreator()); - } - - protected SslContext createWsSslContext() { - try { - return tryCreateWsSslContext(); - } - catch(Exception e) { - throw new IllegalStateException("can not create ssl context", e); - } - } - - protected SslContext tryCreateWsSslContext() throws Exception { - SelfSignedCertificate cert = new SelfSignedCertificate(); - return SslContextBuilder.forServer(cert.certificate(), cert.privateKey()).build(); - } - - protected ServerBootstrap createServerBootstrap( - EzyAbstractBootstrapCreator creator, EzyServerContext ctx) { - return creator - .context(ctx) - .childGroup(childGroup) - .parentGroup(parentGroup) - .create(); - } - - protected EventLoopGroup newParentEventLoopGroup() { - return new NioEventLoopGroup(0, EzyExecutors.newThreadFactory("parenteventloopgroup")); - } - - protected EventLoopGroup newChildEventLoopGroup() { - return new NioEventLoopGroup(0, EzyExecutors.newThreadFactory("childeventloopgroup")); - } - - protected EzyCodecCreator newCodecCreator() { - return EzyClassUtil.newInstance(getCodecCreatorClassName()); - } - - protected EzyCodecCreator newWsCodecCreator() { - return EzyClassUtil.newInstance(getWsCodecCreatorClassName()); - } - - protected String getCodecCreatorClassName() { - return "com.tvd12.ezyfoxserver.codec.MsgPackCodecCreator"; - } - - protected String getWsCodecCreatorClassName() { - return "com.tvd12.ezyfoxserver.codec.JacksonCodecCreator"; - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyServerBootstrapCreator.java deleted file mode 100644 index 683d3bad..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyServerBootstrapCreator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; -import com.tvd12.ezyfoxserver.creator.EzyDataHandlerCreator; -import com.tvd12.ezyfoxserver.creator.impl.EzyDataHandlerCreatorImpl; - -import io.netty.channel.Channel; -import io.netty.channel.ChannelInitializer; - -public class EzyServerBootstrapCreator> - extends EzyAbstractBootstrapCreator { - - protected EzyCodecCreator codecCreator; - - public static EzyServerBootstrapCreator newInstance() { - return new EzyServerBootstrapCreator<>(); - } - - public C codecCreator(EzyCodecCreator codecCreator) { - this.codecCreator = codecCreator; - return getThis(); - } - - @Override - protected ChannelInitializer newChannelInitializer() { - return newChannelInitializerBuilder() - .codecCreator(codecCreator) - .dataHandlerCreator(newDataHandlerCreator()) - .build(); - } - - protected EzyChannelInitializer.Builder newChannelInitializerBuilder() { - return EzyChannelInitializer.builder(); - } - - protected EzyDataHandlerCreator newDataHandlerCreator() { - return EzyDataHandlerCreatorImpl.builder() - .context(context) - .build(); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsChannelInitializer.java deleted file mode 100644 index 9931b104..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsChannelInitializer.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.codec.EzyCombinedCodec; -import com.tvd12.ezyfoxserver.handler.EzyWsFrameHandler; - -import io.netty.channel.Channel; -import io.netty.channel.ChannelInboundHandler; -import io.netty.channel.ChannelOutboundHandler; -import io.netty.channel.ChannelPipeline; -import io.netty.handler.codec.http.HttpObjectAggregator; -import io.netty.handler.codec.http.HttpServerCodec; -import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; -import io.netty.handler.stream.ChunkedWriteHandler; - -class EzyWsChannelInitializer extends EzyChannelInitializer { - - protected EzyWsChannelInitializer(Builder builder) { - super(builder); - } - - @Override - protected void initChannel(Channel ch, - ChannelOutboundHandler encoder, - ChannelInboundHandler decoder) throws Exception { - ChannelPipeline pipeline = ch.pipeline(); - pipeline.addLast(new HttpServerCodec()); - pipeline.addLast(new HttpObjectAggregator(64 * 1024)); - pipeline.addLast(new ChunkedWriteHandler()); - pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); - pipeline.addLast(new EzyWsFrameHandler()); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); - pipeline.addLast(newDataHandler()); - pipeline.addLast(new EzyCombinedCodec(decoder, encoder)); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyChannelInitializer.Builder { - - public EzyWsChannelInitializer build() { - return new EzyWsChannelInitializer(this); - } - - } -} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureChannelInitializer.java deleted file mode 100644 index 57ee5b5e..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureChannelInitializer.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import javax.net.ssl.SSLEngine; - -import io.netty.channel.Channel; -import io.netty.handler.ssl.SslContext; -import io.netty.handler.ssl.SslHandler; - -class EzyWsSecureChannelInitializer extends EzyWsChannelInitializer { - - private SslContext sslContext; - - protected EzyWsSecureChannelInitializer(Builder builder) { - super(builder); - this.sslContext = builder.sslContext; - } - - @Override - protected void initChannel(Channel ch) throws Exception { - super.initChannel(ch); - SSLEngine engine = sslContext.newEngine(ch.alloc()); - ch.pipeline().addFirst(new SslHandler(engine)); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzyWsChannelInitializer.Builder { - private SslContext sslContext; - - public Builder sslContext(SslContext sslContext) { - this.sslContext = sslContext; - return this; - } - - @Override - public EzyWsChannelInitializer build() { - return new EzyWsSecureChannelInitializer(this); - } - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureServerBootstrapCreator.java deleted file mode 100644 index ad8af1d8..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsSecureServerBootstrapCreator.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.builder.impl.EzyWsChannelInitializer.Builder; - -import io.netty.handler.ssl.SslContext; - -public class EzyWsSecureServerBootstrapCreator - extends EzyWsServerBootstrapCreator { - - private SslContext sslContext; - - public static EzyWsSecureServerBootstrapCreator newInstance() { - return new EzyWsSecureServerBootstrapCreator(); - } - - public EzyWsSecureServerBootstrapCreator sslContext(SslContext sslContext) { - this.sslContext = sslContext; - return this; - } - - @Override - protected Builder newWsChannelInitializerBuilder() { - return EzyWsSecureChannelInitializer.builder() - .sslContext(sslContext); - } -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsServerBootstrapCreator.java deleted file mode 100644 index 6850031e..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyWsServerBootstrapCreator.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.tvd12.ezyfoxserver.builder.impl; - -import com.tvd12.ezyfoxserver.builder.impl.EzyChannelInitializer.Builder; - -public class EzyWsServerBootstrapCreator> - extends EzyServerBootstrapCreator { - - public static EzyWsServerBootstrapCreator newInstance() { - return new EzyWsServerBootstrapCreator<>(); - } - - @Override - protected Builder newChannelInitializerBuilder() { - return newWsChannelInitializerBuilder(); - } - - protected EzyWsChannelInitializer.Builder newWsChannelInitializerBuilder() { - return EzyWsChannelInitializer.builder(); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java deleted file mode 100644 index d27cd480..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCodecCreator.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.channel.ChannelOutboundHandler; - -public interface EzyCodecCreator { - - ChannelOutboundHandler newEncoder(); - - ChannelInboundHandlerAdapter newDecoder(); - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandler.java deleted file mode 100644 index d8f0353f..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandler.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import java.util.List; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; - -public interface EzyDecodeHandler { - - /** - * Get next state - * - * @return the next state - */ - EzyIDecodeState nextState(); - - /** - * Get next handler corresponding the next state - * - * @return the next handler - */ - EzyDecodeHandler nextHandler(); - - /** - * Handler decoding - * - * @param in the input - * @param out the output - * @return true if decoding is successful or not - */ - boolean handle(ByteBuf in, List out); - - /** - * Handler decoding - * - * @param ctx the context - * @param in the input - * @param out the output - * @return true if decoding is successful or not - */ - default boolean handle(final ChannelHandlerContext ctx, - final ByteBuf in, final List out) { - return handle(in, out); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandlers.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandlers.java deleted file mode 100644 index 94009c64..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyDecodeHandlers.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; - -public abstract class EzyDecodeHandlers { - - protected EzyIDecodeState state; - protected Map handers; - - protected EzyDecodeHandlers(AbstractBuilder builder) { - this.state = firstState(); - this.handers = builder.newHandlers(); - } - - public void handle(ChannelHandlerContext ctx, - ByteBuf in, List out) { - handle(in, out); - } - - protected void handle(ByteBuf in, List out) { - EzyDecodeHandler handler = handers.get(state); - while(handler != null && handler.handle(in, out)) { - state = handler.nextState(); - handler = handler.nextHandler(); - } - } - - protected EzyIDecodeState firstState() { - return EzyDecodeState.PREPARE_MESSAGE; - } - - public abstract static class AbstractBuilder { - protected Map newHandlers() { - Map answer = new HashMap<>(); - addHandlers(answer); - return answer; - } - - protected abstract void addHandlers(Map answer); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageReader.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageReader.java deleted file mode 100644 index 83a81bc6..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyMessageReader.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import io.netty.buffer.ByteBuf; - -public class EzyMessageReader { - - private int size; - private byte[] content; - private EzyMessageHeader header; - - public EzyMessageReader() { - clear(); - } - - public boolean readHeader(ByteBuf buf) { - if(buf.readableBytes() < getHeaderLength()) - return false; - readHeader(buf.readByte()); - return true; - } - - public boolean readSize(ByteBuf buf) { - if(buf.readableBytes() < getSizeLength()) - return false; - this.size = buf.readInt(); - return true; - } - - public boolean readContent(ByteBuf buf) { - if(buf.readableBytes() < size) - return false; - this.content = new byte[size]; - buf.readBytes(content); - return true; - } - - public void clear() { - this.size = 0; - this.content = new byte[0]; - } - - public EzyMessage get() { - return EzyMessageBuilder.messageBuilder() - .header(header) - .size(size) - .content(content) - .build(); - } - - private void readHeader(byte header) { - this.header = new EzyMessageHeaderReader().read(header); - } - - protected int getSizeLength() { - return header.isBigSize() ? 4 : 2; - } - - protected int getHeaderLength() { - return 1; - } -} - -class EzyMessageHeaderReader { - - protected boolean bigSize; - protected boolean encrypted; - protected boolean compressed; - - protected boolean readBigSize(byte header) { - return (header & 1) > 0; - } - - protected boolean readEncrypted(byte header) { - return (header & (1 << 1)) > 0; - } - - protected boolean readCompressed(byte header) { - return (header & (2 << 1)) > 0; - } - - public EzyMessageHeader read(byte header) { - return EzyMessageBuilder - .headerBuilder() - .bigSize(readBigSize(header)) - .encrypted(readEncrypted(header)) - .compressed(readCompressed(header)) - .build(); - } -} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageToBytes.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageToBytes.java deleted file mode 100644 index f9ddff3d..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzySimpleMessageToBytes.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import java.util.HashMap; -import java.util.Map; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import lombok.Builder; - -@Builder -@SuppressWarnings("rawtypes") -public class EzySimpleMessageToBytes implements EzyMessageToBytes { - - private static final Map CONVERTERS; - - static { - CONVERTERS = defaultConverters(); - } - - @SuppressWarnings("unchecked") - @Override - public T convert(EzyMessage message, Class type) { - return (T) getConverters().get(type).convert(message); - } - - protected Map getConverters() { - return CONVERTERS; - } - - private static Map defaultConverters() { - Map answer = new HashMap<>(); - answer.put(ByteBuf.class, new MessageToByteBuf()); - return answer; - } - -} - -interface Converter { - T convert(EzyMessage message); -} - -class MessageToByteBuf implements Converter { - - @Override - public ByteBuf convert(EzyMessage message) { - ByteBuf answer = newByteBuf(message); - writeHeader(answer, message); - writeSize(answer, message); - writeContent(answer, message); - return answer; - } - - private void writeHeader(ByteBuf answer, EzyMessage message) { - writeHeader(answer, message.getHeader()); - } - - private void writeHeader(ByteBuf answer, EzyMessageHeader header) { - byte headerByte = 0; - headerByte |= header.isBigSize() ? 1 : 0; - headerByte |= header.isEncrypted() ? 1 << 1 : 0; - headerByte |= header.isCompressed() ? 1 << 2 : 0; - answer.writeByte(headerByte); - } - - private void writeSize(ByteBuf answer, EzyMessage message) { - if(message.hasBigSize()) - answer.writeInt(message.getSize()); - else - answer.writeShort(message.getSize()); - } - - private void writeContent(ByteBuf answer, EzyMessage message) { - answer.writeBytes(message.getContent()); - } - - private ByteBuf newByteBuf(EzyMessage message) { - return Unpooled.buffer(getCapacity(message)); - } - - private int getCapacity(EzyMessage message){ - return 1 + message.getSizeLength() + message.getContent().length; - } - -} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/EzyDataHandlerCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/EzyDataHandlerCreator.java deleted file mode 100644 index 0b9e9b3c..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/EzyDataHandlerCreator.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.tvd12.ezyfoxserver.creator; - -import io.netty.channel.ChannelHandler; - -public interface EzyDataHandlerCreator { - - ChannelHandler newHandler(); - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/impl/EzyDataHandlerCreatorImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/impl/EzyDataHandlerCreatorImpl.java deleted file mode 100644 index d82b7afc..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/creator/impl/EzyDataHandlerCreatorImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.tvd12.ezyfoxserver.creator.impl; - -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.creator.EzyDataHandlerCreator; -import com.tvd12.ezyfoxserver.handler.EzyChannelDataHandler; -import com.tvd12.ezyfoxserver.handler.EzyDataHandler; -import com.tvd12.ezyfoxserver.handler.EzyUserHandler; - -import io.netty.channel.ChannelHandler; -import lombok.Builder; - -@Builder -public class EzyDataHandlerCreatorImpl implements EzyDataHandlerCreator { - - private EzyServerContext context; - - @Override - public ChannelHandler newHandler() { - EzyChannelDataHandler handler = new EzyChannelDataHandler(); - handler.setDataHandler(newDataHandler()); - return handler; - } - - protected EzyDataHandler newDataHandler() { - EzyUserHandler handler = new EzyUserHandler(); - handler.setContext(context); - return handler; - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleSession.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleSession.java deleted file mode 100644 index 37617bbc..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzySimpleSession.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.tvd12.ezyfoxserver.entity; - -import java.net.SocketAddress; - -import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; -import com.tvd12.ezyfoxserver.entity.EzyData; - -import io.netty.channel.Channel; -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -public class EzySimpleSession extends EzyAbstractSession implements EzyNettySession { - - protected Channel channel; - - @Override - public SocketAddress getClientAddress() { - return channel.remoteAddress(); - } - - @Override - public SocketAddress getServerAddress() { - return channel.localAddress(); - } - - @Override - public void send(EzyData data) { - channel.writeAndFlush(data); - } - - @Override - public void disconnect() { - channel.disconnect().syncUninterruptibly(); - } - - @Override - public void close() { - channel.close().syncUninterruptibly(); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/factory/EzyNettySessionFactory.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/factory/EzyNettySessionFactory.java deleted file mode 100644 index f454164a..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/factory/EzyNettySessionFactory.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.tvd12.ezyfoxserver.factory; - -import com.tvd12.ezyfoxserver.entity.EzyNettySession; -import com.tvd12.ezyfoxserver.entity.EzySimpleSession; - -public class EzyNettySessionFactory extends EzyAbstractSessionFactory { - - @Override - protected EzyNettySession newSession() { - return new EzySimpleSession(); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyChannelDataHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyChannelDataHandler.java deleted file mode 100644 index f122bb34..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyChannelDataHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.tvd12.ezyfoxserver.handler; - -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInboundHandlerAdapter; -import lombok.Setter; - -/** - * Created by tavandung12 on 1/17/17. - */ -public class EzyChannelDataHandler extends ChannelInboundHandlerAdapter { - - @Setter - protected EzyDataHandler dataHandler; - - @Override - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - dataHandler.handlerAdded(ctx); - } - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - dataHandler.handlerRemoved(ctx); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - dataHandler.channelRead(ctx, msg); - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { - dataHandler.channelReadComplete(ctx); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - dataHandler.exceptionCaught(ctx, cause); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyDataHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyDataHandler.java deleted file mode 100644 index c785db11..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyDataHandler.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.tvd12.ezyfoxserver.handler; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.delegate.EzySessionAdapter; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyNettySession; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.wrapper.EzyNettySessionManager; - -import io.netty.channel.ChannelHandlerContext; -import lombok.Getter; - -public abstract class EzyDataHandler extends EzySessionAdapter { - - @Getter - protected Logger logger; - @Getter - protected EzyNettySession session; - - protected EzyServerContext context; - - protected EzyNettySessionManager sessionManager; - - { - this.logger = LoggerFactory.getLogger(getClass()); - } - - protected abstract void sessionAdded(EzySession session); - protected abstract void dataReceived(EzySession session, EzyArray msg); - - public void handlerAdded(ChannelHandlerContext ctx) throws Exception { - handlerAdded(ctx, borrowSession(ctx)); - } - - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - logger.debug("data handler removed"); - } - - protected EzySession borrowSession(ChannelHandlerContext ctx) { - session = sessionManager.borrowSession(ctx.channel()); - session.setDelegate(this); - return session; - } - - protected void returnSession(ChannelHandlerContext ctx) { - sessionManager.returnSession(session); - } - - private void handlerAdded(ChannelHandlerContext ctx, EzySession session) { - updateSessionAll(ctx, session); - sessionAdded(session); - } - - private void updateSessionAll(ChannelHandlerContext ctx, EzySession session) { - session.setCreationTime(System.currentTimeMillis()); - session.setLastActivityTime(System.currentTimeMillis()); - session.setLastReadTime(System.currentTimeMillis()); - session.setLastWriteTime(System.currentTimeMillis()); - session.setProperty(ChannelHandlerContext.class, ctx); - } - - public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { - dataReceived(session, (EzyArray)msg); - } - - public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { - logger.debug("channel read complete"); - } - - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { - getLogger().error("exception caught at session " + session, cause); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionHandler.java deleted file mode 100644 index 1548dac6..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzySessionHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.tvd12.ezyfoxserver.handler; - -import com.tvd12.ezyfoxserver.EzyServer; -import com.tvd12.ezyfoxserver.command.EzyRunWorker; -import com.tvd12.ezyfoxserver.constant.EzyCommand; -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.context.EzyAppContext; -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.controller.EzyController; -import com.tvd12.ezyfoxserver.entity.EzyArray; -import com.tvd12.ezyfoxserver.entity.EzyData; -import com.tvd12.ezyfoxserver.entity.EzySession; -import com.tvd12.ezyfoxserver.exception.EzyRequestHandleException; -import com.tvd12.ezyfoxserver.interceptor.EzyInterceptor; -import com.tvd12.ezyfoxserver.wrapper.EzyControllers; -import com.tvd12.ezyfoxserver.wrapper.EzyManagers; -import com.tvd12.ezyfoxserver.wrapper.EzyNettySessionManager; -import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; - -import lombok.Setter; - -public class EzySessionHandler extends EzyDataHandler { - - @Setter - protected EzyControllers controllers; - - @Override - protected void sessionAdded(EzySession session) { - getLogger().debug("add session: {}", session); - } - - @Override - protected void dataReceived(EzySession session, EzyArray msg) { - getLogger().debug("from session: {}", session); - int cmdId = msg.get(0); - EzyData data = msg.get(1); - EzyConstant cmd = EzyCommand.valueOf(cmdId); - handleRequest(cmd, data); - getLogger().debug("command {}, data {}", cmd, data); - } - - protected void handleRequest(EzyConstant cmd, EzyData data) { - context.get(EzyRunWorker.class).run(() -> - tryHandleRequest(cmd, data) - ); - } - - protected void tryHandleRequest(EzyConstant cmd, EzyData data) { - try { - interceptRequest(controllers.getInterceptor(cmd), data); - handleRequest(controllers.getController(cmd), data); - } - catch(Exception e) { - throw new EzyRequestHandleException(newHandleRequestErrorMessage(cmd, data), e); - } - } - - @SuppressWarnings("rawtypes") - protected void interceptRequest(EzyInterceptor interceptor, EzyData data) - throws Exception { - interceptServerRequest(interceptor, data); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected void interceptServerRequest(EzyInterceptor interceptor, EzyData data) - throws Exception { - interceptor.intercept(context, getReceiver(), data); - } - - @SuppressWarnings("rawtypes") - protected void handleRequest(EzyController controller, EzyData data) { - handleServerRequest(controller, data); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected void handleServerRequest(EzyController controller, EzyData data) { - controller.handle(context, getReceiver(), data); - } - - protected Object getReceiver() { - return session; - } - - protected EzyAppContext getAppContext(int appId) { - return context.getAppContext(appId); - } - - public void setContext(EzyServerContext ctx) { - this.context = ctx; - this.controllers = getBoss().getControllers(); - this.sessionManager = getSessionManager(); - } - - protected EzyServer getBoss() { - return context.getBoss(); - } - - protected EzyManagers getManagers() { - return getBoss().getManagers(); - } - - protected EzyNettySessionManager getSessionManager() { - return (EzyNettySessionManager) getManagers().getManager(EzySessionManager.class); - } - - protected String newHandleRequestErrorMessage(EzyConstant cmd, EzyData data) { - return "error when handle request command: " + cmd + ", data: " + data; - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserHandler.java deleted file mode 100644 index 789bc485..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyUserHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.tvd12.ezyfoxserver.handler; - -import com.tvd12.ezyfoxserver.command.EzyDisconnectUser; -import com.tvd12.ezyfoxserver.constant.EzyConstant; -import com.tvd12.ezyfoxserver.context.EzyServerContext; -import com.tvd12.ezyfoxserver.entity.EzyUser; -import com.tvd12.ezyfoxserver.wrapper.EzyUserManager; - -import io.netty.channel.ChannelHandlerContext; - -public class EzyUserHandler extends EzySessionHandler { - - protected EzyUser user; - protected EzyUserManager userManager; - - @Override - public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { - super.handlerRemoved(ctx); - this.chechAndRemoveUser(); - } - - protected void chechAndRemoveUser() { - if(user != null) - removeUser(); - } - - protected void removeUser() { - userManager.removeUser(user); - user.setSession(null); - } - - @Override - protected Object getReceiver() { - return user != null ? user : checkAndGetReceiver(); - } - - protected Object checkAndGetReceiver() { - if(userManager.containsUser(getSession())) - user = userManager.getUser(getSession()); - return user != null ? user : super.getReceiver(); - } - - @Override - public void setContext(EzyServerContext ctx) { - super.setContext(ctx); - this.userManager = getManagers().getManager(EzyUserManager.class); - } - - @Override - public void onSessionReturned(EzyConstant reason) { - newDisconnectUser(reason).execute(); - } - - protected EzyDisconnectUser newDisconnectUser(EzyConstant reason) { - return context.get(EzyDisconnectUser.class) - .session(session) - .user(user) - .reason(reason); - } - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyServerBootstrap.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyServerBootstrap.java similarity index 82% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyServerBootstrap.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyServerBootstrap.java index 205fc9c8..28207194 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/EzyNettyServerBootstrap.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyServerBootstrap.java @@ -1,4 +1,6 @@ -package com.tvd12.ezyfoxserver; +package com.tvd12.ezyfoxserver.netty; + +import com.tvd12.ezyfoxserver.EzyServerBootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; @@ -21,24 +23,25 @@ public class EzyNettyServerBootstrap extends EzyServerBootstrap { protected ChannelFuture wsChannelFuture; @Override - protected void startOtherBootstraps() throws Exception { + protected void startOtherBootstraps(Runnable callback) throws Exception { startServerBootstrap(); startWsServerBootstrap(); + callback.run(); waitAndCloseChannelFuture(); waitAndCloseWsChannelFuture(); waitAndShutdownEventLoopGroups(); } protected void startServerBootstrap() throws Exception { - getLogger().debug("starting server bootstrap ...."); + getLogger().debug("starting tcp socket server bootstrap ...."); channelFuture = serverBootstrap.bind().sync(); - getLogger().debug("server bootstrap started"); + getLogger().debug("tcp socket server bootstrap has started"); } protected void startWsServerBootstrap() throws Exception { - getLogger().debug("starting server bootstrap ...."); + getLogger().debug("starting websocket server bootstrap ...."); wsChannelFuture = wsServerBootstrap.bind().sync(); - getLogger().debug("server bootstrap started"); + getLogger().debug("websockt server bootstrap has started"); } @SuppressWarnings("unchecked") diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyStarter.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyStarter.java new file mode 100644 index 00000000..fe5af98b --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyStarter.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.netty; + +import com.tvd12.ezyfoxserver.EzyLoader; +import com.tvd12.ezyfoxserver.EzyStarter; +import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.netty.builder.impl.EzyNettyServerBootstrapBuilderImpl; +import com.tvd12.ezyfoxserver.netty.wrapper.impl.EzyNettySessionManagerImpl; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; + +public class EzyNettyStarter extends EzyStarter { + + protected EzyNettyStarter(Builder builder) { + super(builder); + } + + @Override + protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { + return new EzyNettyServerBootstrapBuilderImpl(); + } + + @Override + protected EzyLoader newLoader() { + return new EzyLoader() { + @Override + protected void addManagers(EzyManagers managers) { + managers.addManager(EzySessionManager.class, EzyNettySessionManagerImpl.builder().build()); + } + }; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyStarter.Builder { + @Override + public EzyStarter build() { + return new EzyNettyStarter(this); + } + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/EzyNettyServerBootstrapBuilder.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/EzyNettyServerBootstrapBuilder.java new file mode 100644 index 00000000..f663c2cd --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/EzyNettyServerBootstrapBuilder.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.netty.builder; + +import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; + +public interface EzyNettyServerBootstrapBuilder extends EzyServerBootstrapBuilder { +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyAbstractBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyAbstractBootstrapCreator.java similarity index 96% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyAbstractBootstrapCreator.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyAbstractBootstrapCreator.java index 2d86f27a..8e3e5971 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/builder/impl/EzyAbstractBootstrapCreator.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyAbstractBootstrapCreator.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.builder.impl; +package com.tvd12.ezyfoxserver.netty.builder.impl; import java.net.InetSocketAddress; diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyChannelInitializer.java new file mode 100644 index 00000000..0499e770 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyChannelInitializer.java @@ -0,0 +1,83 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.netty.codec.EzyCombinedCodec; +import com.tvd12.ezyfoxserver.netty.creator.EzyDataHandlerCreator; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelInboundHandler; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelOutboundHandler; +import io.netty.channel.ChannelPipeline; + +class EzyChannelInitializer extends ChannelInitializer { + + protected int maxRequestSize; + protected EzyCodecCreator codecCreator; + protected EzyDataHandlerCreator dataHandlerCreator; + + protected EzyChannelInitializer(Builder builder) { + this.codecCreator = builder.codecCreator; + this.maxRequestSize = builder.maxRequestSize; + this.dataHandlerCreator = builder.dataHandlerCreator; + } + + @Override + protected void initChannel(Channel ch) throws Exception { + initChannel(ch, newEncoder(), newDecoder()); + } + + protected void initChannel(Channel ch, + ChannelOutboundHandler encoder, + ChannelInboundHandler decoder) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast("codec-1", new EzyCombinedCodec(decoder, encoder)); + pipeline.addLast("handler", newDataHandler()); + pipeline.addLast("codec-2", new EzyCombinedCodec(decoder, encoder)); + } + + protected ChannelHandler newDataHandler() { + return dataHandlerCreator.newHandler(EzyConnectionType.SOCKET); + } + + protected ChannelOutboundHandler newEncoder() { + return (ChannelOutboundHandler) codecCreator.newEncoder(); + } + + protected ChannelInboundHandler newDecoder() { + return (ChannelInboundHandler) codecCreator.newDecoder(maxRequestSize); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + protected int maxRequestSize; + private EzyCodecCreator codecCreator; + private EzyDataHandlerCreator dataHandlerCreator; + + public Builder maxRequestSize(int maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return this; + } + + public Builder codecCreator(EzyCodecCreator codecCreator) { + this.codecCreator = codecCreator; + return this; + } + + public Builder dataHandlerCreator(EzyDataHandlerCreator dataHandlerCreator) { + this.dataHandlerCreator = dataHandlerCreator; + return this; + } + + public EzyChannelInitializer build() { + return new EzyChannelInitializer(this); + } + + } +} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyNettyServerBootstrapBuilderImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyNettyServerBootstrapBuilderImpl.java new file mode 100644 index 00000000..60c3ae28 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyNettyServerBootstrapBuilderImpl.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.EzyHttpServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.netty.EzyNettyServerBootstrap; +import com.tvd12.ezyfoxserver.netty.builder.EzyNettyServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; + +public class EzyNettyServerBootstrapBuilderImpl + extends EzyHttpServerBootstrapBuilder + implements EzyNettyServerBootstrapBuilder { + + private EventLoopGroup childGroup; + private EventLoopGroup parentGroup; + + @Override + protected void prebuild() { + childGroup = newChildEventLoopGroup(); + parentGroup = newParentEventLoopGroup(); + } + + @Override + protected EzyNettyServerBootstrap newServerBootstrap() { + EzyNettyServerBootstrap answer = new EzyNettyServerBootstrap(); + answer.setChildGroup(childGroup); + answer.setParentGroup(parentGroup); + answer.setServerBootstrap(createServerBootstrap()); + answer.setWsServerBootstrap(createWsServerBootstrap()); + return answer; + } + + protected ServerBootstrap createServerBootstrap() { + return createServerBootstrap(newServerBootstrapCreator()); + } + + protected ServerBootstrap createWsServerBootstrap() { + return createServerBootstrap(newWsServerBootstrapCreator()); + } + + protected EzyServerBootstrapCreator newServerBootstrapCreator() { + return EzyServerBootstrapCreator.newInstance() + .codecCreator(newCodecCreator()) + .port(getSettings().getSocket().getPort()) + .maxRequestSize(getSocketSettings().getMaxRequestSize()); + } + + protected EzyWsServerBootstrapCreator newWsServerBootstrapCreator() { + return newWsServerBootstrapCreatorFactory().newCreator(); + } + + protected EzyWsServerBootstrapCreatorFactory newWsServerBootstrapCreatorFactory() { + return EzyWsServerBootstrapCreatorFactory.builder() + .wsCodecCreator(newWsCodecCreator()) + .port(getWebsocketSettings().getPort()) + .sslPort(getWebsocketSettings().getSslPort()) + .sslActive(getWebsocketSettings().isSslActive()) + .sslContext(newSslContext(getWebsocketSettings().getSslConfig())) + .maxFrameSize(getWebsocketSettings().getMaxFrameSize()) + .build(); + } + + protected ServerBootstrap createServerBootstrap(EzyAbstractBootstrapCreator creator) { + return creator + .context(serverContext) + .childGroup(childGroup) + .parentGroup(parentGroup) + .create(); + } + + protected EventLoopGroup newParentEventLoopGroup() { + return new NioEventLoopGroup(0, EzyExecutors.newThreadFactory("parenteventloopgroup")); + } + + protected EventLoopGroup newChildEventLoopGroup() { + return new NioEventLoopGroup(0, EzyExecutors.newThreadFactory("childeventloopgroup")); + } + + protected EzyCodecCreator newCodecCreator() { + return EzyClasses.newInstance(getCodecCreatorClassName()); + } + + protected EzyCodecCreator newWsCodecCreator() { + return EzyClasses.newInstance(getWsCodecCreatorClassName()); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerBootstrapCreator.java new file mode 100644 index 00000000..065c6d02 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerBootstrapCreator.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.netty.creator.EzyDataHandlerCreator; +import com.tvd12.ezyfoxserver.netty.creator.impl.EzyDataHandlerCreatorImpl; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelInitializer; + +public class EzyServerBootstrapCreator> + extends EzyAbstractBootstrapCreator { + + protected int maxRequestSize; + protected EzyCodecCreator codecCreator; + + public static EzyServerBootstrapCreator newInstance() { + return new EzyServerBootstrapCreator<>(); + } + + public C maxRequestSize(int maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return getThis(); + } + + public C codecCreator(EzyCodecCreator codecCreator) { + this.codecCreator = codecCreator; + return getThis(); + } + + @Override + protected ChannelInitializer newChannelInitializer() { + return newChannelInitializerBuilder() + .codecCreator(codecCreator) + .maxRequestSize(maxRequestSize) + .dataHandlerCreator(newDataHandlerCreator()) + .build(); + } + + protected EzyChannelInitializer.Builder newChannelInitializerBuilder() { + return EzyChannelInitializer.builder(); + } + + protected EzyDataHandlerCreator newDataHandlerCreator() { + return EzyDataHandlerCreatorImpl.builder() + .context(context) + .build(); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerContextBuilderImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerContextBuilderImpl.java new file mode 100644 index 00000000..0da53dcb --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyServerContextBuilderImpl.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.builder.EzySimpleServerContextBuilder; + +public class EzyServerContextBuilderImpl + extends EzySimpleServerContextBuilder { + + public static EzyServerContextBuilderImpl builder() { + return new EzyServerContextBuilderImpl(); + } +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsChannelInitializer.java new file mode 100644 index 00000000..f9fecd4e --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsChannelInitializer.java @@ -0,0 +1,81 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.netty.codec.EzyCombinedCodec; +import com.tvd12.ezyfoxserver.netty.handler.EzyHttpRequestHandler; +import com.tvd12.ezyfoxserver.netty.handler.EzyWsFrameHandler; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandler; +import io.netty.channel.ChannelOutboundHandler; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.codec.CorruptedFrameException; +import io.netty.handler.codec.http.HttpObjectAggregator; +import io.netty.handler.codec.http.HttpServerCodec; +import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; +import io.netty.handler.stream.ChunkedWriteHandler; + +class EzyWsChannelInitializer extends EzyChannelInitializer { + + protected int maxFrameSize; + + protected EzyWsChannelInitializer(Builder builder) { + super(builder); + this.maxFrameSize = builder.maxFrameSize; + } + + @Override + protected void initChannel(Channel ch, + ChannelOutboundHandler encoder, + ChannelInboundHandler decoder) throws Exception { + ChannelPipeline pipeline = ch.pipeline(); + pipeline.addLast("http-server-codec", new HttpServerCodec()); + pipeline.addLast("http-object-aggregator", new HttpObjectAggregator(64 * 1024)); + pipeline.addLast("chunked-write-andler", new ChunkedWriteHandler()); + pipeline.addLast("http-request-handler", new EzyHttpRequestHandler("/ws")); + pipeline.addLast("ws-server-protocol-handler", newWebSocketServerProtocolHandler()); + pipeline.addLast("ws-frame-handler", new EzyWsFrameHandler()); + pipeline.addLast("codec-1", new EzyCombinedCodec(decoder, encoder)); + pipeline.addLast("handler", newDataHandler()); + pipeline.addLast("codec-2", new EzyCombinedCodec(decoder, encoder)); + } + + @Override + protected ChannelHandler newDataHandler() { + return dataHandlerCreator.newHandler(EzyConnectionType.WEBSOCKET); + } + + protected WebSocketServerProtocolHandler newWebSocketServerProtocolHandler() { + return new WebSocketServerProtocolHandler("/ws", null, false, maxFrameSize) { + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + if(cause instanceof CorruptedFrameException) + ctx.fireExceptionCaught(new EzyMaxRequestSizeException(cause.getMessage())); + else + super.exceptionCaught(ctx, cause); + } + }; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyChannelInitializer.Builder { + + protected int maxFrameSize; + + public Builder maxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + return this; + } + + public EzyWsChannelInitializer build() { + return new EzyWsChannelInitializer(this); + } + + } +} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureChannelInitializer.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureChannelInitializer.java new file mode 100644 index 00000000..69befb22 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureChannelInitializer.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelInboundHandler; +import io.netty.channel.ChannelOutboundHandler; +import io.netty.channel.ChannelPipeline; +import io.netty.handler.ssl.SslHandler; + +class EzyWsSecureChannelInitializer extends EzyWsChannelInitializer { + + private SSLContext sslContext; + + protected EzyWsSecureChannelInitializer(Builder builder) { + super(builder); + this.sslContext = builder.sslContext; + } + + @Override + protected void initChannel(Channel ch, + ChannelOutboundHandler encoder, + ChannelInboundHandler decoder) throws Exception { + super.initChannel(ch, encoder, decoder); + ChannelPipeline pipeline = ch.pipeline(); + SSLEngine engine = sslContext.createSSLEngine(); + engine.setUseClientMode(false); + pipeline.addFirst("ssl-handler", new SslHandler(engine)); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyWsChannelInitializer.Builder { + private SSLContext sslContext; + + public Builder sslContext(SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + @Override + public EzyWsChannelInitializer build() { + return new EzyWsSecureChannelInitializer(this); + } + } +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureServerBootstrapCreator.java new file mode 100644 index 00000000..e1626aa1 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsSecureServerBootstrapCreator.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import javax.net.ssl.SSLContext; + +import com.tvd12.ezyfoxserver.netty.builder.impl.EzyWsChannelInitializer.Builder; + +public class EzyWsSecureServerBootstrapCreator + extends EzyWsServerBootstrapCreator { + + private SSLContext sslContext; + + public static EzyWsSecureServerBootstrapCreator newInstance() { + return new EzyWsSecureServerBootstrapCreator(); + } + + public EzyWsSecureServerBootstrapCreator sslContext(SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + @Override + protected Builder newWsChannelInitializerBuilder() { + return EzyWsSecureChannelInitializer.builder() + .sslContext(sslContext); + } +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreator.java new file mode 100644 index 00000000..10bf27e6 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreator.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import com.tvd12.ezyfoxserver.netty.builder.impl.EzyChannelInitializer.Builder; + +public class EzyWsServerBootstrapCreator> + extends EzyServerBootstrapCreator { + + protected int maxFrameSize; + + public static EzyWsServerBootstrapCreator newInstance() { + return new EzyWsServerBootstrapCreator<>(); + } + + public C maxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + return getThis(); + } + + @Override + protected Builder newChannelInitializerBuilder() { + return newWsChannelInitializerBuilder().maxFrameSize(maxFrameSize); + } + + protected EzyWsChannelInitializer.Builder newWsChannelInitializerBuilder() { + return EzyWsChannelInitializer.builder(); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreatorFactory.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreatorFactory.java new file mode 100644 index 00000000..52d0a44f --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/builder/impl/EzyWsServerBootstrapCreatorFactory.java @@ -0,0 +1,103 @@ +package com.tvd12.ezyfoxserver.netty.builder.impl; + +import javax.net.ssl.SSLContext; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; + +public class EzyWsServerBootstrapCreatorFactory { + + protected int port; + protected int sslPort; + protected int maxFrameSize; + protected boolean sslActive; + protected SSLContext sslContext; + protected EzyCodecCreator wsCodecCreator; + + protected EzyWsServerBootstrapCreatorFactory(Builder builder) { + this.port = builder.port; + this.sslPort = builder.sslPort; + this.sslActive = builder.sslActive; + this.sslContext = builder.sslContext; + this.maxFrameSize = builder.maxFrameSize; + this.wsCodecCreator = builder.wsCodecCreator; + } + + public EzyWsServerBootstrapCreator newCreator() { + return sslActive + ? newWsServerBootstrapCreator(newWsSecureServerBootstrapCreator()) + : newWsServerBootstrapCreator(newWsServerBootstrapCreator()); + } + + protected EzyWsServerBootstrapCreator newWsServerBootstrapCreator( + EzyWsServerBootstrapCreator creator) { + return creator + .port(getPort()) + .maxFrameSize(maxFrameSize) + .maxRequestSize(maxFrameSize) + .codecCreator(wsCodecCreator); + } + + protected EzyWsServerBootstrapCreator newWsServerBootstrapCreator() { + return EzyWsServerBootstrapCreator.newInstance(); + } + + protected EzyWsServerBootstrapCreator newWsSecureServerBootstrapCreator() { + return EzyWsSecureServerBootstrapCreator.newInstance() + .sslContext(sslContext); + } + + protected int getPort() { + return sslActive ? sslPort : port; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder + implements EzyBuilder { + + protected int port; + protected int sslPort; + protected int maxFrameSize; + protected boolean sslActive; + protected SSLContext sslContext; + protected EzyCodecCreator wsCodecCreator; + + public Builder port(int port) { + this.port = port; + return this; + } + + public Builder sslPort(int sslPort) { + this.sslPort = sslPort; + return this; + } + + public Builder maxFrameSize(int maxFrameSize) { + this.maxFrameSize = maxFrameSize; + return this; + } + + public Builder sslActive(boolean sslActive) { + this.sslActive = sslActive; + return this; + } + + public Builder sslContext(SSLContext sslContext) { + this.sslContext = sslContext; + return this; + } + + public Builder wsCodecCreator(EzyCodecCreator wsCodecCreator) { + this.wsCodecCreator = wsCodecCreator; + return this; + } + + @Override + public EzyWsServerBootstrapCreatorFactory build() { + return new EzyWsServerBootstrapCreatorFactory(this); + } + } +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCombinedCodec.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyCombinedCodec.java similarity index 89% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCombinedCodec.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyCombinedCodec.java index fb8209a2..cabd9951 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/codec/EzyCombinedCodec.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyCombinedCodec.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.codec; +package com.tvd12.ezyfoxserver.netty.codec; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelOutboundHandler; diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandler.java new file mode 100644 index 00000000..05c14bef --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandler.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import java.util.List; + +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; + +public interface EzyDecodeHandler { + + /** + * Get next state + * + * @return the next state + */ + EzyIDecodeState nextState(); + + /** + * Get next handler corresponding the next state + * + * @return the next handler + */ + EzyDecodeHandler nextHandler(); + + /** + * Handler decoding + * + * @param in the input + * @param out the output + * @return true if decoding is successful or not + */ + boolean handle(ByteBuf in, List out); + + /** + * Handler decoding + * + * @param ctx the context + * @param in the input + * @param out the output + * @return true if decoding is successful or not + */ + default boolean handle(final ChannelHandlerContext ctx, + final ByteBuf in, final List out) { + return handle(in, out); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandlers.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandlers.java new file mode 100644 index 00000000..8533c065 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyDecodeHandlers.java @@ -0,0 +1,50 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; + +public abstract class EzyDecodeHandlers { + + protected EzyIDecodeState state; + protected Map handers; + + protected EzyDecodeHandlers(AbstractBuilder builder) { + this.state = firstState(); + this.handers = builder.newHandlers(); + } + + public void handle(ChannelHandlerContext ctx, + ByteBuf in, List out) { + handle(in, out); + } + + protected void handle(ByteBuf in, List out) { + EzyDecodeHandler handler = handers.get(state); + while(handler != null && handler.handle(in, out)) { + state = handler.nextState(); + handler = handler.nextHandler(); + } + } + + protected EzyIDecodeState firstState() { + return EzyDecodeState.PREPARE_MESSAGE; + } + + public abstract static class AbstractBuilder { + protected Map newHandlers() { + Map answer = new HashMap<>(); + addHandlers(answer); + return answer; + } + + protected abstract void addHandlers(Map answer); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyMessageReader.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyMessageReader.java new file mode 100644 index 00000000..6265c0c5 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzyMessageReader.java @@ -0,0 +1,103 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeader; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeaderBuilder; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.io.EzyInts; +import com.tvd12.ezyfoxserver.netty.io.EzyByteBufs; + +import io.netty.buffer.ByteBuf; + +public class EzyMessageReader { + + private int size; + private byte[] content; + private EzyMessageHeader header; + + public EzyMessageReader() { + clear(); + } + + public boolean readHeader(ByteBuf buf) { + if(buf.readableBytes() < getHeaderLength()) + return false; + readHeader(buf.readByte()); + return true; + } + + public boolean readSize(ByteBuf buf, int maxSize) { + if(buf.readableBytes() < getSizeLength()) + return false; + this.size = EzyInts.bin2uint(EzyByteBufs.getBytes(buf, getSizeLength())); + if(size > maxSize) + throw new EzyMaxRequestSizeException(size, maxSize); + return true; + } + + public boolean readContent(ByteBuf buf) { + if(buf.readableBytes() < size) + return false; + this.content = new byte[size]; + buf.readBytes(content); + return true; + } + + public void clear() { + this.size = 0; + this.content = new byte[0]; + } + + public EzyMessage get() { + return EzyMessageBuilder.newInstance() + .header(header) + .size(size) + .content(content) + .build(); + } + + private void readHeader(byte header) { + this.header = new EzyMessageHeaderReader().read(header); + } + + protected int getSizeLength() { + return header.isBigSize() ? 4 : 2; + } + + protected int getHeaderLength() { + return 1; + } +} + +class EzyMessageHeaderReader { + + protected boolean bigSize; + protected boolean encrypted; + protected boolean compressed; + + protected boolean readBigSize(byte header) { + return (header & 1) > 0; + } + + protected boolean readEncrypted(byte header) { + return (header & (1 << 1)) > 0; + } + + protected boolean readCompressed(byte header) { + return (header & (1 << 2)) > 0; + } + + protected boolean readText(byte header) { + return (header & (1 << 3)) > 0; + } + + public EzyMessageHeader read(byte header) { + return EzyMessageHeaderBuilder.newInstance() + .bigSize(readBigSize(header)) + .encrypted(readEncrypted(header)) + .compressed(readCompressed(header)) + .text(readText(header)) + .build(); + } +} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzySimpleMessageToBytes.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzySimpleMessageToBytes.java new file mode 100644 index 00000000..bb6da5b5 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/codec/EzySimpleMessageToBytes.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeader; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import lombok.Builder; + +@Builder +public class EzySimpleMessageToBytes implements EzyMessageToBytes { + + @SuppressWarnings("unchecked") + @Override + public ByteBuf convert(EzyMessage message) { + ByteBuf answer = newByteBuf(message); + writeHeader(answer, message); + writeSize(answer, message); + writeContent(answer, message); + return answer; + } + + private void writeHeader(ByteBuf answer, EzyMessage message) { + writeHeader(answer, message.getHeader()); + } + + private void writeHeader(ByteBuf answer, EzyMessageHeader header) { + byte headerByte = 0; + headerByte |= header.isBigSize() ? 1 : 0; + headerByte |= header.isEncrypted() ? 1 << 1 : 0; + headerByte |= header.isCompressed() ? 1 << 2 : 0; + headerByte |= header.isText() ? 1 << 3 : 0; + answer.writeByte(headerByte); + } + + private void writeSize(ByteBuf answer, EzyMessage message) { + if(message.hasBigSize()) + answer.writeInt(message.getSize()); + else + answer.writeShort(message.getSize()); + } + + private void writeContent(ByteBuf answer, EzyMessage message) { + answer.writeBytes(message.getContent()); + } + + private ByteBuf newByteBuf(EzyMessage message) { + return Unpooled.buffer(getCapacity(message)); + } + + private int getCapacity(EzyMessage message){ + return 1 + message.getSizeLength() + message.getContent().length; + } + +} \ No newline at end of file diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/EzyDataHandlerCreator.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/EzyDataHandlerCreator.java new file mode 100644 index 00000000..8ae0c07a --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/EzyDataHandlerCreator.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.netty.creator; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; + +import io.netty.channel.ChannelHandler; + +public interface EzyDataHandlerCreator { + + ChannelHandler newHandler(EzyConnectionType type); + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/impl/EzyDataHandlerCreatorImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/impl/EzyDataHandlerCreatorImpl.java new file mode 100644 index 00000000..918392f5 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/creator/impl/EzyDataHandlerCreatorImpl.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.netty.creator.impl; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.netty.creator.EzyDataHandlerCreator; +import com.tvd12.ezyfoxserver.netty.handler.EzyChannelDataHandler; +import com.tvd12.ezyfoxserver.netty.handler.EzyDataHandler; + +import io.netty.channel.ChannelHandler; +import lombok.Builder; + +@Builder +public class EzyDataHandlerCreatorImpl implements EzyDataHandlerCreator { + + private EzyServerContext context; + + @Override + public ChannelHandler newHandler(EzyConnectionType type) { + EzyChannelDataHandler handler = new EzyChannelDataHandler(); + handler.setConnectionType(type); + handler.setDataHandler(newDataHandler()); + return handler; + } + + protected EzyDataHandler newDataHandler() { + EzyDataHandler handler = new EzyDataHandler(); + handler.setContext(context); + return handler; + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzyNettySession.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzyNettySession.java similarity index 76% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzyNettySession.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzyNettySession.java index 6eb36a57..9e1fafdd 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/entity/EzyNettySession.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzyNettySession.java @@ -1,4 +1,6 @@ -package com.tvd12.ezyfoxserver.entity; +package com.tvd12.ezyfoxserver.netty.entity; + +import com.tvd12.ezyfoxserver.entity.EzySession; import io.netty.channel.Channel; diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzySimpleSession.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzySimpleSession.java new file mode 100644 index 00000000..e907f674 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/entity/EzySimpleSession.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.netty.entity; + +import java.net.SocketAddress; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyData; + +import io.netty.channel.Channel; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzySimpleSession extends EzyAbstractSession implements EzyNettySession { + private static final long serialVersionUID = -6257434105426561446L; + + protected transient Channel channel; + + @Override + public SocketAddress getClientAddress() { + return channel != null ? channel.remoteAddress() : null; + } + + @Override + public SocketAddress getServerAddress() { + return channel != null ? channel.localAddress() : null; + } + + @Override + protected void sendData(EzyData data, EzyTransportType type) { + channel.writeAndFlush(data); + } + + @Override + public void disconnect() { + channel.disconnect().syncUninterruptibly(); + } + + @Override + public void close() { + channel.close().syncUninterruptibly(); + } + + @Override + public void destroy() { + super.destroy(); + this.setChannel(null); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/factory/EzyNettySessionFactory.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/factory/EzyNettySessionFactory.java new file mode 100644 index 00000000..8f7b39a7 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/factory/EzyNettySessionFactory.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.netty.factory; + +import com.tvd12.ezyfoxserver.factory.EzyAbstractSessionFactory; +import com.tvd12.ezyfoxserver.netty.entity.EzyNettySession; +import com.tvd12.ezyfoxserver.netty.entity.EzySimpleSession; + +public class EzyNettySessionFactory extends EzyAbstractSessionFactory { + + @Override + protected EzyNettySession newSession() { + return new EzySimpleSession(); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesReceived.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesReceived.java new file mode 100644 index 00000000..69c673bc --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesReceived.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.netty.handler; + +public interface EzyBytesReceived { + + void bytesReceived(int count); + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesSent.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesSent.java new file mode 100644 index 00000000..334b46e6 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyBytesSent.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.netty.handler; + +public interface EzyBytesSent { + + void bytesSent(int count); + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyChannelDataHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyChannelDataHandler.java new file mode 100644 index 00000000..451f3a71 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyChannelDataHandler.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.netty.handler; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import lombok.Setter; + +/** + * Created by tavandung12 on 1/17/17. + */ +public class EzyChannelDataHandler + extends ChannelInboundHandlerAdapter + implements EzyBytesReceived, EzyBytesSent { + + @Setter + protected EzyDataHandler dataHandler; + + @Setter + protected EzyConnectionType connectionType; + + @Override + public void bytesReceived(int count) { + dataHandler.bytesReceived(count); + } + + @Override + public void bytesSent(int count) { + dataHandler.bytesSent(count); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + dataHandler.channelActive(ctx, connectionType); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + dataHandler.channelInactive(ctx); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + dataHandler.channelRead(ctx, msg); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + dataHandler.exceptionCaught(ctx, cause); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyDataHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyDataHandler.java new file mode 100644 index 00000000..4629678b --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyDataHandler.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.netty.handler; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.handler.EzySimpleDataHandler; +import com.tvd12.ezyfoxserver.netty.entity.EzyNettySession; +import com.tvd12.ezyfoxserver.netty.wrapper.EzyNettySessionManager; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.DecoderException; + +public class EzyDataHandler extends EzySimpleDataHandler { + + public void channelActive(ChannelHandlerContext ctx, EzyConnectionType type) throws Exception { + getLogger().debug("channel actived, connection type = {}", type); + borrowSession(ctx, type); + handleSessionActive(ctx); + } + + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + getLogger().debug("channel {} inactive", ctx.channel().remoteAddress()); + channelInactive(); + } + + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + dataReceived((EzyArray)msg); + } + + public void bytesReceived(int count) { + session.addReadBytes(count); + } + + public void bytesSent(int count) { + session.addWrittenBytes(count); + } + + public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) throws Exception { + Throwable cause = throwable; + if(throwable instanceof DecoderException) { + cause = throwable.getCause(); + } + if(cause instanceof EzyMaxRequestSizeException) { + getLogger().warn("exception: {}", cause.getMessage()); + exceptionCaught(cause); + } + else { + getLogger().debug("exception caught at session " + ctx.channel().remoteAddress(), cause); + ctx.close(); + } + } + + private void borrowSession(ChannelHandlerContext ctx, EzyConnectionType type) { + borrowSession(() -> newSession(ctx, type)); + } + + private EzyNettySession newSession(ChannelHandlerContext ctx, EzyConnectionType type) { + return getNettySessionManager().borrowSession(ctx.channel(), type); + } + + private void handleSessionActive(ChannelHandlerContext ctx) { + updateSession(ctx); + sessionActive(); + } + + private void updateSession(ChannelHandlerContext ctx) { + session.setProperty(ChannelHandlerContext.class, ctx); + } + + private EzyNettySessionManager getNettySessionManager() { + return (EzyNettySessionManager)sessionManager; + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyHttpRequestHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyHttpRequestHandler.java new file mode 100644 index 00000000..4d208d23 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyHttpRequestHandler.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.netty.handler; + +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.SimpleChannelInboundHandler; +import io.netty.handler.codec.http.FullHttpRequest; + +public class EzyHttpRequestHandler + extends SimpleChannelInboundHandler { + + protected final String wsUri; + + public EzyHttpRequestHandler(String wsUri) { + this.wsUri = wsUri; + } + + @Override + public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) + throws Exception { + if (wsUri.equalsIgnoreCase(request.uri())) + ctx.fireChannelRead(request.retain()); + } + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyWsFrameHandler.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyWsFrameHandler.java similarity index 80% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyWsFrameHandler.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyWsFrameHandler.java index 572ae0c2..8b498c7e 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/handler/EzyWsFrameHandler.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/handler/EzyWsFrameHandler.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.handler; +package com.tvd12.ezyfoxserver.netty.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,11 +14,7 @@ */ public class EzyWsFrameHandler extends ChannelInboundHandlerAdapter { - protected Logger logger; - - { - logger = LoggerFactory.getLogger(getClass()); - } + protected Logger logger = LoggerFactory.getLogger(getClass()); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) @@ -28,8 +24,11 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) protected void channelRead(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { - logger.debug("web socket request text: {}", msg.text()); ctx.fireChannelRead(msg.content()); } + protected Logger getLogger() { + return logger; + } + } diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBufs.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/io/EzyByteBufs.java similarity index 80% rename from ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBufs.java rename to ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/io/EzyByteBufs.java index 99cbaa04..313ee238 100644 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBufs.java +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/io/EzyByteBufs.java @@ -1,8 +1,8 @@ -package com.tvd12.ezyfoxserver.io; +package com.tvd12.ezyfoxserver.netty.io; import io.netty.buffer.ByteBuf; -public abstract class EzyByteBufs { +public final class EzyByteBufs { private EzyByteBufs() { } diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/EzyNettySessionManager.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/EzyNettySessionManager.java new file mode 100644 index 00000000..5d8219b5 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/EzyNettySessionManager.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.netty.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.netty.entity.EzyNettySession; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; + +import io.netty.channel.Channel; + +public interface EzyNettySessionManager extends EzySessionManager { + + /** + * Get session by channel + * + * @param channel the channel + * @return the session mapped to the channel + */ + EzyNettySession getSession(Channel channel); + + /** + * Borrow session from pool and map the session to channel + * + * @param channel the channel + * @param type the connection type + * @return the session mapped channel + */ + EzyNettySession borrowSession(Channel channel, EzyConnectionType type); + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/impl/EzyNettySessionManagerImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/impl/EzyNettySessionManagerImpl.java new file mode 100644 index 00000000..a2241293 --- /dev/null +++ b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/netty/wrapper/impl/EzyNettySessionManagerImpl.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.netty.wrapper.impl; + +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.netty.entity.EzyNettySession; +import com.tvd12.ezyfoxserver.netty.factory.EzyNettySessionFactory; +import com.tvd12.ezyfoxserver.netty.wrapper.EzyNettySessionManager; +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.wrapper.EzySimpleSessionManager; + +import io.netty.channel.Channel; + +public class EzyNettySessionManagerImpl + extends EzySimpleSessionManager + implements EzyNettySessionManager { + + protected ConcurrentHashMap sessionsByChannel + = new ConcurrentHashMap<>(); + + protected EzyNettySessionManagerImpl(Builder builder) { + super(builder); + } + + @Override + protected void unmapSession(EzyNettySession session) { + super.unmapSession(session); + sessionsByChannel.remove(session.getChannel()); + } + + @Override + protected void clearSession(EzyNettySession session) { + super.clearSession(session); + session.setChannel(null); + } + + @Override + public EzyNettySession getSession(Channel channel) { + return sessionsByChannel.get(channel); + } + + @Override + public EzyNettySession borrowSession(Channel channel, EzyConnectionType type) { + EzyNettySession ss = borrowSession(type); + ss.setChannel(channel); + sessionsByChannel.put(channel, ss); + return ss; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleSessionManager.Builder { + + @Override + public EzyNettySessionManagerImpl build() { + return new EzyNettySessionManagerImpl(this); + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyNettySessionFactory(); + } + } + + +} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyNettySessionManager.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyNettySessionManager.java deleted file mode 100644 index 0e0f055d..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/EzyNettySessionManager.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.tvd12.ezyfoxserver.wrapper; - -import com.tvd12.ezyfoxserver.entity.EzyNettySession; - -import io.netty.channel.Channel; - -public interface EzyNettySessionManager extends EzySessionManager { - - /** - * Borrow session from pool and map the session to channel - * - * @param channel the channel - * @return the session mapped channel - */ - EzyNettySession borrowSession(Channel channel); - - /** - * Get session by channel - * - * @param channel the channel - * @return the session mapped to the channel - */ - EzyNettySession getSession(Channel channel); - -} diff --git a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyNettySessionManagerImpl.java b/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyNettySessionManagerImpl.java deleted file mode 100644 index 8bdfae0a..00000000 --- a/ezyfox-server-netty/src/main/java/com/tvd12/ezyfoxserver/wrapper/impl/EzyNettySessionManagerImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.tvd12.ezyfoxserver.wrapper.impl; - -import java.util.concurrent.ConcurrentHashMap; - -import com.tvd12.ezyfoxserver.entity.EzyNettySession; -import com.tvd12.ezyfoxserver.factory.EzyNettySessionFactory; -import com.tvd12.ezyfoxserver.factory.EzySessionFactory; -import com.tvd12.ezyfoxserver.wrapper.EzyNettySessionManager; -import com.tvd12.ezyfoxserver.wrapper.EzySimpleSessionManager; - -import io.netty.channel.Channel; - -public class EzyNettySessionManagerImpl - extends EzySimpleSessionManager - implements EzyNettySessionManager { - - protected ConcurrentHashMap sessionsByChannel; - - protected EzyNettySessionManagerImpl(Builder builder) { - super(builder); - } - - @SuppressWarnings("rawtypes") - @Override - protected void initComponents(AbstractBuilder builder) { - super.initComponents(builder); - sessionsByChannel = new ConcurrentHashMap<>(); - } - - @Override - protected void unmapSession(EzyNettySession session) { - super.unmapSession(session); - sessionsByChannel.remove(session.getChannel()); - } - - @Override - protected void clearSession(EzyNettySession session) { - super.clearSession(session); - session.setChannel(null); - } - - @Override - public EzyNettySession getSession(Channel channel) { - return sessionsByChannel.get(channel); - } - - @Override - public EzyNettySession borrowSession(Channel channel) { - EzyNettySession ss = borrowSession(); - ss.setChannel(channel); - sessionsByChannel.putIfAbsent(channel, ss); - return ss; - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends EzySimpleSessionManager.Builder { - @Override - protected EzySessionFactory newSessionFactory() { - return new EzyNettySessionFactory(); - } - - @Override - protected EzyNettySessionManagerImpl newProduct() { - return new EzyNettySessionManagerImpl(this); - } - - @Override - public EzyNettySessionManagerImpl build() { - return (EzyNettySessionManagerImpl) super.build(); - } - } - - -} diff --git a/ezyfox-server-nettycodec/pom.xml b/ezyfox-server-nettycodec/pom.xml index 3ba62324..aedbd02f 100644 --- a/ezyfox-server-nettycodec/pom.xml +++ b/ezyfox-server-nettycodec/pom.xml @@ -6,27 +6,34 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-nettycodec 1.0.0 ezyfox-server-nettycodec http://maven.apache.org + + + 1.0.0 + 1.0.0 + 1.0.0 + + com.tvd12 ezyfox-server-netty - 1.0.0 + ${ezy.netty.version} com.tvd12 ezyfox-server-msgpack - 1.0.0 + ${ezy.msgpack.version} com.tvd12 ezyfox-server-jackson - 1.0.0 + ${ezy.jackson.version} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonByteToMessageDecoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonByteToMessageDecoder.java deleted file mode 100644 index a32a9be2..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonByteToMessageDecoder.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.io.EzyByteBufs; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; - -public class JacksonByteToMessageDecoder extends ByteToMessageDecoder { - - private final Logger logger; - private final EzyMessageDeserializer deserializer; - - public JacksonByteToMessageDecoder(EzyMessageDeserializer deserializer) { - this.deserializer = deserializer; - this.logger = LoggerFactory.getLogger(getClass()); - } - - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) - throws Exception { - logger.debug("decode {} bytes", in); - out.add(deserializer.deserialize(EzyByteBufs.getBytes(in))); - } -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonCodecCreator.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonCodecCreator.java deleted file mode 100644 index b0e9307d..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonCodecCreator.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.channel.ChannelOutboundHandler; - -public class JacksonCodecCreator implements EzyCodecCreator { - - protected ObjectMapper objectMapper; - protected EzyMessageSerializer serializer; - protected EzyMessageDeserializer deserializer; - - public JacksonCodecCreator() { - this.objectMapper = newObjectMapper(); - this.serializer = newSerializer(); - this.deserializer = newDeserializer(); - } - - protected ObjectMapper newObjectMapper() { - return new ObjectMapper(); - } - - protected EzyMessageSerializer newSerializer() { - return new JacksonSimpleSerializer(objectMapper); - } - - protected EzyMessageDeserializer newDeserializer() { - return new JacksonSimpleDeserializer(objectMapper); - } - - @Override - public ChannelOutboundHandler newEncoder() { - return new JacksonMessageToByteEncoder(serializer); - } - - @Override - public ChannelInboundHandlerAdapter newDecoder() { - return new JacksonByteToMessageDecoder(deserializer); - } - -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonMessageToByteEncoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonMessageToByteEncoder.java deleted file mode 100644 index e972f1a8..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/JacksonMessageToByteEncoder.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.entity.EzyArray; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -public class JacksonMessageToByteEncoder extends MessageToByteEncoder { - - protected final Logger logger; - protected final EzyMessageSerializer serializer; - - public JacksonMessageToByteEncoder(EzyMessageSerializer serializer) { - this.serializer = serializer; - this.logger = LoggerFactory.getLogger(getClass()); - } - - @Override - protected void encode(ChannelHandlerContext ctx, EzyArray msg, ByteBuf out) - throws Exception { - writeMessage(serializer.serialize(msg), out); - } - - private void writeMessage(byte[] message, ByteBuf out) { - logger.debug("write message with size {}", message.length); - out.writeBytes(message); - } - -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackByteToMessageDecoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackByteToMessageDecoder.java deleted file mode 100644 index c9b97bb6..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackByteToMessageDecoder.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.PREPARE_MESSAGE; -import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_CONTENT; -import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_HEADER; -import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_SIZE; - -import java.util.List; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import lombok.AllArgsConstructor; -import lombok.Setter; - -public class MsgPackByteToMessageDecoder extends ByteToMessageDecoder { - - protected final Logger logger; - protected final Handlers handlers; - - public MsgPackByteToMessageDecoder(EzyMessageDeserializer deserializer) { - this.logger = LoggerFactory.getLogger(getClass()); - this.handlers = Handlers.builder().deserializer(deserializer).build(); - } - - @Override - protected void decode(ChannelHandlerContext ctx, - ByteBuf in, List out) throws Exception { - logger.debug("decode {} bytes", in); - handlers.handle(ctx, in, out); - } - -} - -@Setter -abstract class AbstractHandler implements EzyDecodeHandler { - - protected EzyDecodeHandler nextHandler; - protected EzyMessageReader messageReader; - - @Override - public EzyDecodeHandler nextHandler() { - return nextHandler; - } -} - -class PrepareMessage extends AbstractHandler { - - @Override - public EzyIDecodeState nextState() { - return READ_MESSAGE_SIZE; - } - - @Override - public boolean handle(ByteBuf in, List out) { - messageReader.clear(); - return true; - } -} - -class ReadMessageHeader extends AbstractHandler { - - @Override - public EzyIDecodeState nextState() { - return EzyDecodeState.READ_MESSAGE_HEADER; - } - - @Override - public boolean handle(ByteBuf in, List out) { - return messageReader.readHeader(in); - } - -} - -class ReadMessageSize extends AbstractHandler { - - @Override - public EzyIDecodeState nextState() { - return READ_MESSAGE_CONTENT; - } - - @Override - public boolean handle(ByteBuf in, List out) { - return messageReader.readSize(in); - } -} - -@AllArgsConstructor -class ReadMessageContent extends AbstractHandler { - - protected EzyMessageDeserializer deserializer; - - @Override - public EzyIDecodeState nextState() { - return PREPARE_MESSAGE; - } - - @Override - public boolean handle(ByteBuf in, List out) { - if(!messageReader.readContent(in)) - return false; - processMessage(messageReader.get(), out); - return true; - } - - private void processMessage(EzyMessage msg, List out) { - out.add(readMessageContent(msg.getContent())); - } - - private Object readMessageContent(byte[] content) { - return deserializer.deserialize(content); - } - -} - -class Handlers extends EzyDecodeHandlers { - - protected Handlers(Builder builder) { - super(builder); - } - - public static Builder builder() { - return new Builder(); - } - - public static class Builder extends AbstractBuilder { - protected EzyMessageReader messageReader; - protected EzyMessageDeserializer deserializer; - - { - messageReader = new EzyMessageReader(); - } - - public Builder deserializer(EzyMessageDeserializer deserializer) { - this.deserializer = deserializer; - return this; - } - - public Handlers build() { - return new Handlers(this); - } - - @Override - protected void addHandlers( - Map answer) { - EzyDecodeHandler readMessgeHeader = new ReadMessageHeader(); - EzyDecodeHandler prepareMessage = new PrepareMessage(); - EzyDecodeHandler readMessageSize = new ReadMessageSize(); - EzyDecodeHandler readMessageContent = new ReadMessageContent(deserializer); - answer.put(PREPARE_MESSAGE, newHandler(prepareMessage, readMessgeHeader)); - answer.put(READ_MESSAGE_HEADER, newHandler(readMessgeHeader, readMessageSize)); - answer.put(READ_MESSAGE_SIZE, newHandler(readMessageSize, readMessageContent)); - answer.put(READ_MESSAGE_CONTENT, newHandler(readMessageContent)); - } - - - private EzyDecodeHandler newHandler(EzyDecodeHandler handler) { - return newHandler(handler, null); - } - - private EzyDecodeHandler newHandler(EzyDecodeHandler handler, EzyDecodeHandler next) { - return newHandler((AbstractHandler)handler, next); - } - - private EzyDecodeHandler newHandler(AbstractHandler handler, EzyDecodeHandler next) { - handler.setNextHandler(next); - handler.setMessageReader(messageReader); - return handler; - } - } - -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecCreator.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecCreator.java deleted file mode 100644 index 91942cb3..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackCodecCreator.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import io.netty.channel.ChannelInboundHandlerAdapter; -import io.netty.channel.ChannelOutboundHandler; - -public class MsgPackCodecCreator implements EzyCodecCreator { - - protected EzyMessageToBytes messageToBytes; - protected EzyObjectToMessage objectToMessage; - protected EzyMessageDeserializer deserializer; - - { - deserializer = new MsgPackSimpleDeserializer(); - messageToBytes = EzySimpleMessageToBytes.builder().build(); - objectToMessage = MsgPackObjectToMessage.builder().build(); - } - - @Override - public ChannelInboundHandlerAdapter newDecoder() { - return new MsgPackByteToMessageDecoder(deserializer); - } - - @Override - public ChannelOutboundHandler newEncoder() { - return new MsgPackMessageToByteEncoder(messageToBytes, objectToMessage); - } - -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackMessageToByteEncoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackMessageToByteEncoder.java deleted file mode 100644 index 4925cda8..00000000 --- a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/codec/MsgPackMessageToByteEncoder.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.tvd12.ezyfoxserver.codec; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.tvd12.ezyfoxserver.entity.EzyArray; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; -import io.netty.util.ReferenceCountUtil; - -public class MsgPackMessageToByteEncoder extends MessageToByteEncoder { - - protected final Logger logger; - protected final EzyMessageToBytes messageToBytes; - protected final EzyObjectToMessage objectToMessage; - - public MsgPackMessageToByteEncoder( - EzyMessageToBytes messageToBytes, - EzyObjectToMessage objectToMessage) { - this.messageToBytes = messageToBytes; - this.objectToMessage = objectToMessage; - this.logger = LoggerFactory.getLogger(getClass()); - } - - @Override - protected void encode(ChannelHandlerContext ctx, EzyArray msg, ByteBuf out) - throws Exception { - writeMessage(convertObjectToBytes(msg), out); - } - - protected ByteBuf convertObjectToBytes(EzyArray object) { - return convertMessageToBytes(convertObjectToMessage(object)); - } - - protected EzyMessage convertObjectToMessage(EzyArray object) { - return objectToMessage.convert(object); - } - - protected ByteBuf convertMessageToBytes(EzyMessage message) { - return messageToBytes.convert(message, ByteBuf.class); - } - - protected void writeMessage(ByteBuf message, ByteBuf out) { - logger.debug("write message with size {}", message.readableBytes()); - out.writeBytes(message); - ReferenceCountUtil.release(message); - } - -} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonByteToMessageDecoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonByteToMessageDecoder.java new file mode 100644 index 00000000..28f29ab7 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonByteToMessageDecoder.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.netty.io.EzyByteBufs; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; + +public class JacksonByteToMessageDecoder extends ByteToMessageDecoder { + + private final Logger logger; + private final EzyMessageDeserializer deserializer; + + public JacksonByteToMessageDecoder(EzyMessageDeserializer deserializer) { + this.deserializer = deserializer; + this.logger = LoggerFactory.getLogger(getClass()); + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) + throws Exception { + logger.debug("decode {} bytes", in); + out.add(deserializer.deserialize(EzyByteBufs.getBytes(in))); + } +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonCodecCreator.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonCodecCreator.java new file mode 100644 index 00000000..3926ab98 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonCodecCreator.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.JacksonObjectMapperBuilder; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleSerializer; + +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelOutboundHandler; + +public class JacksonCodecCreator implements EzyCodecCreator { + + protected final ObjectMapper objectMapper; + protected final EzyMessageSerializer serializer; + protected final EzyMessageDeserializer deserializer; + + public JacksonCodecCreator() { + this.objectMapper = newObjectMapper(); + this.serializer = newSerializer(); + this.deserializer = newDeserializer(); + } + + protected ObjectMapper newObjectMapper() { + return JacksonObjectMapperBuilder.newInstance().build(); + } + + protected EzyMessageSerializer newSerializer() { + return new JacksonSimpleSerializer(objectMapper); + } + + protected EzyMessageDeserializer newDeserializer() { + return new JacksonSimpleDeserializer(objectMapper); + } + + @Override + public ChannelOutboundHandler newEncoder() { + return new JacksonMessageToByteEncoder(serializer); + } + + @Override + public ChannelInboundHandlerAdapter newDecoder(int maxRequestSize) { + return new JacksonByteToMessageDecoder(deserializer); + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToByteEncoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToByteEncoder.java new file mode 100644 index 00000000..7b670134 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToByteEncoder.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; + +public class JacksonMessageToByteEncoder extends MessageToByteEncoder { + + protected final Logger logger; + protected final EzyMessageSerializer serializer; + + public JacksonMessageToByteEncoder(EzyMessageSerializer serializer) { + this.serializer = serializer; + this.logger = LoggerFactory.getLogger(getClass()); + } + + @Override + protected void encode(ChannelHandlerContext ctx, EzyArray msg, ByteBuf out) + throws Exception { + writeMessage(serializer.serialize(msg), out); + } + + private void writeMessage(byte[] message, ByteBuf out) { + logger.debug("write message with size {}", message.length); + out.writeBytes(message); + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToTextWsFrameEncoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToTextWsFrameEncoder.java new file mode 100644 index 00000000..515e536c --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonMessageToTextWsFrameEncoder.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; + +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToMessageEncoder; +import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; + +public class JacksonMessageToTextWsFrameEncoder extends MessageToMessageEncoder { + + protected final Logger logger; + protected final EzyMessageSerializer serializer; + + public JacksonMessageToTextWsFrameEncoder(EzyMessageSerializer serializer) { + this.serializer = serializer; + this.logger = LoggerFactory.getLogger(getClass()); + } + + @Override + protected void encode(ChannelHandlerContext ctx, EzyArray msg, List out) throws Exception { + writeMessage(serializer.serialize(msg), out); + } + + private void writeMessage(byte[] message, List out) { + logger.debug("write message with size {}", message.length); + out.add(new TextWebSocketFrame(Unpooled.wrappedBuffer(message))); + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonWsCodecCreator.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonWsCodecCreator.java new file mode 100644 index 00000000..64661764 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/JacksonWsCodecCreator.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import io.netty.channel.ChannelOutboundHandler; + +public class JacksonWsCodecCreator extends JacksonCodecCreator { + + public JacksonWsCodecCreator() { + super(); + } + + @Override + public ChannelOutboundHandler newEncoder() { + return new JacksonMessageToTextWsFrameEncoder(serializer); + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackByteToMessageDecoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackByteToMessageDecoder.java new file mode 100644 index 00000000..279ee1fe --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackByteToMessageDecoder.java @@ -0,0 +1,197 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.PREPARE_MESSAGE; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_CONTENT; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_HEADER; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_SIZE; + +import java.util.List; +import java.util.Map; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.netty.handler.EzyBytesReceived; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import lombok.AllArgsConstructor; +import lombok.Setter; + +public class MsgPackByteToMessageDecoder extends ByteToMessageDecoder { + + protected final Handlers handlers; + + public MsgPackByteToMessageDecoder( + EzyMessageDeserializer deserializer, int maxSize) { + this.handlers = Handlers.builder() + .maxSize(maxSize) + .deserializer(deserializer) + .build(); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ByteBuf bytes = (ByteBuf)msg; + int bytesCount = bytes.readableBytes(); + super.channelRead(ctx, msg); + EzyBytesReceived delegate = (EzyBytesReceived)ctx.pipeline().get("handler"); + delegate.bytesReceived(bytesCount); + } + + @Override + protected void decode(ChannelHandlerContext ctx, + ByteBuf in, List out) throws Exception { + handlers.handle(ctx, in, out); + } + +} + +@Setter +abstract class AbstractHandler implements EzyDecodeHandler { + + protected EzyDecodeHandler nextHandler; + protected EzyMessageReader messageReader; + + @Override + public EzyDecodeHandler nextHandler() { + return nextHandler; + } +} + +class PrepareMessage extends AbstractHandler { + + @Override + public EzyIDecodeState nextState() { + return READ_MESSAGE_HEADER; + } + + @Override + public boolean handle(ByteBuf in, List out) { + messageReader.clear(); + return true; + } +} + +class ReadMessageHeader extends AbstractHandler { + + @Override + public EzyIDecodeState nextState() { + return EzyDecodeState.READ_MESSAGE_SIZE; + } + + @Override + public boolean handle(ByteBuf in, List out) { + return messageReader.readHeader(in); + } + +} + +class ReadMessageSize extends AbstractHandler { + + protected final int maxSize; + + public ReadMessageSize(int maxSize) { + this.maxSize = maxSize; + } + + @Override + public EzyIDecodeState nextState() { + return READ_MESSAGE_CONTENT; + } + + @Override + public boolean handle(ByteBuf in, List out) { + return messageReader.readSize(in, maxSize); + } +} + +@AllArgsConstructor +class ReadMessageContent extends AbstractHandler { + + protected EzyMessageDeserializer deserializer; + + @Override + public EzyIDecodeState nextState() { + return PREPARE_MESSAGE; + } + + @Override + public boolean handle(ByteBuf in, List out) { + if(!messageReader.readContent(in)) + return false; + processMessage(messageReader.get(), out); + return true; + } + + private void processMessage(EzyMessage msg, List out) { + out.add(readMessageContent(msg.getContent())); + } + + private Object readMessageContent(byte[] content) { + return deserializer.deserialize(content); + } + +} + +class Handlers extends EzyDecodeHandlers { + + protected Handlers(Builder builder) { + super(builder); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends AbstractBuilder { + protected int maxSize; + protected EzyMessageDeserializer deserializer; + protected EzyMessageReader messageReader = new EzyMessageReader(); + + public Builder maxSize(int maxSize) { + this.maxSize = maxSize; + return this; + } + + public Builder deserializer(EzyMessageDeserializer deserializer) { + this.deserializer = deserializer; + return this; + } + + public Handlers build() { + return new Handlers(this); + } + + @Override + protected void addHandlers( + Map answer) { + EzyDecodeHandler readMessgeHeader = new ReadMessageHeader(); + EzyDecodeHandler prepareMessage = new PrepareMessage(); + EzyDecodeHandler readMessageSize = new ReadMessageSize(maxSize); + EzyDecodeHandler readMessageContent = new ReadMessageContent(deserializer); + answer.put(PREPARE_MESSAGE, newHandler(prepareMessage, readMessgeHeader)); + answer.put(READ_MESSAGE_HEADER, newHandler(readMessgeHeader, readMessageSize)); + answer.put(READ_MESSAGE_SIZE, newHandler(readMessageSize, readMessageContent)); + answer.put(READ_MESSAGE_CONTENT, newHandler(readMessageContent)); + } + + + private EzyDecodeHandler newHandler(EzyDecodeHandler handler) { + return newHandler(handler, null); + } + + private EzyDecodeHandler newHandler(EzyDecodeHandler handler, EzyDecodeHandler next) { + return newHandler((AbstractHandler)handler, next); + } + + private EzyDecodeHandler newHandler(AbstractHandler handler, EzyDecodeHandler next) { + handler.setNextHandler(next); + handler.setMessageReader(messageReader); + return handler; + } + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackCodecCreator.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackCodecCreator.java new file mode 100644 index 00000000..f1edd0a1 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackCodecCreator.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; +import com.tvd12.ezyfoxserver.codec.EzyObjectToMessage; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectToMessage; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.netty.codec.EzySimpleMessageToBytes; + +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelOutboundHandler; + +public class MsgPackCodecCreator implements EzyCodecCreator { + + protected final EzyMessageToBytes messageToBytes + = EzySimpleMessageToBytes.builder().build(); + protected final EzyObjectToMessage objectToMessage + = MsgPackObjectToMessage.builder().build(); + protected final EzyMessageDeserializer deserializer + = new MsgPackSimpleDeserializer(); + + @Override + public ChannelInboundHandlerAdapter newDecoder(int maxRequestSize) { + return new MsgPackByteToMessageDecoder(deserializer, maxRequestSize); + } + + @Override + public ChannelOutboundHandler newEncoder() { + return new MsgPackMessageToByteEncoder(messageToBytes, objectToMessage); + } + +} diff --git a/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackMessageToByteEncoder.java b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackMessageToByteEncoder.java new file mode 100644 index 00000000..02a8a1b8 --- /dev/null +++ b/ezyfox-server-nettycodec/src/main/java/com/tvd12/ezyfoxserver/netty/codec/MsgPackMessageToByteEncoder.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.netty.codec; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; +import com.tvd12.ezyfoxserver.codec.EzyObjectToMessage; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.netty.handler.EzyBytesSent; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.MessageToByteEncoder; +import io.netty.util.ReferenceCountUtil; + +public class MsgPackMessageToByteEncoder extends MessageToByteEncoder { + + protected final EzyMessageToBytes messageToBytes; + protected final EzyObjectToMessage objectToMessage; + + public MsgPackMessageToByteEncoder( + EzyMessageToBytes messageToBytes, + EzyObjectToMessage objectToMessage) { + this.messageToBytes = messageToBytes; + this.objectToMessage = objectToMessage; + } + + @Override + protected void encode(ChannelHandlerContext ctx, EzyArray msg, ByteBuf out) + throws Exception { + ByteBuf bytes = convertObjectToBytes(msg); + int bytesCount = bytes.readableBytes(); + writeMessage(bytes, out); + EzyBytesSent delegate = (EzyBytesSent)ctx.pipeline().get("handler"); + delegate.bytesSent(bytesCount); + } + + protected ByteBuf convertObjectToBytes(EzyArray object) { + return convertMessageToBytes(convertObjectToMessage(object)); + } + + protected EzyMessage convertObjectToMessage(EzyArray object) { + return objectToMessage.convert(object); + } + + protected ByteBuf convertMessageToBytes(EzyMessage message) { + return messageToBytes.convert(message); + } + + protected void writeMessage(ByteBuf message, ByteBuf out) { + out.writeBytes(message); + ReferenceCountUtil.release(message); + } + +} diff --git a/ezyfox-server-nettyrunner/.gitignore b/ezyfox-server-nettyrunner/.gitignore new file mode 100644 index 00000000..6d9594aa --- /dev/null +++ b/ezyfox-server-nettyrunner/.gitignore @@ -0,0 +1 @@ +/logs/ diff --git a/ezyfox-server-nettyrunner/pom.xml b/ezyfox-server-nettyrunner/pom.xml index 3a177b67..7df92031 100644 --- a/ezyfox-server-nettyrunner/pom.xml +++ b/ezyfox-server-nettyrunner/pom.xml @@ -6,7 +6,7 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-nettyrunner @@ -14,17 +14,22 @@ 1.0.0 ezyfox-server-nettyrunner http://maven.apache.org + + + 1.0.0 + 1.0.0 + com.tvd12 ezyfox-server-netty - 1.0.0 + ${ezy.netty.version} com.tvd12 ezyfox-server-nettycodec - 1.0.0 + ${ezy.nettycodec.version} @@ -37,7 +42,7 @@ - com.tvd12.ezyfoxserver.EzyFoxRunner + com.tvd12.ezyfoxserver.EzyNettyRunner diff --git a/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/EzyNettyRunner.java b/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/EzyNettyRunner.java deleted file mode 100644 index 10450e87..00000000 --- a/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/EzyNettyRunner.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.tvd12.ezyfoxserver; - -import com.tvd12.ezyfoxserver.EzyStarter.Builder; - -public class EzyNettyRunner extends EzyRunner { - - public static void main(String[] args) throws Exception { - new EzyNettyRunner().run(args); - } - - @Override - protected Builder newStarterBuilder() { - return EzyNettyStarter.builder(); - } - -} diff --git a/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyRunner.java b/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyRunner.java new file mode 100644 index 00000000..e62eb349 --- /dev/null +++ b/ezyfox-server-nettyrunner/src/main/java/com/tvd12/ezyfoxserver/netty/EzyNettyRunner.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.netty; + +import com.tvd12.ezyfoxserver.EzyRunner; +import com.tvd12.ezyfoxserver.EzyStarter.Builder; +import com.tvd12.ezyfoxserver.netty.EzyNettyStarter; + +public class EzyNettyRunner extends EzyRunner { + + public static void main(String[] args) throws Exception { + new EzyNettyRunner().run(args); + } + + @Override + protected Builder newStarterBuilder() { + return EzyNettyStarter.builder(); + } + +} diff --git a/ezyfox-server-nio/.gitignore b/ezyfox-server-nio/.gitignore new file mode 100755 index 00000000..ebae499a --- /dev/null +++ b/ezyfox-server-nio/.gitignore @@ -0,0 +1,32 @@ +# Operating System Files + +*.DS_Store +Thumbs.db + +# Build Files # + +bin +target +build/ +.gradle + +# Eclipse Project Files # + +.classpath +.project +.settings + +# IntelliJ IDEA Files # + +*.iml +*.ipr +*.iws +*.idea + +# Test files + +*-uploaded +dependency-reduced-pom.xml +README.html + +upload-dir diff --git a/ezyfox-server-nio/assembly.xml b/ezyfox-server-nio/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-nio/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-nio/pom.xml b/ezyfox-server-nio/pom.xml new file mode 100755 index 00000000..76b4c224 --- /dev/null +++ b/ezyfox-server-nio/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-nio + 1.0.0 + + ezyfox-server-nio + http://maven.apache.org + + + 1.0.0 + 1.0.0 + 9.4.6.v20170531 + + + + + com.tvd12 + ezyfox-server-core + ${ezy.core.version} + + + com.tvd12 + ezyfox-server-boot + ${ezy.boot.version} + + + org.eclipse.jetty.websocket + websocket-server + ${jetty.version} + + + org.eclipse.jetty.websocket + websocket-client + + + + + + 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 new file mode 100644 index 00000000..55cbd68c --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioServerBootstrap.java @@ -0,0 +1,67 @@ +package com.tvd12.ezyfoxserver.nio; + +import com.tvd12.ezyfoxserver.EzyServerBootstrap; +import com.tvd12.ezyfoxserver.nio.builder.impl.EzySocketServerBootstrap; +import com.tvd12.ezyfoxserver.nio.builder.impl.EzyWebSocketServerBootstrap; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; + +import lombok.Setter; + +public class EzyNioServerBootstrap extends EzyServerBootstrap { + + private EzySocketServerBootstrap socketServerBootstrap; + private EzyWebSocketServerBootstrap websocketServerBootstrap; + + @Setter + private EzyHandlerGroupManager handlerGroupManager; + @Setter + private EzySessionTicketsQueue socketSessionTicketsQueue; + @Setter + private EzySessionTicketsQueue websocketSessionTicketsQueue; + + @Override + protected void startOtherBootstraps(Runnable callback) throws Exception { + startSocketServerBootstrap(); + startWebSocketServerBootstrap(); + callback.run(); + } + + private void startSocketServerBootstrap() throws Exception { + getLogger().debug("starting tcp socket server bootstrap ...."); + socketServerBootstrap = newSocketServerBootstrap(); + socketServerBootstrap.start(); + getLogger().debug("tcp socket server bootstrap has started"); + } + + protected void startWebSocketServerBootstrap() throws Exception { + getLogger().debug("starting websocket server bootstrap ...."); + websocketServerBootstrap = newWebSocketServerBootstrap(); + websocketServerBootstrap.start(); + getLogger().debug("websockt server bootstrap has started"); + } + + private EzySocketServerBootstrap newSocketServerBootstrap() { + return EzySocketServerBootstrap.builder() + .serverContext(context) + .handlerGroupManager(handlerGroupManager) + .sessionTicketsQueue(socketSessionTicketsQueue) + .build(); + } + + private EzyWebSocketServerBootstrap newWebSocketServerBootstrap() { + return EzyWebSocketServerBootstrap.builder() + .serverContext(context) + .handlerGroupManager(handlerGroupManager) + .sessionTicketsQueue(websocketSessionTicketsQueue) + .build(); + } + + @Override + public void destroy() { + super.destroy(); + socketServerBootstrap.destroy(); + websocketServerBootstrap.destroy(); + } + +} 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 new file mode 100644 index 00000000..6f4ff640 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioStarter.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.nio; + +import com.tvd12.ezyfoxserver.EzyLoader; +import com.tvd12.ezyfoxserver.EzyStarter; +import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.nio.builder.impl.EzyNioServerBootstrapBuilderImpl; +import com.tvd12.ezyfoxserver.nio.wrapper.impl.EzyNioSessionManagerImpl; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; + +public class EzyNioStarter extends EzyStarter { + + protected EzyNioStarter(Builder builder) { + super(builder); + } + + @Override + protected EzyServerBootstrapBuilder newServerBootstrapBuilder() { + return new EzyNioServerBootstrapBuilderImpl(); + } + + @Override + protected EzyLoader newLoader() { + return new EzyLoader() { + @Override + protected void addManagers(EzyManagers managers) { + managers.addManager(EzySessionManager.class, EzyNioSessionManagerImpl.builder().build()); + } + }; + } + + 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/builder/EzyNioServerBootstrapBuilder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/EzyNioServerBootstrapBuilder.java new file mode 100644 index 00000000..fb0b7b1c --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/EzyNioServerBootstrapBuilder.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.nio.builder; + +import com.tvd12.ezyfoxserver.builder.EzyServerBootstrapBuilder; + +public interface EzyNioServerBootstrapBuilder extends EzyServerBootstrapBuilder { +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyCodecFactoryImpl.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyCodecFactoryImpl.java new file mode 100644 index 00000000..f6704eab --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyCodecFactoryImpl.java @@ -0,0 +1,77 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import static com.tvd12.ezyfoxserver.constant.EzyConnectionType.SOCKET; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.factory.EzyCodecFactory; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioObjectToByteEncoder; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.setting.EzySocketSetting; +import com.tvd12.ezyfoxserver.setting.EzyWebSocketSetting; + +public class EzyCodecFactoryImpl implements EzyCodecFactory { + + private final EzySocketSetting socketSettings; + private final EzyWebSocketSetting websocketSettings; + + private final EzyCodecCreator socketCodecCreator; + private final EzyCodecCreator websocketCodecCreator; + + public EzyCodecFactoryImpl(Builder builder) { + this.socketSettings = builder.socketSettings; + this.websocketSettings = builder.websocketSettings; + this.socketCodecCreator = newSocketCodecCreator(); + this.websocketCodecCreator = newWebsocketCodecCreator(); + } + + @Override + public Object newDecoder(EzyConnectionType type) { + if(type == SOCKET) { + return socketCodecCreator.newDecoder(socketSettings.getMaxRequestSize()); + } + return websocketCodecCreator.newDecoder(websocketSettings.getMaxFrameSize()); + } + + @Override + public Object newEncoder(EzyConnectionType type) { + if(type == SOCKET) { + return (EzyNioObjectToByteEncoder) socketCodecCreator.newEncoder(); + } + return (EzyNioObjectToByteEncoder) websocketCodecCreator.newEncoder(); + } + + private EzyCodecCreator newSocketCodecCreator() { + return EzyClasses.newInstance(socketSettings.getCodecCreator()); + } + + private EzyCodecCreator newWebsocketCodecCreator() { + return EzyClasses.newInstance(websocketSettings.getCodecCreator()); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private EzySocketSetting socketSettings; + private EzyWebSocketSetting websocketSettings; + + public Builder socketSettings(EzySocketSetting settings) { + this.socketSettings = settings; + return this; + } + + public Builder websocketSettings(EzyWebSocketSetting settings) { + this.websocketSettings = settings; + return this; + } + + @Override + public EzyCodecFactory build() { + return new EzyCodecFactoryImpl(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 new file mode 100644 index 00000000..487f6c0d --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyHandlerGroupBuilderFactoryImpl.java @@ -0,0 +1,67 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.factory.EzyHandlerGroupBuilderFactory; +import com.tvd12.ezyfoxserver.nio.handler.EzyAbstractHandlerGroup; +import com.tvd12.ezyfoxserver.nio.handler.EzySimpleNioHandlerGroup; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.websocket.EzySimpleWsHandlerGroup; + +public class EzyHandlerGroupBuilderFactoryImpl implements EzyHandlerGroupBuilderFactory { + + private EzySessionTicketsQueue socketSessionTicketsQueue; + private EzySessionTicketsQueue websocketSessionTicketsQueue; + + public EzyHandlerGroupBuilderFactoryImpl(Builder builder) { + this.socketSessionTicketsQueue = builder.socketSessionTicketsQueue; + this.websocketSessionTicketsQueue = builder.websocketSessionTicketsQueue; + } + + @Override + public EzyAbstractHandlerGroup.Builder newBuilder(EzyConnectionType type) { + switch (type) { + case SOCKET: + return newBuilderBySocketType(); + default: + return newBuilderByWebSocketType(); + } + } + + private EzyAbstractHandlerGroup.Builder newBuilderBySocketType() { + EzyAbstractHandlerGroup.Builder builder = EzySimpleNioHandlerGroup.builder(); + builder.sessionTicketsQueue(socketSessionTicketsQueue); + return builder; + } + + private EzyAbstractHandlerGroup.Builder newBuilderByWebSocketType() { + EzyAbstractHandlerGroup.Builder builder = EzySimpleWsHandlerGroup.builder(); + builder.sessionTicketsQueue(websocketSessionTicketsQueue); + return builder; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private EzySessionTicketsQueue socketSessionTicketsQueue; + private EzySessionTicketsQueue websocketSessionTicketsQueue; + + public Builder socketSessionTicketsQueue(EzySessionTicketsQueue socketSessionTicketsQueue) { + this.socketSessionTicketsQueue = socketSessionTicketsQueue; + return this; + } + + public Builder websocketSessionTicketsQueue(EzySessionTicketsQueue websocketSessionTicketsQueue) { + this.websocketSessionTicketsQueue = websocketSessionTicketsQueue; + return this; + } + + @Override + public EzyHandlerGroupBuilderFactory build() { + return new EzyHandlerGroupBuilderFactoryImpl(this); + } + } + +} 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 new file mode 100644 index 00000000..8a6ef7c5 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyNioServerBootstrapBuilderImpl.java @@ -0,0 +1,97 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import java.util.concurrent.ExecutorService; + +import com.tvd12.ezyfoxserver.EzyHttpServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.EzyServerBootstrap; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.nio.EzyNioServerBootstrap; +import com.tvd12.ezyfoxserver.nio.builder.EzyNioServerBootstrapBuilder; +import com.tvd12.ezyfoxserver.nio.factory.EzyCodecFactory; +import com.tvd12.ezyfoxserver.nio.factory.EzyHandlerGroupBuilderFactory; +import com.tvd12.ezyfoxserver.nio.socket.EzyBlockingSessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.nio.wrapper.impl.EzyHandlerGroupManagerImpl; + +public class EzyNioServerBootstrapBuilderImpl + extends EzyHttpServerBootstrapBuilder + implements EzyNioServerBootstrapBuilder { + + @Override + protected EzyServerBootstrap newServerBootstrap() { + ExecutorService statsThreadPool = newStatsThreadPool(); + ExecutorService codecThreadPool = newCodecThreadPool(); + ExecutorService handlerThreadPool = newHandlerThreadPool(); + EzySessionTicketsQueue socketSessionTicketsQueue = newSocketSessionTicketsQueue(); + EzySessionTicketsQueue websocketSessionTicketsQueue = newWebSocketSessionTicketsQueue(); + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory = newHandlerGroupBuilderFactory( + socketSessionTicketsQueue, + websocketSessionTicketsQueue); + EzyHandlerGroupManager handlerGroupManager = newHandlerGroupManager( + statsThreadPool, + codecThreadPool, + handlerThreadPool, + handlerGroupBuilderFactory); + EzyNioServerBootstrap bootstrap = new EzyNioServerBootstrap(); + bootstrap.setHandlerGroupManager(handlerGroupManager); + bootstrap.setSocketSessionTicketsQueue(socketSessionTicketsQueue); + bootstrap.setWebsocketSessionTicketsQueue(websocketSessionTicketsQueue); + return bootstrap; + } + + private EzyHandlerGroupManager newHandlerGroupManager( + ExecutorService statsThreadPool, + ExecutorService codecThreadPool, + ExecutorService handlerThreadPool, + EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory) { + + return EzyHandlerGroupManagerImpl.builder() + .serverContext(serverContext) + .codecFactory(newCodecFactory()) + .statsThreadPool(statsThreadPool) + .codecThreadPool(codecThreadPool) + .handlerThreadPool(handlerThreadPool) + .handlerGroupBuilderFactory(handlerGroupBuilderFactory) + .build(); + } + + private EzyHandlerGroupBuilderFactory newHandlerGroupBuilderFactory( + EzySessionTicketsQueue socketSessionTicketsQueue, + EzySessionTicketsQueue websocketSessionTicketsQueue) { + + return EzyHandlerGroupBuilderFactoryImpl.builder() + .socketSessionTicketsQueue(socketSessionTicketsQueue) + .websocketSessionTicketsQueue(websocketSessionTicketsQueue) + .build(); + } + + + private ExecutorService newStatsThreadPool() { + return EzyExecutors.newFixedThreadPool(3, "statistics"); + } + + private ExecutorService newCodecThreadPool() { + return EzyExecutors.newFixedThreadPool(3, "codec"); + } + + private ExecutorService newHandlerThreadPool() { + return EzyExecutors.newFixedThreadPool(3, "handler"); + } + + private EzySessionTicketsQueue newSocketSessionTicketsQueue() { + return new EzyBlockingSessionTicketsQueue(); + } + + private EzySessionTicketsQueue newWebSocketSessionTicketsQueue() { + return new EzyBlockingSessionTicketsQueue(); + } + + private EzyCodecFactory newCodecFactory() { + return EzyCodecFactoryImpl.builder() + .socketSettings(getSocketSettings()) + .websocketSettings(getWebsocketSettings()) + .build(); + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzySocketServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzySocketServerBootstrap.java new file mode 100644 index 00000000..948c80f0 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzySocketServerBootstrap.java @@ -0,0 +1,179 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySocketAcceptor; +import com.tvd12.ezyfoxserver.nio.socket.EzySocketHandler; +import com.tvd12.ezyfoxserver.nio.socket.EzySocketReader; +import com.tvd12.ezyfoxserver.nio.socket.EzySocketWriter; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.setting.EzySocketSetting; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +import static com.tvd12.ezyfoxserver.util.EzyProcessor.*; + +public class EzySocketServerBootstrap + implements EzyStartable, EzyDestroyable { + + private Selector readSelector; + private Selector acceptSelector; + private ServerSocket serverSocket; + private ServerSocketChannel serverSocketChannel; + + private EzySocketWriter socketWriter; + private EzySocketReader socketReader; + private EzySocketAcceptor socketAcceptor; + + private EzyServerContext serverContext; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionTicketsQueue sessionTicketsQueue; + + public EzySocketServerBootstrap(Builder builder) { + this.serverContext = builder.serverContext; + this.handlerGroupManager = builder.handlerGroupManager; + this.sessionTicketsQueue = builder.sessionTicketsQueue; + } + + @Override + public void start() throws Exception { + openSelectors(); + newAndConfigServerSocketChannel(); + getBindAndConfigServerSocket(); + startSocketHandlers(); + } + + @Override + public void destroy() { + processWithLogException(socketAcceptor::destroy); + processWithLogException(socketWriter::destroy); + processWithLogException(socketReader::destroy); + processWithLogException(serverSocket::close); + 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 { + socketWriter = newSocketWriter(); + socketReader = newSocketReader(); + socketAcceptor = newSocketAcceptor(); + socketAcceptor.start(); + socketReader.start(); + socketWriter.start(); + } + + private EzySocketAcceptor newSocketAcceptor() { + return newSocketHandler(EzySocketAcceptor.builder() + .tcpNoDelay(true) + .readSelector(readSelector) + .ownSelector(acceptSelector) + .threadPoolSize(getAcceptorPoolSize())); + } + + private EzySocketReader newSocketReader() { + return newSocketHandler(EzySocketReader.builder() + .ownSelector(readSelector) + .threadPoolSize(getReaderPoolSize())); + } + + private EzySocketWriter newSocketWriter() { + return newSocketHandler(EzySocketWriter.builder() + .threadPoolSize(getWriterPoolSize()) + .sessionTicketsQueue(sessionTicketsQueue)); + } + + @SuppressWarnings("unchecked") + private T newSocketHandler(EzySocketHandler.Builder builder) { + return (T)builder + .handlerGroupManager(handlerGroupManager) + .build(); + } + + + private Selector openSelector() throws Exception { + return Selector.open(); + } + + private ServerSocketChannel newServerSocketChannel() throws Exception { + return ServerSocketChannel.open(); + } + + private int getReaderPoolSize() { + return 3; + } + + private int getWriterPoolSize() { + return 3; + } + + private int getAcceptorPoolSize() { + return 3; + } + + private int getSocketPort() { + return getSocketSettings().getPort(); + } + + private String getSocketAddress() { + return getSocketSettings().getAddress(); + } + + private EzySocketSetting getSocketSettings() { + return serverContext.getServer().getSettings().getSocket(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzyServerContext serverContext; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionTicketsQueue sessionTicketsQueue; + + public Builder serverContext(EzyServerContext context) { + this.serverContext = context; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager manager) { + this.handlerGroupManager = manager; + return this; + } + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return this; + } + + @Override + public EzySocketServerBootstrap build() { + return new EzySocketServerBootstrap(this); + } + } +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerBootstrap.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerBootstrap.java new file mode 100644 index 00000000..afb60951 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerBootstrap.java @@ -0,0 +1,124 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import static com.tvd12.ezyfoxserver.util.EzyProcessor.processWithLogException; + +import org.eclipse.jetty.server.Server; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.websocket.EzyWsSocketWriter; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.setting.EzyWebSocketSetting; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +public class EzyWebSocketServerBootstrap + implements EzyStartable, EzyDestroyable { + + private Server server; + private EzyWsSocketWriter socketWriter; + + private EzyServerContext serverContext; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionTicketsQueue sessionTicketsQueue; + + public EzyWebSocketServerBootstrap(Builder builder) { + this.serverContext = builder.serverContext; + this.handlerGroupManager = builder.handlerGroupManager; + this.sessionTicketsQueue = builder.sessionTicketsQueue; + } + + @Override + public void start() throws Exception { + server = newSocketServer(); + server.start(); + socketWriter = newSocketWriter(); + socketWriter.start(); + } + + @Override + public void destroy() { + processWithLogException(server::stop); + } + + private Server newSocketServer() { + return newSocketServerCreator() + .port(getSocketPort()) + .address(getSocketAddress()) + .settings(getWsSettings()) + .sessionSettings(getSessionSettings()) + .handlerGroupManager(handlerGroupManager) + .create(); + } + + private EzyWsSocketWriter newSocketWriter() { + return EzyWsSocketWriter.builder() + .threadPoolSize(getWriterPoolSize()) + .handlerGroupManager(handlerGroupManager) + .sessionTicketsQueue(sessionTicketsQueue) + .build(); + } + + private EzyWebSocketServerCreator newSocketServerCreator() { + return new EzyWebSocketServerCreator(); + } + + private int getWriterPoolSize() { + return 3; + } + + private int getSocketPort() { + return getWsSettings().getPort(); + } + + private String getSocketAddress() { + return getWsSettings().getAddress(); + } + + private EzyWebSocketSetting getWsSettings() { + return getServerSettings().getWebsocket(); + } + + private EzySessionManagementSetting getSessionSettings() { + return getServerSettings().getSessionManagement(); + } + + private EzySettings getServerSettings() { + return serverContext.getServer().getSettings(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + + private EzyServerContext serverContext; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionTicketsQueue sessionTicketsQueue; + + public Builder serverContext(EzyServerContext context) { + this.serverContext = context; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager manager) { + this.handlerGroupManager = manager; + return this; + } + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + 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/EzyWebSocketServerCreator.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java new file mode 100644 index 00000000..87a9af97 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/builder/impl/EzyWebSocketServerCreator.java @@ -0,0 +1,96 @@ +package com.tvd12.ezyfoxserver.nio.builder.impl; + +import java.net.InetSocketAddress; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.websocket.api.WebSocketPolicy; +import org.eclipse.jetty.websocket.server.WebSocketHandler; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; +import org.eclipse.jetty.websocket.servlet.WebSocketCreator; +import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; + +import com.tvd12.ezyfoxserver.nio.websocket.EzyWsHandler; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting; +import com.tvd12.ezyfoxserver.setting.EzyWebSocketSetting; + +public class EzyWebSocketServerCreator { + + private int port; + private String address; + + private EzyWebSocketSetting settings; + private EzyHandlerGroupManager handlerGroupManager; + private EzySessionManagementSetting sessionSettings; + + public EzyWebSocketServerCreator port(int port) { + this.port = port; + return this; + } + + public EzyWebSocketServerCreator address(String address) { + this.address = address; + return this; + } + + public EzyWebSocketServerCreator settings(EzyWebSocketSetting settings) { + this.settings = settings; + return this; + } + + public EzyWebSocketServerCreator sessionSettings(EzySessionManagementSetting sessionSettings) { + this.sessionSettings = sessionSettings; + return this; + } + + public EzyWebSocketServerCreator handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { + this.handlerGroupManager = handlerGroupManager; + return this; + } + + public Server create() { + ContextHandler contextHandler = new ContextHandler("/ws"); + contextHandler.setAllowNullPathInfo(true); + EzyWsHandler wsHandler = newWsHandler(); + contextHandler.setHandler(newWebSocketHandler(wsHandler)); + Server server = new Server(newSocketAddress()); + server.setHandler(contextHandler); + return server; + } + + private EzyWsHandler newWsHandler() { + return EzyWsHandler.builder() + .settings(sessionSettings) + .handlerGroupManager(handlerGroupManager) + .build(); + } + + private InetSocketAddress newSocketAddress() { + return new InetSocketAddress(address, port); + } + + 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() { + public void configure(WebSocketServletFactory factory) { + WebSocketPolicy policy = factory.getPolicy(); + factory.setCreator(newWebSocketCreator(handler)); + policy.setMaxTextMessageSize(settings.getMaxFrameSize()); + policy.setMaxBinaryMessageSize(settings.getMaxFrameSize()); + policy.setMaxTextMessageBufferSize(settings.getMaxFrameSize()); + policy.setMaxBinaryMessageBufferSize(settings.getMaxFrameSize()); + } + }; + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyBytesToData.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyBytesToData.java new file mode 100644 index 00000000..87d25478 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyBytesToData.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +public interface EzyBytesToData { + + + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDataToBytes.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDataToBytes.java new file mode 100644 index 00000000..50208cbb --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDataToBytes.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.entity.EzyData; + +public interface EzyDataToBytes { + + ByteBuffer convert(EzyData data); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandler.java new file mode 100644 index 00000000..0a558559 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandler.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyMessage; + +public interface EzyDecodeHandler { + + /** + * Get next state + * + * @return the next state + */ + EzyIDecodeState nextState(); + + /** + * Get next handler corresponding the next state + * + * @return the next handler + */ + EzyDecodeHandler nextHandler(); + + /** + * Handler decoding + * + * @param in the input + * @param out the output + * @return true if decoding is successful or not + */ + boolean handle(ByteBuffer in, Queue out); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandlers.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandlers.java new file mode 100644 index 00000000..08d949c5 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyDecodeHandlers.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyMessage; + +public abstract class EzyDecodeHandlers { + + protected EzyIDecodeState state; + protected Map handers; + + protected EzyDecodeHandlers(AbstractBuilder builder) { + this.state = firstState(); + this.handers = builder.newHandlers(); + } + + protected void handle(ByteBuffer in, Queue out) { + EzyDecodeHandler handler = handers.get(state); + while(handler != null && handler.handle(in, out)) { + state = handler.nextState(); + handler = handler.nextHandler(); + } + } + + protected EzyIDecodeState firstState() { + return EzyDecodeState.PREPARE_MESSAGE; + } + + public abstract static class AbstractBuilder { + protected Map newHandlers() { + Map answer = new HashMap<>(); + addHandlers(answer); + return answer; + } + + protected abstract void addHandlers(Map answer); + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyMessageReader.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyMessageReader.java new file mode 100644 index 00000000..e9ab8fdf --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzyMessageReader.java @@ -0,0 +1,103 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeader; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeaderBuilder; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.ezyfoxserver.io.EzyInts; + +public class EzyMessageReader { + + private int size; + private byte[] content; + private EzyMessageHeader header; + + public EzyMessageReader() { + clear(); + } + + public boolean readHeader(ByteBuffer buf) { + if(buf.remaining() < getHeaderLength()) + return false; + readHeader(buf.get()); + return true; + } + + public boolean readSize(ByteBuffer buf, int maxSize) { + if(buf.remaining() < getSizeLength()) + return false; + this.size = EzyInts.bin2uint(EzyBytes.copy(buf, getSizeLength())); + if(size > maxSize) + throw new EzyMaxRequestSizeException(size, maxSize); + return true; + } + + public boolean readContent(ByteBuffer buf) { + if(buf.remaining() < size) + return false; + this.content = new byte[size]; + buf.get(content); + return true; + } + + public void clear() { + this.size = 0; + this.content = new byte[0]; + } + + public EzyMessage get() { + return EzyMessageBuilder.newInstance() + .header(header) + .size(size) + .content(content) + .build(); + } + + private void readHeader(byte header) { + this.header = new EzyMessageHeaderReader().read(header); + } + + protected int getSizeLength() { + return header.isBigSize() ? 4 : 2; + } + + protected int getHeaderLength() { + return 1; + } +} + +class EzyMessageHeaderReader { + + protected boolean bigSize; + protected boolean encrypted; + protected boolean compressed; + + protected boolean readBigSize(byte header) { + return (header & 1 << 0) > 0; + } + + protected boolean readEncrypted(byte header) { + return (header & (1 << 1)) > 0; + } + + protected boolean readCompressed(byte header) { + return (header & (2 << 1)) > 0; + } + + protected boolean readText(byte header) { + return (header & (3 << 1)) > 0; + } + + public EzyMessageHeader read(byte header) { + return EzyMessageHeaderBuilder.newInstance() + .bigSize(readBigSize(header)) + .encrypted(readEncrypted(header)) + .compressed(readCompressed(header)) + .text(readText(header)) + .build(); + } +} \ No newline at end of file diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzySimpleMessageToBytes.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzySimpleMessageToBytes.java new file mode 100644 index 00000000..6ec492a4 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/codec/EzySimpleMessageToBytes.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageHeader; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; + +import lombok.Builder; + +@Builder +public class EzySimpleMessageToBytes implements EzyMessageToBytes { + + @SuppressWarnings("unchecked") + @Override + public ByteBuffer convert(EzyMessage message) { + ByteBuffer answer = newByteBuffer(message); + writeHeader(answer, message); + writeSize(answer, message); + writeContent(answer, message); + answer.flip(); + return answer; + } + + private void writeHeader(ByteBuffer answer, EzyMessage message) { + writeHeader(answer, message.getHeader()); + } + + private void writeHeader(ByteBuffer answer, EzyMessageHeader header) { + byte headerByte = 0; + headerByte |= header.isBigSize() ? 1 : 0; + headerByte |= header.isEncrypted() ? 1 << 1 : 0; + headerByte |= header.isCompressed() ? 1 << 2 : 0; + headerByte |= header.isText() ? 1 << 3 : 0; + answer.put(headerByte); + } + + private void writeSize(ByteBuffer answer, EzyMessage message) { + if(message.hasBigSize()) + answer.putInt(message.getSize()); + else + answer.putShort((short)message.getSize()); + } + + private void writeContent(ByteBuffer answer, EzyMessage message) { + answer.put(message.getContent()); + } + + private ByteBuffer newByteBuffer(EzyMessage message) { + int capacity = getCapacity(message); + return ByteBuffer.allocate(capacity); + } + + private int getCapacity(EzyMessage message){ + return 1 + message.getSizeLength() + message.getContent().length; + } + +} \ No newline at end of file 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 new file mode 100644 index 00000000..3afd3c63 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzyDecodeDelegate.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.nio.delegate; + +public interface EzyDecodeDelegate { + + void onDecoded(); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzySocketChannelDelegate.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzySocketChannelDelegate.java new file mode 100644 index 00000000..e7a84837 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/delegate/EzySocketChannelDelegate.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.nio.delegate; + +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; + +public interface EzySocketChannelDelegate { + + void onChannelInactivated(EzyChannel channel); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyChannel.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyChannel.java new file mode 100644 index 00000000..9ff8cbb4 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyChannel.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.nio.entity; + +import java.net.SocketAddress; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; + +public interface EzyChannel { + + void close(); + + void disconnect(); + + boolean isConnected(); + + int write(Object data) throws Exception; + + T getConnection(); + + EzyConnectionType getConnectionType(); + + SocketAddress getServerAddress(); + + SocketAddress getClientAddress(); + +} 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 new file mode 100644 index 00000000..630b778d --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzyNioSession.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.nio.entity; + +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.nio.socket.EzyPacketQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; + +public interface EzyNioSession extends EzySession { + + String SELECTION_KEY = "SessionSelectionKey"; + + /** + * Get the channel mapped to this session + * + * @return the channel + */ + EzyChannel getChannel(); + + /** + * Map this session to the channel + * + * @param channel the channel + */ + void setChannel(EzyChannel channel); + + /** + * Get connection + * + * @return the connection + */ + T getConnection(); + + /** + * Get packet queue + * + * @return the packet queue + */ + EzyPacketQueue getPacketQueue(); + + /** + * set session tickets queue + * + * @param queue the queue + */ + void setSessionTicketsQueue(EzySessionTicketsQueue queue); + +} 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 new file mode 100644 index 00000000..9869cd42 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/entity/EzySimpleSession.java @@ -0,0 +1,73 @@ +package com.tvd12.ezyfoxserver.nio.entity; + +import java.net.SocketAddress; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; +import com.tvd12.ezyfoxserver.entity.EzyAbstractSession; +import com.tvd12.ezyfoxserver.entity.EzyData; +import com.tvd12.ezyfoxserver.nio.socket.EzyPacketQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySimplePacket; +import com.tvd12.ezyfoxserver.util.EzyProcessor; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Setter +@Getter +@ToString(callSuper = true) +public class EzySimpleSession extends EzyAbstractSession implements EzyNioSession { + private static final long serialVersionUID = -8390274886953462147L; + + protected EzyChannel channel; + protected EzyPacketQueue packetQueue; + protected EzySessionTicketsQueue sessionTicketsQueue; + + @Override + public void setChannel(EzyChannel channel) { + this.channel = channel; + } + + @Override + protected void sendData(EzyData data, EzyTransportType type) { + EzySimplePacket packet = new EzySimplePacket(); + packet.setType(type); + packet.setData(data); + packetQueue.add(packet); + sessionTicketsQueue.add(this); + } + + @Override + public void disconnect() { + EzyProcessor.processWithLogException(() -> channel.close()); + } + + @Override + public void close() { + EzyProcessor.processWithLogException(() -> channel.close()); + } + + @Override + public T getConnection() { + return channel.getConnection(); + } + + @Override + public SocketAddress getServerAddress() { + return channel != null ? channel.getServerAddress() : null; + } + + @Override + public SocketAddress getClientAddress() { + return channel != null ? channel.getClientAddress() : null; + } + + @Override + public void destroy() { + super.destroy(); + this.packetQueue.clear(); + this.channel = null; + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/example/EzySocketWriteException.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/example/EzySocketWriteException.java new file mode 100644 index 00000000..0ca42b12 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/example/EzySocketWriteException.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.nio.example; + +public class EzySocketWriteException extends IllegalStateException { + private static final long serialVersionUID = -85983192721313901L; + + public EzySocketWriteException(String message, Throwable throwable) { + super(message, throwable); + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyCodecFactory.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyCodecFactory.java new file mode 100644 index 00000000..7697d1a3 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyCodecFactory.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.nio.factory; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; + +public interface EzyCodecFactory { + + Object newDecoder(EzyConnectionType type); + + Object newEncoder(EzyConnectionType type); + +} 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 new file mode 100644 index 00000000..fba6f50e --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyHandlerGroupBuilderFactory.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.nio.factory; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.handler.EzyAbstractHandlerGroup; + +public interface EzyHandlerGroupBuilderFactory { + + EzyAbstractHandlerGroup.Builder newBuilder(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 new file mode 100644 index 00000000..31e9e6f1 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/factory/EzyNioSessionFactory.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.nio.factory; + +import com.tvd12.ezyfoxserver.factory.EzyAbstractSessionFactory; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.entity.EzySimpleSession; +import com.tvd12.ezyfoxserver.nio.socket.EzyNonBlockingPacketQueue; + +public class EzyNioSessionFactory extends EzyAbstractSessionFactory { + + @Override + protected EzyNioSession newSession() { + EzySimpleSession session = new EzySimpleSession(); + session.setPacketQueue(new EzyNonBlockingPacketQueue()); + return session; + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractDataDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractDataDecoder.java new file mode 100644 index 00000000..efdac3bf --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractDataDecoder.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzyAbstractDataDecoder + extends EzyLoggable { + + protected ByteBuffer buffer; + protected volatile boolean active; + + protected final D decoder; + + public EzyAbstractDataDecoder(D decoder) { + this.active = true; + this.decoder = decoder; + } + + public void destroy() { + this.active = false; + } + +} 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 new file mode 100644 index 00000000..f3333879 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyAbstractHandlerGroup.java @@ -0,0 +1,225 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import static com.tvd12.ezyfoxserver.util.EzyProcessor.processWithLogException; +import static java.util.concurrent.CompletableFuture.supplyAsync; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.atomic.AtomicReference; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.nio.delegate.EzySocketChannelDelegate; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public abstract class EzyAbstractHandlerGroup + < + D extends EzyDestroyable, + E extends EzyNioDataEncoder + > + extends EzyLoggable + implements EzySocketChannelDelegate { + + protected final EzyChannel channel; + + protected D decoder; + protected E encoder; + protected final EzyNioDataHandler handler; + + protected final ExecutorService statsThreadPool; + protected final ExecutorService codecThreadPool; + protected final ExecutorService handlerThreadPool; + + protected final AtomicReference session; + protected final EzySocketChannelDelegate channelDelegate; + protected final EzySessionTicketsQueue sessionTicketsQueue; + + public EzyAbstractHandlerGroup(Builder builder) { + this.session = new AtomicReference(); + this.channel = builder.channel; + this.statsThreadPool = builder.statsThreadPool; + this.codecThreadPool = builder.codecThreadPool; + this.handlerThreadPool = builder.handlerThreadPool; + this.channelDelegate = builder.channelDelegate; + this.sessionTicketsQueue = builder.sessionTicketsQueue; + + this.decoder = newDecoder(builder.decoder); + this.encoder = newEncoder(builder.encoder); + this.handler = newDataHandler(builder.serverContext); + } + + protected abstract D newDecoder(Object decoder); + + protected abstract E newEncoder(Object encoder); + + private EzyNioDataHandler newDataHandler(EzyServerContext context) { + EzySimpleNioDataHandler handler = new EzySimpleNioDataHandler(channel); + handler.setContext(context); + handler.setChannelDelegate(this); + return handler; + } + + public final void fireChannelInactive() { + try { + decoder.destroy(); + handler.channelInactive(); + } + catch(Exception e) { + getLogger().error("handler inactive error", e); + } + } + + public final void fireChannelInactive(EzyDisconnectReason reason) { + try { + decoder.destroy(); + handler.channelInactive(reason); + } + catch(Exception e) { + getLogger().error("handler inactive error", e); + } + } + + public final void fireExceptionCaught(Throwable throwable) { + try { + handler.exceptionCaught(throwable); + } + catch(Exception e) { + fireChannelInactive(); + } + } + + public final void fireDataSend(Object data) throws Exception { + executeHandleSendData(data); + } + + public final EzyNioSession fireChannelActive() throws Exception { + EzyNioSession ss = handler.channelActive(); + ss.setSessionTicketsQueue(sessionTicketsQueue); + session.set(ss); + return ss; + } + + @Override + public final void onChannelInactivated(EzyChannel channel) { + channelDelegate.onChannelInactivated(channel); + } + + private void executeHandleSendData(Object data) { + CompletableFuture encodeFuture = + supplyAsync(() -> encodeData0(data), codecThreadPool); + CompletableFuture sendBytesFuture = encodeFuture + .thenAcceptAsync(bytes -> sendBytesToClient(bytes), handlerThreadPool); + processWithLogException(sendBytesFuture::get); + } + + private Object encodeData0(Object data) { + try { + return encodeData(data); + } + catch(Exception e) { + getLogger().error("decode data error on session: " + getSession().getClientAddress(), e); + return null; + } + } + + protected abstract Object encodeData(Object data) throws Exception; + + private void sendBytesToClient(Object bytes) { + try { + EzyChannel channel = getSession().getChannel(); + if(bytes != null && channel != null && channel.isConnected()) { + int writeBytes = channel.write(bytes); + executeAddWrittenBytes(writeBytes); + } + } + catch(Exception e) { + getLogger().error("can't send bytes: " + bytes + " to session: " + getSession().getClientAddress(), e); + } + } + + protected final void executeAddReadBytes(int bytes) { + statsThreadPool.execute(() -> addReadBytes(bytes)); + } + + private void executeAddWrittenBytes(int bytes) { + statsThreadPool.execute(() -> addWrittenBytes(bytes)); + } + + private synchronized void addReadBytes(int count) { + getSession().addReadBytes(count); + } + + private synchronized void addWrittenBytes(int count) { + getSession().addWrittenBytes(count); + } + + protected final EzyNioSession getSession() { + return session.get(); + } + + public static abstract class Builder implements EzyBuilder { + + private EzyChannel channel; + + private ExecutorService statsThreadPool; + private ExecutorService codecThreadPool; + private ExecutorService handlerThreadPool; + + private Object decoder; + private EzyNioObjectToByteEncoder encoder; + private EzyServerContext serverContext; + private EzySocketChannelDelegate channelDelegate; + private EzySessionTicketsQueue sessionTicketsQueue; + + public Builder channel(EzyChannel channel) { + this.channel = channel; + return this; + } + + public Builder decoder(Object decoder) { + this.decoder = decoder; + return this; + } + + public Builder encoder(Object encoder) { + this.encoder = (EzyNioObjectToByteEncoder) encoder; + return this; + } + + public Builder codecThreadPool(ExecutorService codecThreadPool) { + this.codecThreadPool = codecThreadPool; + return this; + } + + public Builder handlerThreadPool(ExecutorService handlerThreadPool) { + this.handlerThreadPool = handlerThreadPool; + return this; + } + + public Builder statsThreadPool(ExecutorService statsThreadPool) { + this.statsThreadPool = statsThreadPool; + return this; + } + + public Builder serverContext(EzyServerContext serverContext) { + this.serverContext = serverContext; + return this; + } + + public Builder channelDelegate(EzySocketChannelDelegate delegate) { + this.channelDelegate = delegate; + return this; + } + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return this; + } + } + +} 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 new file mode 100644 index 00000000..eb9552a0 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyHandlerGroup.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; + +public interface EzyHandlerGroup { + + void fireChannelInactive(); + + void fireExceptionCaught(Throwable throwable); + + void fireDataSend(Object data) throws Exception; + + EzyNioSession fireChannelActive() throws Exception; + + void fireChannelInactive(EzyDisconnectReason reason); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioByteToObjectDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioByteToObjectDecoder.java new file mode 100644 index 00000000..c86f7692 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioByteToObjectDecoder.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; + +public interface EzyNioByteToObjectDecoder { + + Object decode(EzyMessage message) throws Exception; + + void decode(ByteBuffer bytes, Queue queue) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataDecoder.java new file mode 100644 index 00000000..8a069acc --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataDecoder.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyNioDataDecoder extends EzyDestroyable { + + Object decode(EzyMessage message) throws Exception; + + void decode(byte[] bytes, EzyCallback callback) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataEncoder.java new file mode 100644 index 00000000..30f6a450 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataEncoder.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; + +public interface EzyNioDataEncoder { + + ByteBuffer encode(Object data) throws Exception; + +} 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 new file mode 100644 index 00000000..f8b832bd --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioDataHandler.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; + +public interface EzyNioDataHandler { + + public void channelInactive() throws Exception; + + public void channelRead(Object msg) throws Exception; + + public EzyNioSession channelActive() throws Exception; + + public void exceptionCaught(Throwable throwable) throws Exception; + + public void channelInactive(EzyDisconnectReason reason) 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 new file mode 100644 index 00000000..c64766f5 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioExceptionHandler.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +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 new file mode 100644 index 00000000..373e78d7 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioHandlerGroup.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +public interface EzyNioHandlerGroup extends EzyHandlerGroup { + + void fireBytesReceived(byte[] bytes) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioObjectToByteEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioObjectToByteEncoder.java new file mode 100644 index 00000000..81237d65 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzyNioObjectToByteEncoder.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; + +public interface EzyNioObjectToByteEncoder { + + ByteBuffer encode(Object msg) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioData.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioData.java new file mode 100644 index 00000000..e8f0afcb --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioData.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +public class EzySimpleNioData { + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataDecoder.java new file mode 100644 index 00000000..6d73fcac --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataDecoder.java @@ -0,0 +1,77 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.codec.EzyMessage; + +public class EzySimpleNioDataDecoder + extends EzyAbstractDataDecoder + implements EzyNioDataDecoder { + + private final Queue queue; + + public EzySimpleNioDataDecoder(EzyNioByteToObjectDecoder decoder) { + super(decoder); + this.queue = new LinkedList<>(); + } + + @Override + public Object decode(EzyMessage message) throws Exception { + return decoder.decode(message); + } + + @Override + public void decode( + byte[] bytes, EzyCallback callback) throws Exception { + predecode(bytes); + decoder.decode(buffer, queue); + handleQueue(callback); + postdecode(); + } + + private void handleQueue(EzyCallback callback) throws Exception { + while(!queue.isEmpty() && active) { + do { + callback.call(queue.poll()); + } + while(!queue.isEmpty()); + + if(buffer.hasRemaining()) { + decoder.decode(buffer, queue); + } + } + } + + private void predecode(byte[] bytes) { + if(buffer == null) + buffer = newBuffer(bytes); + else + buffer = mergeBytes(bytes); + } + + private void postdecode() { + buffer = getRemainBytes(buffer); + } + + private ByteBuffer newBuffer(byte[] bytes) { + return ByteBuffer.wrap(bytes); + } + + private ByteBuffer mergeBytes(byte[] bytes) { + int capacity = buffer.remaining() + bytes.length; + ByteBuffer merge = ByteBuffer.allocate(capacity).put(buffer).put(bytes); + merge.flip(); + return merge; + } + + private ByteBuffer getRemainBytes(ByteBuffer old) { + if(!old.hasRemaining()) + return null; + byte[] bytes = new byte[old.remaining()]; + old.get(bytes); + return ByteBuffer.wrap(bytes); + } +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataEncoder.java new file mode 100644 index 00000000..217e0e7a --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataEncoder.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import java.nio.ByteBuffer; + +public class EzySimpleNioDataEncoder implements EzyNioDataEncoder { + + private EzyNioObjectToByteEncoder encoder; + + public EzySimpleNioDataEncoder(EzyNioObjectToByteEncoder encoder) { + this.encoder = encoder; + } + + @Override + public ByteBuffer encode(Object data) throws Exception { + return encoder.encode(data); + } + +} 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 new file mode 100644 index 00000000..4a88926f --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioDataHandler.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.exception.EzyMaxRequestSizeException; +import com.tvd12.ezyfoxserver.handler.EzySimpleDataHandler; +import com.tvd12.ezyfoxserver.nio.delegate.EzySocketChannelDelegate; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyNioSessionManager; + +import lombok.Setter; + +public class EzySimpleNioDataHandler + extends EzySimpleDataHandler + implements EzyNioDataHandler { + + protected final EzyChannel channel; + + @Setter + protected EzySocketChannelDelegate channelDelegate; + + public EzySimpleNioDataHandler(EzyChannel channel) { + this.channel = channel; + } + + @Override + public EzyNioSession channelActive() throws Exception { + getLogger().debug("channel actived, add session"); + borrowSession(); + sessionActive(); + return session; + } + + @Override + public void channelRead(Object msg) throws Exception { + dataReceived((EzyArray)msg); + } + + @Override + public void onSessionReturned(EzyConstant reason) { + this.channelDelegate.onChannelInactivated(channel); + super.onSessionReturned(reason); + } + + @Override + public void exceptionCaught(Throwable cause) throws Exception { + if(cause instanceof EzyMaxRequestSizeException) { + getLogger().warn("exception: {}", cause.getMessage()); + super.exceptionCaught(cause); + } + else { + getLogger().debug("exception caught at session " + channel, cause); + channel.close(); + } + } + + private void borrowSession() { + borrowSession(this::newSession); + } + + private EzyNioSession newSession() { + return ((EzyNioSessionManager)sessionManager).borrowSession(channel); + } + +} 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 new file mode 100644 index 00000000..536543d8 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/handler/EzySimpleNioHandlerGroup.java @@ -0,0 +1,86 @@ +package com.tvd12.ezyfoxserver.nio.handler; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.codec.EzyMessage; + +public class EzySimpleNioHandlerGroup + extends EzyAbstractHandlerGroup + implements EzyNioHandlerGroup { + + private final EzyCallback decodeBytesCallback; + + public EzySimpleNioHandlerGroup(Builder builder) { + super(builder); + this.decodeBytesCallback = this::executeHandleReceivedMessage; + } + + @Override + protected EzyNioDataDecoder newDecoder(Object decoder) { + return new EzySimpleNioDataDecoder((EzyNioByteToObjectDecoder)decoder); + } + + @Override + protected EzyNioDataEncoder newEncoder(Object encoder) { + return new EzySimpleNioDataEncoder((EzyNioObjectToByteEncoder)encoder); + } + + @Override + protected Object encodeData(Object data) throws Exception { + return encoder.encode(data); + } + + @Override + public void fireBytesReceived(byte[] bytes) throws Exception { + handleReceivedBytes(bytes); + executeAddReadBytes(bytes.length); + } + + private synchronized void handleReceivedBytes(byte[] bytes) { + try { + decoder.decode(bytes, decodeBytesCallback); + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + private void executeHandleReceivedMessage(EzyMessage message) { + codecThreadPool.execute(() -> handleReceivedMesssage(message)); + } + + private void handleReceivedMesssage(EzyMessage message) { + Object data = decodeMessage(message); + handlerThreadPool.execute(() -> handleReceivedData(data)); + } + + private Object decodeMessage(EzyMessage message) { + try { + return decoder.decode(message); + } + catch(Exception e) { + getLogger().error("decode message error", e); + return null; + } + } + + private void handleReceivedData(Object data) { + try { + handler.channelRead(data); + } catch (Exception e) { + getLogger().error("handle data error, data: " + data, e); + } + } + + 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/socket/EzyBlockingSessionTicketsQueue.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyBlockingSessionTicketsQueue.java new file mode 100644 index 00000000..a42fb833 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyBlockingSessionTicketsQueue.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; + +public class EzyBlockingSessionTicketsQueue implements EzySessionTicketsQueue { + + private final BlockingQueue queue + = new LinkedBlockingQueue<>(); + + @Override + public void clear() { + queue.clear(); + } + + @Override + public void add(EzyNioSession session) { + queue.add(session); + } + + @Override + public EzyNioSession take() throws InterruptedException { + return queue.take(); + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNonBlockingPacketQueue.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNonBlockingPacketQueue.java new file mode 100644 index 00000000..e55991d9 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyNonBlockingPacketQueue.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +public class EzyNonBlockingPacketQueue implements EzyPacketQueue { + + private final int capacity; + private final Queue queue = new ConcurrentLinkedQueue<>(); + + public EzyNonBlockingPacketQueue() { + this(512); + } + + public EzyNonBlockingPacketQueue(int capacity) { + this.capacity = capacity; + } + + @Override + public void clear() { + queue.clear(); + } + + @Override + public EzyPacket take() { + return queue.poll(); + } + + @Override + public boolean isFull() { + return queue.size() == capacity; + } + + @Override + public boolean isEmpty() { + return queue.isEmpty(); + } + + @Override + public void add(EzyPacket packet) { + queue.add(packet); + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacket.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacket.java new file mode 100644 index 00000000..d8398f75 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacket.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; + +public interface EzyPacket { + + Object getData(); + + EzyTransportType getType(); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacketQueue.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacketQueue.java new file mode 100644 index 00000000..34560efd --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzyPacketQueue.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +public interface EzyPacketQueue { + + void clear(); + + EzyPacket take(); + + boolean isFull(); + + boolean isEmpty(); + + void add(EzyPacket packet); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySessionTicketsQueue.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySessionTicketsQueue.java new file mode 100644 index 00000000..dd96ebd6 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySessionTicketsQueue.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; + +public interface EzySessionTicketsQueue { + + void clear(); + + void add(EzyNioSession session); + + EzyNioSession take() throws InterruptedException; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySimplePacket.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySimplePacket.java new file mode 100644 index 00000000..7204b491 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySimplePacket.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import com.tvd12.ezyfoxserver.constant.EzyTransportType; + +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class EzySimplePacket implements EzyPacket { + + private Object data; + private EzyTransportType type = EzyTransportType.TCP; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketAcceptor.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketAcceptor.java new file mode 100644 index 00000000..c6273c29 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketAcceptor.java @@ -0,0 +1,123 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.util.Iterator; +import java.util.Set; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioHandlerGroup; + +public class EzySocketAcceptor extends EzySocketHandler { + + private boolean tcpNoDelay; + private Selector ownSelector; + private Selector readSelector; + + public EzySocketAcceptor(Builder builder) { + super(builder); + this.tcpNoDelay = builder.tcpNoDelay; + this.ownSelector = builder.ownSelector; + this.readSelector = builder.readSelector; + } + + @Override + protected String getThreadName() { + return "socket-acceptor"; + } + + @Override + protected void tryDestroy() throws Exception { + super.tryDestroy(); + this.ownSelector.close(); + } + + @Override + protected void tryLoop() { + getLogger().info("socket-acceptor threadpool has started"); + while(active) { + tryProcessReadyKeys(); + } + getLogger().info("socket-acceptor threadpool shutting down"); + } + + private void tryProcessReadyKeys() { + try { + processReadyKeys(); + } + catch(Exception e) { + getLogger().info("I/O error at socket-acceptor", e); + } + } + + private synchronized 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 { + ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); + if(key.isAcceptable()) { + SocketChannel clientChannel = serverChannel.accept(); + acceptConnection(clientChannel); + } + } + + private void acceptConnection(SocketChannel clientChannel) throws Exception { + clientChannel.configureBlocking(false); + clientChannel.socket().setTcpNoDelay(tcpNoDelay); + + EzyChannel channel = new EzySocketChannel(clientChannel); + + EzyNioHandlerGroup dataHandler = handlerGroupManager + .newHandlerGroup(channel, EzyConnectionType.SOCKET); + EzyNioSession session = dataHandler.fireChannelActive(); + + SelectionKey selectionKey = clientChannel.register(readSelector, SelectionKey.OP_READ); + session.setProperty(EzyNioSession.SELECTION_KEY, selectionKey); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySocketHandler.Builder { + + private boolean tcpNoDelay; + private Selector ownSelector; + private Selector readSelector; + + public Builder tcpNoDelay(boolean tcpNoDelay) { + this.tcpNoDelay = tcpNoDelay; + return this; + } + + public Builder ownSelector(Selector ownSelector) { + this.ownSelector = ownSelector; + return this; + } + + public Builder readSelector(Selector readSelector) { + this.readSelector = readSelector; + return this; + } + + @Override + public EzySocketAcceptor build() { + return new EzySocketAcceptor(this); + } + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketChannel.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketChannel.java new file mode 100644 index 00000000..86d3f283 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketChannel.java @@ -0,0 +1,59 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import static com.tvd12.ezyfoxserver.util.EzyReturner.returnWithException; + +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SocketChannel; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import static com.tvd12.ezyfoxserver.util.EzyProcessor.*; + +import lombok.Getter; + +@Getter +public class EzySocketChannel implements EzyChannel { + + private final SocketChannel channel; + private final SocketAddress serverAddress; + private final SocketAddress clientAddress; + + public EzySocketChannel(SocketChannel channel) { + this.channel = channel; + this.serverAddress = returnWithException(channel::getLocalAddress); + this.clientAddress = returnWithException(channel::getRemoteAddress); + } + + @Override + public int write(Object data) throws Exception { + return channel.write((ByteBuffer)data); + } + + @SuppressWarnings("unchecked") + @Override + public SocketChannel getConnection() { + return channel; + } + + @Override + public EzyConnectionType getConnectionType() { + return EzyConnectionType.SOCKET; + } + + @Override + public boolean isConnected() { + return channel.isConnected(); + } + + @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/EzySocketHandler.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketHandler.java new file mode 100644 index 00000000..562feaad --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketHandler.java @@ -0,0 +1,84 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.util.List; +import java.util.concurrent.ExecutorService; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.concurrent.EzyExecutors; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +public abstract class EzySocketHandler + extends EzyLoggable + implements EzyStartable, EzyDestroyable { + + protected int threadPoolSize; + protected ExecutorService threadPool; + protected EzyHandlerGroupManager handlerGroupManager; + + protected volatile boolean active; + + public EzySocketHandler(Builder builder) { + this.threadPoolSize = builder.threadPoolSize; + this.handlerGroupManager = builder.handlerGroupManager; + this.threadPool = EzyExecutors.newFixedThreadPool(threadPoolSize, "socket-acceptor"); + Runtime.getRuntime().addShutdownHook(new Thread(() -> threadPool.shutdown())); + } + + protected abstract String getThreadName(); + + @Override + public void start() throws Exception { + setActive(true); + startLoopService(); + } + + protected void setActive(boolean value) { + this.active = value; + } + + private void startLoopService() { + Runnable task = newServiceTask(); + for(int i = 0 ; i < threadPoolSize ; i++) + threadPool.execute(task); + } + + private Runnable newServiceTask() { + return this::tryLoop; + } + + protected abstract void tryLoop(); + + @Override + public void destroy() { + EzyProcessor.processWithLogException(this::tryDestroy); + } + + protected void tryDestroy() throws Exception { + setActive(false); + List remainTasks = threadPool.shutdownNow(); + getLogger().info("{} stopped. Never commenced execution task: " + remainTasks.size()); + } + + public static abstract class Builder> + implements EzyBuilder { + protected int threadPoolSize; + protected EzyHandlerGroupManager handlerGroupManager; + + @SuppressWarnings("unchecked") + public B threadPoolSize(int threadPoolSize) { + this.threadPoolSize = threadPoolSize; + return (B)this; + } + + @SuppressWarnings("unchecked") + public B handlerGroupManager(EzyHandlerGroupManager manager) { + this.handlerGroupManager = manager; + return (B)this; + } + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketReader.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketReader.java new file mode 100644 index 00000000..35fb448a --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketReader.java @@ -0,0 +1,133 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.nio.ByteBuffer; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.util.Iterator; +import java.util.Set; + +import com.tvd12.ezyfoxserver.nio.handler.EzyNioHandlerGroup; + +public class EzySocketReader extends EzySocketHandler { + + protected Selector ownSelector; + + public EzySocketReader(Builder builder) { + super(builder); + this.ownSelector = builder.ownSelector; + } + + @Override + protected String getThreadName() { + return "socket-reader"; + } + + @Override + protected void tryDestroy() throws Exception { + super.tryDestroy(); + this.ownSelector.close(); + } + + @Override + protected void tryLoop() { + getLogger().info("socket-reader threadpool has started"); + ByteBuffer buffer = ByteBuffer.allocateDirect(getMaxBufferSize()); + while(active) { + tryProcessReadyKeys(buffer); + } + getLogger().info("socket-reader threadpool shutting down"); + } + + private int getMaxBufferSize() { + return 8192; + } + + private void tryProcessReadyKeys(ByteBuffer buffer) { + try { + processReadyKeys(buffer); + Thread.sleep(5L); + } + catch(Exception e) { + getLogger().info("I/O error at socket-reader", e); + } + } + + private synchronized void processReadyKeys(ByteBuffer buffer) throws Exception { + ownSelector.selectNow(); + + Set readyKeys = this.ownSelector.selectedKeys(); + Iterator iterator = readyKeys.iterator(); + while(iterator.hasNext()) { + SelectionKey key = iterator.next(); + iterator.remove(); + if(key.isValid()) { + processReadyKey(key, buffer); + } + } + } + + private void processReadyKey(SelectionKey key, ByteBuffer buffer) throws Exception { + buffer.clear(); + if(key.isWritable()) { + processWritableKey(key, buffer); + } + if(key.isReadable()) { + processReadableKey(key, buffer); + } + } + + private void processWritableKey(SelectionKey key, ByteBuffer buffer) throws Exception { + + } + + private void processReadableKey(SelectionKey key, ByteBuffer buffer) throws Exception { + SocketChannel channel = (SocketChannel) key.channel(); + if(!channel.isConnected()) { + return; + } + long readBytes = channel.read(buffer); + if(readBytes == -1L) { + closeConnection(channel); + } + else { + processReadBytes(channel, buffer); + } + } + + private void processReadBytes(SocketChannel channel, ByteBuffer buffer) throws Exception { + buffer.flip(); + byte[] binary = new byte[buffer.limit()]; + buffer.get(binary); + EzyNioHandlerGroup group = handlerGroupManager.getHandlerGroup(channel); + if(group != null) { + group.fireBytesReceived(binary); + } + + } + + private void closeConnection(SelectableChannel channel) throws Exception { + handlerGroupManager.removeHandlerGroup((SocketChannel) channel); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySocketHandler.Builder { + + private Selector ownSelector; + + public Builder ownSelector(Selector ownSelector) { + this.ownSelector = ownSelector; + return this; + } + + @Override + public EzySocketReader build() { + return new EzySocketReader(this); + } + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketWriter.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketWriter.java new file mode 100644 index 00000000..82b0a69c --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/socket/EzySocketWriter.java @@ -0,0 +1,89 @@ +package com.tvd12.ezyfoxserver.nio.socket; + +import java.nio.channels.SocketChannel; + +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioHandlerGroup; + +public class EzySocketWriter extends EzySocketHandler { + + private final EzySessionTicketsQueue sessionTicketsQueue; + + public EzySocketWriter(Builder builder) { + super(builder); + this.sessionTicketsQueue = builder.sessionTicketsQueue; + } + + @Override + protected String getThreadName() { + return "socket-writer"; + } + + @Override + protected void tryDestroy() throws Exception { + super.tryDestroy(); + this.sessionTicketsQueue.clear(); + } + + @Override + protected void tryLoop() { + while(active) { + tryProcessSessionTicketsQueue(); + } + getLogger().info("socket-writer threadpool shutting down."); + } + + private void tryProcessSessionTicketsQueue() { + try { + EzyNioSession session = sessionTicketsQueue.take(); + processSessionQueue(session); + } + catch (InterruptedException e) { + getLogger().warn("socket-writer thread interrupted: " + Thread.currentThread()); + setActive(false); + } + catch(Throwable throwable) { + getLogger().warn("problems in socket-writer main loop, thread: " + Thread.currentThread(), throwable); + } + } + + private void processSessionQueue(EzyNioSession session) throws Exception { + SocketChannel channel = session.getConnection(); + if(channel == null) return; + EzyNioHandlerGroup group = handlerGroupManager.getHandlerGroup(channel); + if(group == null) return; + EzyPacketQueue queue = session.getPacketQueue(); + boolean emptyQueue = processSessionQueue(group, queue); + if(!emptyQueue) sessionTicketsQueue.add(session); + } + + private boolean processSessionQueue(EzyNioHandlerGroup group, EzyPacketQueue queue) + throws Exception { + if(!queue.isEmpty()) { + EzyPacket packet = queue.take(); + group.fireDataSend(packet.getData()); + return queue.isEmpty(); + } + return true; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySocketHandler.Builder { + + private EzySessionTicketsQueue sessionTicketsQueue; + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return this; + } + + @Override + public EzySocketWriter build() { + return new EzySocketWriter(this); + } + + } +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataDecoder.java new file mode 100644 index 00000000..8a535e50 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataDecoder.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.nio.handler.EzyAbstractDataDecoder; + +public class EzySimpleWsDataDecoder + extends EzyAbstractDataDecoder + implements EzyWsDataDecoder { + + public EzySimpleWsDataDecoder(EzyWsByteToObjectDecoder decoder) { + super(decoder); + this.buffer = ByteBuffer.allocate(32768); + } + + @Override + public void decode(String bytes, EzyCallback callback) throws Exception { + callback.call(decoder.decode(bytes)); + } + + @Override + public void decode(byte[] bytes, int offset, int len, EzyCallback callback) throws Exception { + ByteBuffer buffer = newBuffer(bytes, offset, len); + callback.call(decoder.decode(buffer)); + } + + private ByteBuffer newBuffer(byte[] bytes, int offset, int len) { + ByteBuffer used = buffer; + int capacity = len - offset; + if(buffer.capacity() < capacity) + used = ByteBuffer.allocate(capacity); + used.clear(); + used.put(bytes, offset, len); + used.flip(); + return used; + } + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataEncoder.java new file mode 100644 index 00000000..c930e8be --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsDataEncoder.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import java.nio.ByteBuffer; + +public class EzySimpleWsDataEncoder implements EzyWsDataEncoder { + + private EzyWsObjectToByteEncoder encoder; + + public EzySimpleWsDataEncoder(EzyWsObjectToByteEncoder encoder) { + this.encoder = encoder; + } + + @Override + public ByteBuffer encode(Object data) throws Exception { + return encoder.encode(data); + } + + @Override + public T encode(Object data, Class outType) throws Exception { + return encoder.encode(data, outType); + } + +} 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 new file mode 100644 index 00000000..4c9024e3 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzySimpleWsHandlerGroup.java @@ -0,0 +1,93 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.nio.handler.EzyAbstractHandlerGroup; + +public class EzySimpleWsHandlerGroup + extends EzyAbstractHandlerGroup + implements EzyWsHandlerGroup { + + private final EzyCallback decodeBytesCallback; + + public EzySimpleWsHandlerGroup(Builder builder) { + super(builder); + this.decodeBytesCallback = this::executeHandleReceivedData; + } + + @Override + protected EzyWsDataDecoder newDecoder(Object decoder) { + return new EzySimpleWsDataDecoder((EzyWsByteToObjectDecoder)decoder); + } + + @Override + protected EzyWsDataEncoder newEncoder(Object encoder) { + return new EzySimpleWsDataEncoder((EzyWsObjectToByteEncoder)encoder); + } + + @Override + protected Object encodeData(Object data) throws Exception { + return encoder.encode(data, String.class); + } + + @Override + public void fireBytesReceived(String bytes) throws Exception { + executeHandleReceivedBytes(bytes); + executeAddReadBytes(bytes.length()); + } + + @Override + public void fireBytesReceived(byte[] bytes, int offset, int len) throws Exception { + executeHandleReceivedBytes(bytes, offset, len); + executeAddReadBytes(len - offset); + } + + private void executeHandleReceivedBytes(String bytes) { + codecThreadPool.execute(() -> handleReceivedBytes(bytes)); + } + + private void executeHandleReceivedBytes(byte[] bytes, int offset, int len) { + codecThreadPool.execute(() -> handleReceivedBytes(bytes, offset, len)); + } + + private void handleReceivedBytes(String bytes) { + try { + decoder.decode(bytes, decodeBytesCallback); + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + private void handleReceivedBytes(byte[] bytes, int offset, int len) { + try { + decoder.decode(bytes, offset, len, decodeBytesCallback); + } + catch(Throwable throwable) { + fireExceptionCaught(throwable); + } + } + + private void executeHandleReceivedData(Object data) { + handlerThreadPool.execute(() -> handleReceivedData(data)); + } + + private void handleReceivedData(Object data) { + try { + handler.channelRead(data); + } catch (Exception e) { + getLogger().error("handle data error, data: " + data, e); + } + } + + 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/EzyWsByteToObjectDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsByteToObjectDecoder.java new file mode 100644 index 00000000..81647f6a --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsByteToObjectDecoder.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import java.nio.ByteBuffer; + +public interface EzyWsByteToObjectDecoder { + + Object decode(String bytes) throws Exception; + + Object decode(ByteBuffer bytes) throws Exception; + +} 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 new file mode 100644 index 00000000..ff92a1be --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsChannel.java @@ -0,0 +1,61 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import static com.tvd12.ezyfoxserver.util.EzyProcessor.processWithException; +import static com.tvd12.ezyfoxserver.util.EzyProcessor.processWithLogException; + +import java.net.SocketAddress; + +import org.eclipse.jetty.websocket.api.Session; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; + +import lombok.Getter; + +@Getter +public class EzyWsChannel implements EzyChannel { + + private final Session session; + private final SocketAddress serverAddress; + private final SocketAddress clientAddress; + + public EzyWsChannel(Session session) { + this.session = session; + this.serverAddress = session.getLocalAddress(); + this.clientAddress = session.getRemoteAddress(); + } + + @Override + public int write(Object data) throws Exception { + String bytes = (String)data; + int bytesSize = bytes.length(); + session.getRemote().sendString(bytes); + return bytesSize; + } + + @SuppressWarnings("unchecked") + @Override + public Session getConnection() { + return session; + } + + @Override + public EzyConnectionType getConnectionType() { + return EzyConnectionType.WEBSOCKET; + } + + @Override + public boolean isConnected() { + return session.isOpen(); + } + + @Override + public void disconnect() { + processWithLogException(session::disconnect); + } + + @Override + public void close() { + processWithException(session::close); + } +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataDecoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataDecoder.java new file mode 100644 index 00000000..46536113 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataDecoder.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; + +public interface EzyWsDataDecoder extends EzyDestroyable { + + void decode(String bytes, EzyCallback callback) throws Exception; + + void decode(byte[] bytes, int offset, int len, EzyCallback callback) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataEncoder.java new file mode 100644 index 00000000..20f4a059 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsDataEncoder.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.nio.handler.EzyNioDataEncoder; + +public interface EzyWsDataEncoder extends EzyNioDataEncoder { + + T encode(Object data, Class outType) throws Exception; + +} 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 new file mode 100644 index 00000000..96d3a17b --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandler.java @@ -0,0 +1,93 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import java.net.SocketTimeoutException; + +import org.eclipse.jetty.websocket.api.Session; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError; +import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; +import org.eclipse.jetty.websocket.api.annotations.WebSocket; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.constant.EzyDisconnectReason; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.setting.EzySessionManagementSetting; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@WebSocket +public class EzyWsHandler extends EzyLoggable { + + private final EzySessionManagementSetting settings; + private final EzyHandlerGroupManager handlerGroupManager; + + public EzyWsHandler(Builder builder) { + this.settings = builder.settings; + this.handlerGroupManager = builder.handlerGroupManager; + } + + @OnWebSocketClose + public void onClose(Session session, int statusCode, String reason) { + getLogger().debug("close session: {}, statusCode = {}, reason = ", session.getRemoteAddress(), statusCode, reason); + EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); + dataHandler.fireChannelInactive(); + } + + @OnWebSocketError + public void onError(Session session, Throwable throwable) { + getLogger().debug("Error: session: " + session.getRemoteAddress(), throwable); + EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); + if(throwable instanceof SocketTimeoutException) { + dataHandler.fireChannelInactive(EzyDisconnectReason.IDLE); + } + else { + dataHandler.fireExceptionCaught(throwable); + } + } + + @OnWebSocketConnect + public void onConnect(Session session) throws Exception { + session.setIdleTimeout(settings.getSessionMaxIdleTime()); + + EzyWsHandlerGroup dataHandler = handlerGroupManager + .newHandlerGroup(new EzyWsChannel(session), EzyConnectionType.WEBSOCKET); + dataHandler.fireChannelActive(); + } + + @OnWebSocketMessage + public void onMessage(Session session, String message) throws Exception { + EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); + dataHandler.fireBytesReceived(message); + } + + @OnWebSocketMessage + public void onMessage(Session session, byte[] payload, int offset, int len) throws Exception { + EzyWsHandlerGroup dataHandler = handlerGroupManager.getHandlerGroup(session); + dataHandler.fireBytesReceived(payload, offset, len); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private EzySessionManagementSetting settings; + private EzyHandlerGroupManager handlerGroupManager; + + public Builder settings(EzySessionManagementSetting settings) { + this.settings = settings; + return this; + } + + public Builder handlerGroupManager(EzyHandlerGroupManager handlerGroupManager) { + this.handlerGroupManager = handlerGroupManager; + 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 new file mode 100644 index 00000000..cbc9e232 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsHandlerGroup.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.nio.handler.EzyHandlerGroup; + +public interface EzyWsHandlerGroup extends EzyHandlerGroup { + + 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/EzyWsObjectToByteEncoder.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsObjectToByteEncoder.java new file mode 100644 index 00000000..95feb41d --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsObjectToByteEncoder.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.nio.handler.EzyNioObjectToByteEncoder; + +public interface EzyWsObjectToByteEncoder extends EzyNioObjectToByteEncoder { + + T encode(Object msg, Class outType) throws Exception; + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsSocketWriter.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsSocketWriter.java new file mode 100644 index 00000000..01c50ac8 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/websocket/EzyWsSocketWriter.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.nio.websocket; + +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.handler.EzyHandlerGroup; +import com.tvd12.ezyfoxserver.nio.socket.EzyPacket; +import com.tvd12.ezyfoxserver.nio.socket.EzyPacketQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySessionTicketsQueue; +import com.tvd12.ezyfoxserver.nio.socket.EzySocketHandler; + +public class EzyWsSocketWriter extends EzySocketHandler { + + private final EzySessionTicketsQueue sessionTicketsQueue; + + public EzyWsSocketWriter(Builder builder) { + super(builder); + this.sessionTicketsQueue = builder.sessionTicketsQueue; + } + + @Override + protected String getThreadName() { + return "ws-socket-writer"; + } + + @Override + protected void tryDestroy() throws Exception { + super.tryDestroy(); + this.sessionTicketsQueue.clear(); + } + + @Override + protected void tryLoop() { + while(active) { + tryProcessSessionTicketsQueue(); + } + getLogger().info("ws-socket-writer threadpool shutting down."); + } + + private void tryProcessSessionTicketsQueue() { + try { + EzyNioSession session = sessionTicketsQueue.take(); + processSessionQueue(session); + } + catch (InterruptedException e) { + getLogger().warn("socket-writer thread interrupted: " + Thread.currentThread()); + setActive(false); + } + catch(Throwable throwable) { + getLogger().warn("problems in ws-socket-writer main loop, thread: " + Thread.currentThread(), throwable); + } + } + + private void processSessionQueue(EzyNioSession session) throws Exception { + Object connection = session.getConnection(); + if(connection == null) return; + EzyHandlerGroup group = handlerGroupManager.getHandlerGroup(connection); + if(group == null) return; + EzyPacketQueue queue = session.getPacketQueue(); + boolean emptyQueue = processSessionQueue(group, queue); + if(!emptyQueue) sessionTicketsQueue.add(session); + } + + private boolean processSessionQueue(EzyHandlerGroup group, EzyPacketQueue queue) + throws Exception { + if(!queue.isEmpty()) { + EzyPacket packet = queue.take(); + group.fireDataSend(packet.getData()); + return queue.isEmpty(); + } + return true; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySocketHandler.Builder { + + private EzySessionTicketsQueue sessionTicketsQueue; + + public Builder sessionTicketsQueue(EzySessionTicketsQueue queue) { + this.sessionTicketsQueue = queue; + return this; + } + + @Override + public EzyWsSocketWriter build() { + return new EzyWsSocketWriter(this); + } + + } +} 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 new file mode 100644 index 00000000..6b334bcd --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyHandlerGroupManager.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.nio.wrapper; + +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.handler.EzyHandlerGroup; + +public interface EzyHandlerGroupManager { + + T getHandlerGroup(Object connection); + + T removeHandlerGroup(Object connection); + + T newHandlerGroup(EzyChannel channel, EzyConnectionType type); + +} diff --git a/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyNioSessionManager.java b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyNioSessionManager.java new file mode 100644 index 00000000..96d10814 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/EzyNioSessionManager.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.nio.wrapper; + +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; + +public interface EzyNioSessionManager extends EzySessionManager { + + /** + * Borrow session from pool and map the session to channel + * + * @param channel the channel + * @return the session mapped channel + */ + EzyNioSession borrowSession(EzyChannel channel); + + /** + * Get session by connection + * + * @param connection the connection + * @return the session mapped to the connection + */ + EzyNioSession getSession(Object connection); + +} 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 new file mode 100644 index 00000000..d5e34933 --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyHandlerGroupManagerImpl.java @@ -0,0 +1,149 @@ +package com.tvd12.ezyfoxserver.nio.wrapper.impl; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.constant.EzyConnectionType; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.nio.delegate.EzySocketChannelDelegate; +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.factory.EzyCodecFactory; +import com.tvd12.ezyfoxserver.nio.factory.EzyHandlerGroupBuilderFactory; +import com.tvd12.ezyfoxserver.nio.handler.EzyAbstractHandlerGroup; +import com.tvd12.ezyfoxserver.nio.handler.EzyHandlerGroup; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyHandlerGroupManager; +import com.tvd12.ezyfoxserver.util.EzyDestroyable; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzyHandlerGroupManagerImpl + extends EzyLoggable + implements EzyHandlerGroupManager, EzySocketChannelDelegate, EzyDestroyable { + + private final ExecutorService statsThreadPool; + private final ExecutorService codecThreadPool; + private final ExecutorService handlerThreadPool; + + private final EzyCodecFactory codecFactory; + private final EzyServerContext serverContext; + + private final Map groupsByConnection; + private final EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; + + public EzyHandlerGroupManagerImpl(Builder builder) { + this.statsThreadPool = builder.statsThreadPool; + this.codecThreadPool = builder.codecThreadPool; + this.handlerThreadPool = builder.handlerThreadPool; + this.codecFactory = builder.codecFactory; + this.serverContext = builder.serverContext; + this.handlerGroupBuilderFactory = builder.handlerGroupBuilderFactory; + this.groupsByConnection = new ConcurrentHashMap<>(); + } + + @SuppressWarnings("unchecked") + @Override + public T newHandlerGroup(EzyChannel channel, EzyConnectionType type) { + EzyHandlerGroup group = newHandlerGroupBuilder(type) + .channel(channel) + .channelDelegate(this) + .serverContext(serverContext) + .decoder(newDataDecoder(type)) + .encoder(newDataEncoder(type)) + .statsThreadPool(statsThreadPool) + .codecThreadPool(codecThreadPool) + .handlerThreadPool(handlerThreadPool) + .build(); + groupsByConnection.put(channel.getConnection(), group); + return (T) group; + } + + private EzyAbstractHandlerGroup.Builder newHandlerGroupBuilder(EzyConnectionType type) { + return handlerGroupBuilderFactory.newBuilder(type); + } + + @SuppressWarnings("unchecked") + @Override + public T getHandlerGroup(Object connection) { + return (T) groupsByConnection.get(connection); + } + + @SuppressWarnings("unchecked") + @Override + public T removeHandlerGroup(Object connection) { + EzyHandlerGroup group = groupsByConnection.get(connection); + if(group != null) + group.fireChannelInactive(); + return (T)group; + } + + @Override + public void onChannelInactivated(EzyChannel channel) { + groupsByConnection.remove(channel.getConnection()); + } + + private Object newDataDecoder(EzyConnectionType type) { + return codecFactory.newDecoder(type); + } + + private Object newDataEncoder(EzyConnectionType type) { + return codecFactory.newEncoder(type); + } + + @Override + public void destroy() { + groupsByConnection.clear(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + private ExecutorService statsThreadPool; + private ExecutorService codecThreadPool; + private ExecutorService handlerThreadPool; + + private EzyServerContext serverContext; + private EzyCodecFactory codecFactory; + + private EzyHandlerGroupBuilderFactory handlerGroupBuilderFactory; + + public Builder statsThreadPool(ExecutorService statsThreadPool) { + this.statsThreadPool = statsThreadPool; + return this; + } + + public Builder codecThreadPool(ExecutorService codecThreadPool) { + this.codecThreadPool = codecThreadPool; + return this; + } + + public Builder handlerThreadPool(ExecutorService handlerThreadPool) { + this.handlerThreadPool = handlerThreadPool; + return this; + } + + public Builder codecFactory(EzyCodecFactory codecFactory) { + this.codecFactory = codecFactory; + return this; + } + + public Builder serverContext(EzyServerContext serverContext) { + this.serverContext = serverContext; + return this; + } + + 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 new file mode 100644 index 00000000..45bbf48c --- /dev/null +++ b/ezyfox-server-nio/src/main/java/com/tvd12/ezyfoxserver/nio/wrapper/impl/EzyNioSessionManagerImpl.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.nio.wrapper.impl; + +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.nio.entity.EzyChannel; +import com.tvd12.ezyfoxserver.nio.entity.EzyNioSession; +import com.tvd12.ezyfoxserver.nio.factory.EzyNioSessionFactory; +import com.tvd12.ezyfoxserver.nio.wrapper.EzyNioSessionManager; +import com.tvd12.ezyfoxserver.pattern.EzyObjectFactory; +import com.tvd12.ezyfoxserver.wrapper.EzySimpleSessionManager; + +public class EzyNioSessionManagerImpl + extends EzySimpleSessionManager + implements EzyNioSessionManager { + + protected ConcurrentHashMap sessionsByConnection + = new ConcurrentHashMap<>(); + + protected EzyNioSessionManagerImpl(Builder builder) { + super(builder); + } + + @Override + protected void unmapSession(EzyNioSession session) { + super.unmapSession(session); + sessionsByConnection.remove(session.getChannel()); + } + + @Override + protected void clearSession(EzyNioSession session) { + super.clearSession(session); + } + + @Override + public EzyNioSession getSession(Object connection) { + return sessionsByConnection.get(connection); + } + + @Override + public EzyNioSession borrowSession(EzyChannel channel) { + EzyNioSession ss = borrowSession(channel.getConnectionType()); + ss.setChannel(channel); + sessionsByConnection.put(channel.getConnection(), ss); + return ss; + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzySimpleSessionManager.Builder { + + @Override + public EzyNioSessionManagerImpl build() { + return new EzyNioSessionManagerImpl(this); + } + + @Override + protected EzyObjectFactory newObjectFactory() { + return new EzyNioSessionFactory(); + } + } + + +} 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 new file mode 100644 index 00000000..555b6d1e --- /dev/null +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/ConcurrentLinkedListTest.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.nio.testing; + +import java.util.concurrent.ConcurrentLinkedQueue; + +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(); + } + } + +} 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 new file mode 100644 index 00000000..8c257b0a --- /dev/null +++ b/ezyfox-server-nio/src/test/java/com/tvd12/ezyfoxserver/nio/testing/Websock.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.nio.testing; + +import org.eclipse.jetty.server.Handler; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.handler.ContextHandler; +import org.eclipse.jetty.server.handler.ContextHandlerCollection; +import org.eclipse.jetty.websocket.api.Session; +import org.eclipse.jetty.websocket.api.WebSocketAdapter; +import org.eclipse.jetty.websocket.server.WebSocketHandler; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; +import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; +import org.eclipse.jetty.websocket.servlet.WebSocketCreator; +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"); + } + } + + public static void main(String[] args) throws Exception { + Server server = new Server(2208); + + // needed. + + ContextHandlerCollection handlerCollection = new ContextHandlerCollection(); + handlerCollection.addHandler(createWebsocketHandler()); + + server.setHandler(handlerCollection); + + server.start(); + } + + private static ContextHandler createWebsocketHandler() { + ContextHandler contextHandler = new ContextHandler("/ws"); + contextHandler.setAllowNullPathInfo(true); // disable redirect from /ws + // to /ws/ + + 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/resources/AllTests.tng.xml b/ezyfox-server-nio/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..1de16472 --- /dev/null +++ b/ezyfox-server-nio/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-niocodec/.gitignore b/ezyfox-server-niocodec/.gitignore new file mode 100755 index 00000000..ebae499a --- /dev/null +++ b/ezyfox-server-niocodec/.gitignore @@ -0,0 +1,32 @@ +# Operating System Files + +*.DS_Store +Thumbs.db + +# Build Files # + +bin +target +build/ +.gradle + +# Eclipse Project Files # + +.classpath +.project +.settings + +# IntelliJ IDEA Files # + +*.iml +*.ipr +*.iws +*.idea + +# Test files + +*-uploaded +dependency-reduced-pom.xml +README.html + +upload-dir diff --git a/ezyfox-server-niocodec/assembly.xml b/ezyfox-server-niocodec/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-niocodec/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-niocodec/pom.xml b/ezyfox-server-niocodec/pom.xml new file mode 100755 index 00000000..4c87d545 --- /dev/null +++ b/ezyfox-server-niocodec/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-niocodec + 1.0.0 + + ezyfox-server-niocodec + http://maven.apache.org + + + 1.0.0 + 1.0.0 + 1.0.0 + + + + + com.tvd12 + ezyfox-server-nio + ${ezy.nio.version} + + + com.tvd12 + ezyfox-server-msgpack + ${ezy.msgpack.version} + + + com.tvd12 + ezyfox-server-jackson + ${ezy.jackson.version} + + + + diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonByteToMessageDecoder.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonByteToMessageDecoder.java new file mode 100644 index 00000000..da434e33 --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonByteToMessageDecoder.java @@ -0,0 +1,26 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.nio.websocket.EzyWsByteToObjectDecoder; + +public class JacksonByteToMessageDecoder implements EzyWsByteToObjectDecoder { + + private final EzyMessageDeserializer deserializer; + + public JacksonByteToMessageDecoder(EzyMessageDeserializer deserializer) { + this.deserializer = deserializer; + } + + @Override + public Object decode(String bytes) throws Exception { + return deserializer.deserialize(bytes); + } + + @Override + public Object decode(ByteBuffer bytes) throws Exception { + return deserializer.deserialize(bytes); + } + +} diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonCodecCreator.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonCodecCreator.java new file mode 100644 index 00000000..bff13ef3 --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonCodecCreator.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.codec.EzyMessageByTypeSerializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonObjectMapperBuilder; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.JacksonSimpleSerializer; + +public class JacksonCodecCreator implements EzyCodecCreator { + + protected final ObjectMapper objectMapper; + protected final EzyMessageDeserializer deserializer; + protected final EzyMessageByTypeSerializer serializer; + + public JacksonCodecCreator() { + this.objectMapper = newObjectMapper(); + this.serializer = newSerializer(); + this.deserializer = newDeserializer(); + } + + protected ObjectMapper newObjectMapper() { + return JacksonObjectMapperBuilder.newInstance().build(); + } + + protected EzyMessageDeserializer newDeserializer() { + return new JacksonSimpleDeserializer(objectMapper); + } + + protected EzyMessageByTypeSerializer newSerializer() { + return new JacksonSimpleSerializer(objectMapper); + } + + @Override + public Object newEncoder() { + return new JacksonMessageToByteEncoder(serializer); + } + + @Override + public Object newDecoder(int maxRequestSize) { + return new JacksonByteToMessageDecoder(deserializer); + } + +} diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonMessageToByteEncoder.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonMessageToByteEncoder.java new file mode 100644 index 00000000..7ee44695 --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/JacksonMessageToByteEncoder.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.tvd12.ezyfoxserver.codec.EzyMessageByTypeSerializer; +import com.tvd12.ezyfoxserver.nio.websocket.EzyWsObjectToByteEncoder; + +public class JacksonMessageToByteEncoder implements EzyWsObjectToByteEncoder { + + protected final Logger logger; + protected final EzyMessageByTypeSerializer serializer; + + public JacksonMessageToByteEncoder(EzyMessageByTypeSerializer serializer) { + this.serializer = serializer; + this.logger = LoggerFactory.getLogger(getClass()); + } + + @Override + public ByteBuffer encode(Object msg) throws Exception { + byte[] bytes = serializer.serialize(msg); + return ByteBuffer.wrap(bytes); + } + + @Override + public T encode(Object msg, Class outType) throws Exception { + return serializer.serialize(msg, outType); + } + +} diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackByteToObjectDecoder.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackByteToObjectDecoder.java new file mode 100644 index 00000000..b81051ab --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackByteToObjectDecoder.java @@ -0,0 +1,173 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.PREPARE_MESSAGE; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_CONTENT; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_HEADER; +import static com.tvd12.ezyfoxserver.codec.EzyDecodeState.READ_MESSAGE_SIZE; + +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Queue; + +import com.tvd12.ezyfoxserver.codec.EzyDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyIDecodeState; +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioByteToObjectDecoder; + +import lombok.Setter; + +public class MsgPackByteToObjectDecoder implements EzyNioByteToObjectDecoder { + + protected final Handlers handlers; + protected final EzyMessageDeserializer deserializer; + + public MsgPackByteToObjectDecoder( + EzyMessageDeserializer deserializer, int maxSize) { + this.deserializer = deserializer; + this.handlers = Handlers.builder() + .maxSize(maxSize) + .build(); + } + + @Override + public Object decode(EzyMessage message) throws Exception { + return deserializer.deserialize(message.getContent()); + } + + @Override + public void decode(ByteBuffer bytes, Queue out) throws Exception { + handlers.handle(bytes, out); + } + +} + +@Setter +abstract class AbstractHandler implements EzyDecodeHandler { + + protected EzyDecodeHandler nextHandler; + protected EzyMessageReader messageReader; + + @Override + public EzyDecodeHandler nextHandler() { + return nextHandler; + } +} + +class PrepareMessage extends AbstractHandler { + + @Override + public EzyIDecodeState nextState() { + return READ_MESSAGE_HEADER; + } + + @Override + public boolean handle(ByteBuffer in, Queue out) { + messageReader.clear(); + return true; + } +} + +class ReadMessageHeader extends AbstractHandler { + + @Override + public EzyIDecodeState nextState() { + return EzyDecodeState.READ_MESSAGE_SIZE; + } + + @Override + public boolean handle(ByteBuffer in, Queue out) { + return messageReader.readHeader(in); + } + +} + +class ReadMessageSize extends AbstractHandler { + + protected final int maxSize; + + public ReadMessageSize(int maxSize) { + this.maxSize = maxSize; + } + + @Override + public EzyIDecodeState nextState() { + return READ_MESSAGE_CONTENT; + } + + @Override + public boolean handle(ByteBuffer in, Queue out) { + return messageReader.readSize(in, maxSize); + } +} + +class ReadMessageContent extends AbstractHandler { + + @Override + public EzyIDecodeState nextState() { + return PREPARE_MESSAGE; + } + + @Override + public boolean handle(ByteBuffer in, Queue out) { + if(!messageReader.readContent(in)) + return false; + out.add(messageReader.get()); + return true; + } + +} + +class Handlers extends EzyDecodeHandlers { + + protected Handlers(Builder builder) { + super(builder); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends AbstractBuilder { + protected int maxSize; + protected EzyMessageReader messageReader = new EzyMessageReader(); + + public Builder maxSize(int maxSize) { + this.maxSize = maxSize; + return this; + } + + public Handlers build() { + return new Handlers(this); + } + + @Override + protected void addHandlers( + Map answer) { + EzyDecodeHandler readMessgeHeader = new ReadMessageHeader(); + EzyDecodeHandler prepareMessage = new PrepareMessage(); + EzyDecodeHandler readMessageSize = new ReadMessageSize(maxSize); + EzyDecodeHandler readMessageContent = new ReadMessageContent(); + answer.put(PREPARE_MESSAGE, newHandler(prepareMessage, readMessgeHeader)); + answer.put(READ_MESSAGE_HEADER, newHandler(readMessgeHeader, readMessageSize)); + answer.put(READ_MESSAGE_SIZE, newHandler(readMessageSize, readMessageContent)); + answer.put(READ_MESSAGE_CONTENT, newHandler(readMessageContent)); + } + + + private EzyDecodeHandler newHandler(EzyDecodeHandler handler) { + return newHandler(handler, null); + } + + private EzyDecodeHandler newHandler(EzyDecodeHandler handler, EzyDecodeHandler next) { + return newHandler((AbstractHandler)handler, next); + } + + private EzyDecodeHandler newHandler(AbstractHandler handler, EzyDecodeHandler next) { + handler.setNextHandler(next); + handler.setMessageReader(messageReader); + return handler; + } + } + +} diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackCodecCreator.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackCodecCreator.java new file mode 100644 index 00000000..5c699f2a --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackCodecCreator.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import com.tvd12.ezyfoxserver.codec.EzyCodecCreator; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; +import com.tvd12.ezyfoxserver.codec.EzyObjectToMessage; +import com.tvd12.ezyfoxserver.codec.MsgPackObjectToMessage; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.nio.codec.EzySimpleMessageToBytes; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioByteToObjectDecoder; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioObjectToByteEncoder; + +public class MsgPackCodecCreator implements EzyCodecCreator { + + protected final EzyMessageToBytes messageToBytes + = EzySimpleMessageToBytes.builder().build(); + protected final EzyObjectToMessage objectToMessage + = MsgPackObjectToMessage.builder().build(); + protected final EzyMessageDeserializer deserializer + = new MsgPackSimpleDeserializer(); + + @Override + public EzyNioByteToObjectDecoder newDecoder(int maxRequestSize) { + return new MsgPackByteToObjectDecoder(deserializer, maxRequestSize); + } + + @Override + public EzyNioObjectToByteEncoder newEncoder() { + return new MsgPackObjectToByteEncoder(messageToBytes, objectToMessage); + } + +} diff --git a/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackObjectToByteEncoder.java b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackObjectToByteEncoder.java new file mode 100644 index 00000000..3a534a10 --- /dev/null +++ b/ezyfox-server-niocodec/src/main/java/com/tvd12/ezyfoxserver/nio/codec/MsgPackObjectToByteEncoder.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.nio.codec; + +import java.nio.ByteBuffer; + +import com.tvd12.ezyfoxserver.codec.EzyMessage; +import com.tvd12.ezyfoxserver.codec.EzyMessageToBytes; +import com.tvd12.ezyfoxserver.codec.EzyObjectToMessage; +import com.tvd12.ezyfoxserver.nio.handler.EzyNioObjectToByteEncoder; + +public class MsgPackObjectToByteEncoder implements EzyNioObjectToByteEncoder { + + protected final EzyMessageToBytes messageToBytes; + protected final EzyObjectToMessage objectToMessage; + + public MsgPackObjectToByteEncoder( + EzyMessageToBytes messageToBytes, + EzyObjectToMessage objectToMessage) { + this.messageToBytes = messageToBytes; + this.objectToMessage = objectToMessage; + } + + @Override + public ByteBuffer encode(Object msg) throws Exception { + return convertObjectToBytes(msg); + } + + protected ByteBuffer convertObjectToBytes(Object object) { + return convertMessageToBytes(convertObjectToMessage(object)); + } + + protected EzyMessage convertObjectToMessage(Object object) { + return objectToMessage.convert(object); + } + + protected ByteBuffer convertMessageToBytes(EzyMessage message) { + return messageToBytes.convert(message); + } + +} diff --git a/ezyfox-server-niocodec/src/test/resources/AllTests.tng.xml b/ezyfox-server-niocodec/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..1de16472 --- /dev/null +++ b/ezyfox-server-niocodec/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-niorunner/.gitignore b/ezyfox-server-niorunner/.gitignore new file mode 100755 index 00000000..669d453f --- /dev/null +++ b/ezyfox-server-niorunner/.gitignore @@ -0,0 +1,33 @@ +# Operating System Files + +*.DS_Store +Thumbs.db + +# Build Files # + +bin +target +build/ +.gradle + +# Eclipse Project Files # + +.classpath +.project +.settings + +# IntelliJ IDEA Files # + +*.iml +*.ipr +*.iws +*.idea + +# Test files + +*-uploaded +dependency-reduced-pom.xml +README.html + +upload-dir +/logs/ diff --git a/ezyfox-server-niorunner/assembly.xml b/ezyfox-server-niorunner/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-niorunner/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-niorunner/pom.xml b/ezyfox-server-niorunner/pom.xml new file mode 100755 index 00000000..a6fb1817 --- /dev/null +++ b/ezyfox-server-niorunner/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-niorunner + 1.0.0 + + ezyfox-server-niorunner + http://maven.apache.org + + + 1.0.0 + 1.0.0 + + + + + com.tvd12 + ezyfox-server-nio + ${ezy.nio.version} + + + com.tvd12 + ezyfox-server-niocodec + ${ezy.niocodec.version} + + + com.tvd12 + ezyfox-server-binding + 1.0.0 + + + com.tvd12 + ezyfox-server-bean + 1.0.0 + + + + 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 new file mode 100644 index 00000000..dbc2b877 --- /dev/null +++ b/ezyfox-server-niorunner/src/main/java/com/tvd12/ezyfoxserver/nio/EzyNioRunner.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.nio; + +import com.tvd12.ezyfoxserver.EzyRunner; +import com.tvd12.ezyfoxserver.EzyStarter.Builder; + +public class EzyNioRunner extends EzyRunner { + + 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 new file mode 100644 index 00000000..1de16472 --- /dev/null +++ b/ezyfox-server-niorunner/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-rabbitmq/pom.xml b/ezyfox-server-rabbitmq/pom.xml new file mode 100644 index 00000000..b6874261 --- /dev/null +++ b/ezyfox-server-rabbitmq/pom.xml @@ -0,0 +1,38 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-rabbitmq + 1.0.0 + ezyfox-server-rabbitmq + http://maven.apache.org + + + 1.0.0 + 1.0.0 + 4.2.1 + + + + + com.tvd12 + ezyfox-server-msgpack + ${ezy.msgpack.version} + + + com.tvd12 + ezyfox-server-common + ${ezy.common.version} + + + com.rabbitmq + amqp-client + ${rabbitmq.version} + + + + \ No newline at end of file diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcClient.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcClient.java new file mode 100644 index 00000000..741a7aa7 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcClient.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.rabbitmq; + +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcResponseEntity; + +public interface EzyRpcClient { + + /** + * + * sync call + * + * @param the value type + * @return the returned value + */ + EzyRpcResponseEntity sync(EzyRpcProcedure procedure); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcProcedureCaller.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcProcedureCaller.java new file mode 100644 index 00000000..06d09bd5 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/EzyRpcProcedureCaller.java @@ -0,0 +1,10 @@ +package com.tvd12.ezyfoxserver.rabbitmq; + +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.exception.EzyRpcException; + +public interface EzyRpcProcedureCaller { + + Object call(EzyRpcProcedure procedure) throws EzyRpcException; + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/callback/EzyRpcCallback.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/callback/EzyRpcCallback.java new file mode 100644 index 00000000..e51fb6fc --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/callback/EzyRpcCallback.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.rabbitmq.callback; + +import com.tvd12.ezyfoxserver.callback.EzyCallback; + +public interface EzyRpcCallback extends EzyCallback { +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureDeserializer.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureDeserializer.java new file mode 100644 index 00000000..1a5a59e4 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureDeserializer.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.rabbitmq.codec; + +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; + +public interface EzyRpcProcedureDeserializer { + + EzyRpcProcedure deserialize(byte[] value); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureSerializer.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureSerializer.java new file mode 100644 index 00000000..e23a904e --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcProcedureSerializer.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.rabbitmq.codec; + +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; + +public interface EzyRpcProcedureSerializer { + + byte[] serialize(EzyRpcProcedure procedure); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureDeserializer.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureDeserializer.java new file mode 100644 index 00000000..4f1f8ef4 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureDeserializer.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.rabbitmq.codec; + +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.entity.EzyArray; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcSimpleProcedure; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EzyRpcSimpleProcedureDeserializer implements EzyRpcProcedureDeserializer { + + protected EzyMessageDeserializer deserializer; + + @Override + public EzyRpcProcedure deserialize(byte[] value) { + return deserialize(toArray(value)); + } + + protected EzyRpcProcedure deserialize(EzyArray array) { + EzyRpcSimpleProcedure procedure = new EzyRpcSimpleProcedure(); + procedure.setParent(array.get(0, String.class)); + procedure.setName(array.get(1, String.class)); + procedure.setArguments(array.get(2, EzyArray.class)); + return procedure; + } + + protected EzyArray toArray(byte[] value) { + return deserializer.deserialize(value); + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureSerializer.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureSerializer.java new file mode 100644 index 00000000..459a9596 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/codec/EzyRpcSimpleProcedureSerializer.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.rabbitmq.codec; + +import java.util.ArrayList; +import java.util.List; + +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.util.EzyEntityBuilders; + +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class EzyRpcSimpleProcedureSerializer + extends EzyEntityBuilders + implements EzyRpcProcedureSerializer { + + protected EzyMessageSerializer messageSerializer; + + @Override + public byte[] serialize(EzyRpcProcedure procedure) { + return messageSerializer.serialize(toArray(procedure)); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected List toArray(EzyRpcProcedure proc) { + List list = new ArrayList<>(); + list.add(proc.getParent()); + list.add(proc.getName()); + list.add(proc.getArguments()); + return list; + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitConnectionFactoryBuilder.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitConnectionFactoryBuilder.java new file mode 100644 index 00000000..c5ce20f8 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitConnectionFactoryBuilder.java @@ -0,0 +1,88 @@ +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import java.util.concurrent.ThreadFactory; + +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.ExceptionHandler; +import com.rabbitmq.client.impl.ForgivingExceptionHandler; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.concurrent.EzyThreadFactory; + +public class EzyRabbitConnectionFactoryBuilder implements EzyBuilder { + protected int port = 5672; + protected String username = "guest"; + protected String password = "guest"; + protected String host = "localhost"; + protected String vhost = "/"; + protected ThreadFactory threadFactory; + protected ExceptionHandler exceptionHandler; + + public EzyRabbitConnectionFactoryBuilder host(String host) { + this.host = host; + return this; + } + + public EzyRabbitConnectionFactoryBuilder vhost(String vhost) { + this.vhost = vhost; + return this; + } + + public EzyRabbitConnectionFactoryBuilder port(int port) { + this.port = port; + return this; + } + + public EzyRabbitConnectionFactoryBuilder username(String username) { + this.username = username; + return this; + } + + public EzyRabbitConnectionFactoryBuilder password(String password) { + this.password = password; + return this; + } + + public EzyRabbitConnectionFactoryBuilder threadFactory(ThreadFactory factory) { + this.threadFactory = factory; + return this; + } + + public EzyRabbitConnectionFactoryBuilder threadFactory(String poolName) { + return threadFactory(newThreadFactory(poolName)); + } + + @Override + public ConnectionFactory build() { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost(host); + factory.setPort(port); + factory.setThreadFactory(getThreadFactory()); + factory.setUsername(username); + factory.setPassword(password); + factory.setVirtualHost(vhost); + factory.setExceptionHandler(getExceptionHandler()); + return factory; + } + + private ThreadFactory getThreadFactory() { + return threadFactory != null ? threadFactory : newThreadFactory(); + } + + private ThreadFactory newThreadFactory() { + return newThreadFactory("threadpool"); + } + + protected ThreadFactory newThreadFactory(String poolName) { + return EzyThreadFactory.builder() + .prefix("rabbitmq").poolName(poolName).build(); + } + + protected ExceptionHandler getExceptionHandler() { + return exceptionHandler != null ? exceptionHandler : newExceptionHandler(); + } + + protected ExceptionHandler newExceptionHandler() { + return new ForgivingExceptionHandler(); + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitEnpoint.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitEnpoint.java new file mode 100644 index 00000000..551473cd --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitEnpoint.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import com.rabbitmq.client.Channel; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.util.EzyStartable; + +import lombok.Setter; + +@Setter +public abstract class EzyRabbitEnpoint + extends EzyLoggable + implements EzyStartable { + + protected String queue; + protected Channel channel; + protected EzyMessageSerializer messageSerializer; + protected EzyMessageDeserializer messageDeserializer; + + protected byte[] serializeToBytes(Object value) { + return messageSerializer.serialize(value); + } + + protected T deserializeToObject(byte[] value) { + return messageDeserializer.deserialize(value); + } + + public static abstract class Builder> + implements EzyBuilder { + protected String queue; + protected Channel channel; + protected EzyMessageSerializer messageSerializer; + protected EzyMessageDeserializer messageDeserializer; + + public B queue(String queue) { + this.queue = queue; + return getThis(); + } + + public B channel(Channel channel) { + this.channel = channel; + return getThis(); + } + + public B messageSerializer(EzyMessageSerializer messageSerializer) { + this.messageSerializer = messageSerializer; + return getThis(); + } + + public B messageDeserializer(EzyMessageDeserializer messageDeserializer) { + this.messageDeserializer = messageDeserializer; + return getThis(); + } + + @Override + public EzyRabbitEnpoint build() { + EzyRabbitEnpoint answer = newProduct(); + answer.setQueue(queue); + answer.setChannel(channel); + answer.setMessageSerializer(messageSerializer); + answer.setMessageDeserializer(messageDeserializer); + return answer; + } + + protected abstract EzyRabbitEnpoint newProduct(); + + @SuppressWarnings("unchecked") + protected B getThis() { + return (B)this; + } + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcCaller.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcCaller.java new file mode 100644 index 00000000..e03a346b --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcCaller.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import java.io.IOException; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.RpcClient; + +public class EzyRabbitRpcCaller extends RpcClient { + + public EzyRabbitRpcCaller(Channel channel, String exchange, String routingKey, String replyTo, int timeout) throws + IOException { + super(channel, exchange, routingKey, replyTo, timeout); + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcClient.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcClient.java new file mode 100644 index 00000000..2fad5875 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcClient.java @@ -0,0 +1,176 @@ +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import java.io.IOException; +import java.util.Map; +import java.util.concurrent.TimeoutException; + +import com.rabbitmq.client.AMQP.BasicProperties; +import com.rabbitmq.client.RpcClient.Response; +import com.rabbitmq.client.ShutdownSignalException; +import com.tvd12.ezyfoxserver.rabbitmq.EzyRpcClient; +import com.tvd12.ezyfoxserver.rabbitmq.codec.EzyRpcProcedureSerializer; +import com.tvd12.ezyfoxserver.rabbitmq.codec.EzyRpcSimpleProcedureSerializer; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcHeaders; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcResponseEntity; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcSimpleHeaders; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcSimpleResponseEntity; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcValueProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.factory.EzyCorrelationIdFactory; +import com.tvd12.ezyfoxserver.rabbitmq.factory.EzySimpleCorrelationIdFactory; + +public class EzyRabbitRpcClient + extends EzyRabbitEnpoint implements EzyRpcClient { + + protected int timeout; + protected String exchange; + protected String routingKey; + protected String replyQueue; + + protected EzyCorrelationIdFactory correlationIdFactory; + protected EzyRpcProcedureSerializer procedureSerializer; + + protected EzyRabbitRpcCaller client; + + @Override + public void start() throws Exception { + this.client = newClient(); + } + + protected EzyRabbitRpcCaller newClient() throws IOException { + return new EzyRabbitRpcCaller(channel, exchange, routingKey, replyQueue, timeout); + } + + @Override + public EzyRpcResponseEntity sync(EzyRpcProcedure procedure) { + try { + return call(procedure); + } + catch(Exception e) { + throw new IllegalArgumentException(e); + } + } + + public EzyRpcResponseEntity call(EzyRpcProcedure procedure) + throws IOException, ShutdownSignalException, TimeoutException { + return call(procedure, newCorrelationId()); + } + + protected EzyRpcResponseEntity call(EzyRpcProcedure procedure, String corrId) + throws IOException, ShutdownSignalException, TimeoutException { + byte[] body = serializeProcedure(procedure); + BasicProperties props = newReplyProperties(corrId); + Response response = client.doCall(props, body); + Object responseBody = deserializeResult(response.getBody(), getReturnType(procedure)); + EzyRpcHeaders responseHeader = newResponseHeaders(response.getProperties().getHeaders()); + return newResponseEntity(responseHeader, responseBody); + } + + protected EzyRpcResponseEntity newResponseEntity(EzyRpcHeaders headers, Object body) { + return EzyRpcSimpleResponseEntity.builder().headers(headers).body(body).build(); + } + + @SuppressWarnings("rawtypes") + protected EzyRpcHeaders newResponseHeaders(Map headers) { + return EzyRpcSimpleHeaders.builder().putAll(headers).build(); + } + + @SuppressWarnings("rawtypes") + protected Class getReturnType(EzyRpcProcedure procedure) { + if(!(procedure instanceof EzyRpcValueProcedure)) + return null; + return ((EzyRpcValueProcedure) procedure).getReturnType(); + } + + @SuppressWarnings("rawtypes") + protected T deserializeResult(byte[] result, Class type) { + return deserializeToObject(result); + } + + protected byte[] serializeProcedure(EzyRpcProcedure procedure) { + return procedureSerializer.serialize(procedure); + } + + protected BasicProperties newReplyProperties(String correlationId) { + return new BasicProperties.Builder() + .correlationId(correlationId) + .replyTo(replyQueue) + .build(); + } + + protected String newCorrelationId() { + return correlationIdFactory.newCorrelationId(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyRabbitEnpoint.Builder { + protected int timeout = 3000; + protected String replyQueue = "hello-queue"; + protected String routingKey = "hola"; + protected String exchange = "hello-exchange"; + + protected EzyCorrelationIdFactory correlationIdFactory; + protected EzyRpcProcedureSerializer procedureSerializer; + + public Builder timeout(int timeout) { + this.timeout = timeout; + return this; + } + + public Builder replyQueue(String replyQueue) { + this.replyQueue = replyQueue; + return this; + } + + public Builder exchange(String exchange) { + this.exchange = exchange; + return this; + } + + public Builder routingKey(String routingKey) { + this.routingKey = routingKey; + return this; + } + + @Override + public EzyRabbitRpcClient build() { + return (EzyRabbitRpcClient) super.build(); + } + + @Override + protected EzyRabbitEnpoint newProduct() { + EzyRabbitRpcClient answer = new EzyRabbitRpcClient(); + answer.timeout = timeout; + answer.exchange = exchange; + answer.replyQueue = replyQueue; + answer.routingKey = routingKey; + answer.procedureSerializer = getProcedureSeriazlier(); + answer.correlationIdFactory = getCorrelationIdFactory(); + return answer; + } + + protected String getReplyQueue() { + try { + return channel.queueDeclare().getQueue(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + protected EzyCorrelationIdFactory getCorrelationIdFactory() { + if(correlationIdFactory != null) + return correlationIdFactory; + return new EzySimpleCorrelationIdFactory(); + } + + protected EzyRpcProcedureSerializer getProcedureSeriazlier() { + if(procedureSerializer != null) + return procedureSerializer; + return new EzyRpcSimpleProcedureSerializer(messageSerializer); + } + + } +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcHandler.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcHandler.java new file mode 100644 index 00000000..fe9f100c --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcHandler.java @@ -0,0 +1,61 @@ +// Copyright (c) 2007-Present Pivotal Software, Inc. All rights reserved. +// +// This software, the RabbitMQ Java client library, is triple-licensed under the +// Mozilla Public License 1.1 ("MPL"), the GNU General Public License version 2 +// ("GPL") and the Apache License version 2 ("ASL"). For the MPL, please see +// LICENSE-MPL-RabbitMQ. For the GPL, please see LICENSE-GPL2. For the ASL, +// please see LICENSE-APACHE2. +// +// This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, +// either express or implied. See the LICENSE file for specific language governing +// rights and limitations of this software. +// +// If you have any questions regarding licensing, please contact us at +// info@rabbitmq.com. + +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import java.io.IOException; + +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.AMQP.BasicProperties; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.QueueingConsumer; +import com.rabbitmq.client.RpcServer; + +@SuppressWarnings("deprecation") +public class EzyRabbitRpcHandler extends RpcServer { + + public EzyRabbitRpcHandler(Channel channel, String queueName) throws IOException { + super(channel, queueName); + } + + @Override + public void processRequest(QueueingConsumer.Delivery request) + throws IOException { + AMQP.BasicProperties requestProperties = request.getProperties(); + String correlationId = requestProperties.getCorrelationId(); + String replyTo = requestProperties.getReplyTo(); + if (correlationId != null && replyTo != null) + { + AMQP.BasicProperties.Builder replyPropertiesBuilder = new AMQP.BasicProperties.Builder(); + byte[] replyBody = handleCall(request, replyPropertiesBuilder); + replyPropertiesBuilder.correlationId(correlationId); + AMQP.BasicProperties replyProperties = replyPropertiesBuilder.build(); + getChannel().basicPublish("", replyTo, replyProperties, replyBody); + } else { + handleCast(request); + } + } + + protected byte[] handleCall( + QueueingConsumer.Delivery request, BasicProperties.Builder replyPropertiesBuilder) { + return handleCall(request.getBody(), replyPropertiesBuilder); + } + + protected byte[] handleCall( + byte[] requestBody, BasicProperties.Builder replyPropertiesBuilder) { + return new byte[0]; + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcServer.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcServer.java new file mode 100644 index 00000000..53c75dbc --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/endpoint/EzyRabbitRpcServer.java @@ -0,0 +1,121 @@ +package com.tvd12.ezyfoxserver.rabbitmq.endpoint; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.rabbitmq.client.AMQP.BasicProperties; +import com.tvd12.ezyfoxserver.rabbitmq.EzyRpcProcedureCaller; +import com.tvd12.ezyfoxserver.rabbitmq.codec.EzyRpcProcedureDeserializer; +import com.tvd12.ezyfoxserver.rabbitmq.codec.EzyRpcSimpleProcedureDeserializer; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.exception.EzyRpcException; + +import lombok.Setter; + +public class EzyRabbitRpcServer extends EzyRabbitEnpoint { + + protected EzyRabbitRpcHandler server; + @Setter + protected Map queueArguments; + @Setter + protected EzyRpcProcedureCaller procedureCaller; + @Setter + protected EzyRpcProcedureDeserializer procedureDeserializer; + + @Override + public void start() throws Exception { + getLogger().info("start server queue = {}", queue); + server = newServer(); + server.mainloop(); + } + + protected EzyRabbitRpcHandler newServer() throws IOException { + return new EzyRabbitRpcHandler(channel, queue) { + public byte[] handleCall(byte[] requestBody, + BasicProperties.Builder replyPropertiesBuilder) { + return doHandleCall(requestBody, replyPropertiesBuilder); + } + }; + } + + protected byte[] doHandleCall(byte[] requestBody, + BasicProperties.Builder replyPropertiesBuilder) { + int code = 200; + String message = "success"; + byte[] responseBody = null; + try { + EzyRpcProcedure procedure = getProcedure(requestBody); + Object answer = executeProcedure(procedure); + responseBody = serializeToBytes(answer); + } + catch (EzyRpcException e) { + code = e.getCode(); + message = e.getMessage(); + } + Map headers = new HashMap<>(); + headers.put("code", code); + headers.put("msg", message); + replyPropertiesBuilder.headers(headers); + return responseBody; + } + + protected Object executeProcedure(EzyRpcProcedure procedure) + throws EzyRpcException { + return procedureCaller.call(procedure); + } + + protected EzyRpcProcedure getProcedure(byte[] body) { + return procedureDeserializer.deserialize(body); + } + + protected BasicProperties newReplyProps(BasicProperties rev) { + return new BasicProperties.Builder() + .correlationId(rev.getCorrelationId()) + .build(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder extends EzyRabbitEnpoint.Builder { + protected Map queueArguments; + protected EzyRpcProcedureCaller procedureCaller; + protected EzyRpcProcedureDeserializer procedureDeserializer; + + public Builder queueArguments(Map queueArguments) { + this.queueArguments = queueArguments; + return this; + } + + public Builder procedureCaller(EzyRpcProcedureCaller procedureCaller) { + this.procedureCaller = procedureCaller; + return this; + } + + @Override + public EzyRabbitRpcServer build() { + return (EzyRabbitRpcServer) super.build(); + } + + + @Override + protected EzyRabbitEnpoint newProduct() { + EzyRabbitRpcServer answer = new EzyRabbitRpcServer(); + answer.setProcedureCaller(procedureCaller); + answer.setQueueArguments(getQueueArguments()); + answer.setProcedureDeserializer(newProcedureDeserializer()); + return answer; + } + + protected Map getQueueArguments() { + return queueArguments != null ? queueArguments : new HashMap<>(); + } + + protected EzyRpcProcedureDeserializer newProcedureDeserializer() { + return new EzyRpcSimpleProcedureDeserializer(messageDeserializer); + } + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcAbstractProcedure.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcAbstractProcedure.java new file mode 100644 index 00000000..215cbc38 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcAbstractProcedure.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +public abstract class EzyRpcAbstractProcedure implements EzyRpcProcedure { + + protected String name; + protected String parent; + protected EzyArray arguments; + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcHeaders.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcHeaders.java new file mode 100644 index 00000000..72fdd0e7 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcHeaders.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +public interface EzyRpcHeaders { + + T get(Object key); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcProcedure.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcProcedure.java new file mode 100644 index 00000000..5c2158c1 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcProcedure.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +import com.tvd12.ezyfoxserver.entity.EzyArray; + +public interface EzyRpcProcedure { + + /** + * @return the procedure name + */ + String getName(); + + /** + * @return the parent class or namespace + */ + String getParent(); + + /** + * @return the arguments + */ + EzyArray getArguments(); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcResponseEntity.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcResponseEntity.java new file mode 100644 index 00000000..843645ab --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcResponseEntity.java @@ -0,0 +1,8 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +public interface EzyRpcResponseEntity { + + T getBody(); + + EzyRpcHeaders getHeaders(); +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleHeaders.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleHeaders.java new file mode 100644 index 00000000..d3090d57 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleHeaders.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +public class EzyRpcSimpleHeaders implements EzyRpcHeaders { + + protected Map headers; + + protected EzyRpcSimpleHeaders(Builder builder) { + this.headers = builder.headers; + } + + @SuppressWarnings("unchecked") + @Override + public T get(Object key) { + return (T) headers.get(key); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected Map headers = new HashMap<>(); + + public Builder put(Object key, Object value) { + headers.put(key, value); + return this; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public Builder putAll(Map map) { + if(map != null) + headers.putAll(map); + return this; + } + + @Override + public EzyRpcHeaders build() { + return new EzyRpcSimpleHeaders(this); + } + } + + @Override + public String toString() { + return "(#headers: " + headers + ")"; + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleProcedure.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleProcedure.java new file mode 100644 index 00000000..aa4ef62b --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleProcedure.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +import org.msgpack.annotation.Message; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@Message +@ToString(callSuper = true) +public class EzyRpcSimpleProcedure extends EzyRpcAbstractProcedure { + + @SuppressWarnings("rawtypes") + private Class returnType; + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleResponseEntity.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleResponseEntity.java new file mode 100644 index 00000000..c5d03629 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcSimpleResponseEntity.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +import lombok.Builder; +import lombok.Getter; +import lombok.ToString; + +@Getter +@Builder +@ToString(of = {"headers", "body"}) +public class EzyRpcSimpleResponseEntity implements EzyRpcResponseEntity { + + protected Object body; + protected EzyRpcHeaders headers; + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcValueProcedure.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcValueProcedure.java new file mode 100644 index 00000000..301e5f8e --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/entity/EzyRpcValueProcedure.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.rabbitmq.entity; + +public interface EzyRpcValueProcedure extends EzyRpcProcedure { + + /** + * @return the return type + */ + @SuppressWarnings("rawtypes") + Class getReturnType(); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/exception/EzyRpcException.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/exception/EzyRpcException.java new file mode 100644 index 00000000..6a523fbb --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/exception/EzyRpcException.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.rabbitmq.exception; + +import lombok.Getter; + +public class EzyRpcException extends Exception { + private static final long serialVersionUID = 6116417224071566449L; + + @Getter + private int code; + + public EzyRpcException(int code, String message) { + super(message); + this.code = code; + } + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzyCorrelationIdFactory.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzyCorrelationIdFactory.java new file mode 100644 index 00000000..edee4f5f --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzyCorrelationIdFactory.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.rabbitmq.factory; + +public interface EzyCorrelationIdFactory { + + String newCorrelationId(); + +} diff --git a/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzySimpleCorrelationIdFactory.java b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzySimpleCorrelationIdFactory.java new file mode 100644 index 00000000..8ce783f2 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/main/java/com/tvd12/ezyfoxserver/rabbitmq/factory/EzySimpleCorrelationIdFactory.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.rabbitmq.factory; + +import java.util.concurrent.atomic.AtomicLong; + +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzySimpleCorrelationIdFactory + extends EzyLoggable + implements EzyCorrelationIdFactory { + + private AtomicLong generator = new AtomicLong(); + + @Override + public String newCorrelationId() { + return String.valueOf(generator.incrementAndGet()); + } + +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/RabbitRpcAllRunner.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/RabbitRpcAllRunner.java new file mode 100644 index 00000000..dfaf5e40 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/RabbitRpcAllRunner.java @@ -0,0 +1,138 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.tvd12.ezyfoxserver.builder.EzyArrayBuilder; +import com.tvd12.ezyfoxserver.codec.EzyMessageDeserializer; +import com.tvd12.ezyfoxserver.codec.EzyMessageSerializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleDeserializer; +import com.tvd12.ezyfoxserver.codec.MsgPackSimpleSerializer; +import com.tvd12.ezyfoxserver.factory.EzyEntityFactory; +import com.tvd12.ezyfoxserver.rabbitmq.EzyRpcProcedureCaller; +import com.tvd12.ezyfoxserver.rabbitmq.endpoint.EzyRabbitConnectionFactoryBuilder; +import com.tvd12.ezyfoxserver.rabbitmq.endpoint.EzyRabbitRpcClient; +import com.tvd12.ezyfoxserver.rabbitmq.endpoint.EzyRabbitRpcServer; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcProcedure; +import com.tvd12.ezyfoxserver.rabbitmq.entity.EzyRpcSimpleProcedure; + +public class RabbitRpcAllRunner { + + public static void main(String[] args) throws Exception { + EzyEntityFactory.create(EzyArrayBuilder.class); + startServer(); + sleep(); +// asynRpc(); + rpc(); + } + + protected static void startServer() throws Exception { + new Thread(()-> { + try { + System.out.println("thread-" + Thread.currentThread().getName() + ": start server"); + newServer().start(); + } catch (Exception e) { + e.printStackTrace(); + } + }).start(); + + } + + protected static void sleep() throws Exception { + Thread.sleep(1000); + } + + protected static void asynRpc() { + new Thread() { + public void run() { + try { + rpc(); + } catch (Exception e) { + e.printStackTrace(); + } + }; + } + .start(); + } + + protected static void rpc() throws Exception { + EzyRabbitRpcClient client = newClient(); + client.start(); + System.out.println("thread-" + Thread.currentThread().getName() + ": start rpc"); + client.sync(newProcedure()); + long start = System.currentTimeMillis(); + for(int i = 0 ; i < 1000 ; i++) + client.sync(newProcedure()); +// System.out.println("i = " + i + ", result = " + client.sync(newProcedure())); + System.out.println("elapsed = " + (System.currentTimeMillis() - start)); + } + + protected static EzyRpcProcedure newProcedure() { + EzyRpcSimpleProcedure procedure = new EzyRpcSimpleProcedure(); + procedure.setParent(""); + procedure.setName(""); + procedure.setArguments(EzyEntityFactory.create(EzyArrayBuilder.class).append(100).build()); + procedure.setReturnType(int.class); + return procedure; + } + + protected static EzyRabbitRpcClient newClient() throws Exception { + ConnectionFactory connectionFactory = new EzyRabbitConnectionFactoryBuilder() + .build(); + Connection connection = connectionFactory.newConnection(); + Channel channel = connection.createChannel(); + channel.basicQos(1); + channel.queueDeclare("rmqia-rpc-queue", false, false, false, null); + channel.queueDeclare("rmqia-rpc-client-queue", false, false, false, null); + channel.queueBind("rmqia-rpc-queue", "rmqia-rpc-exchange", "rmqia-rpc-routing-key"); + return EzyRabbitRpcClient.builder() + .timeout(300 * 1000) + .channel(channel) + .queue("rmqia-rpc-queue") + .exchange("rmqia-rpc-exchange") + .routingKey("rmqia-rpc-routing-key") + .replyQueue("rmqia-rpc-client-queue") + .messageSerializer(newMessageSerializer()) + .messageDeserializer(newMessageDeserializer()) + .build(); + } + + protected static EzyRabbitRpcServer newServer() throws Exception { + ConnectionFactory connectionFactory = new EzyRabbitConnectionFactoryBuilder() + .build(); + Connection connection = connectionFactory.newConnection(); + Channel channel = connection.createChannel(); + channel.basicQos(1); + channel.queueDeclare("rmqia-rpc-queue", false, false, false, null); + return EzyRabbitRpcServer.builder() + .queue("rmqia-rpc-queue") + .channel(channel) + .messageSerializer(newMessageSerializer()) + .messageDeserializer(newMessageDeserializer()) + .procedureCaller(new EzyRpcProcedureCaller() { + + @Override + public Object call(EzyRpcProcedure procedure) { + int n = procedure.getArguments().get(0, int.class); + return n + 3; + } + }) + .build(); + } + + protected static EzyMessageSerializer newMessageSerializer() { + return new MsgPackSimpleSerializer(); + } + + protected static EzyMessageDeserializer newMessageDeserializer() { + return new MsgPackSimpleDeserializer(); + } + + protected static Logger getLogger() { + return LoggerFactory.getLogger(RabbitRpcAllRunner.class); + } + +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/EndPoint.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/EndPoint.java new file mode 100644 index 00000000..b5323fce --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/EndPoint.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.first; + +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; + +/** + * Represents a connection with a queue + * + * @author syntx + * + */ +public abstract class EndPoint { + + protected Channel channel; + protected Connection connection; + protected String endPointName; + + public EndPoint(String endpointName) throws Exception { + this.endPointName = endpointName; + + // Create a connection factory + ConnectionFactory factory = new ConnectionFactory(); + + // hostname of your rabbitmq server + factory.setHost("localhost"); + + // getting a connection + connection = factory.newConnection(); + + // creating a channel + channel = connection.createChannel(); + + // declaring a queue for this channel. If queue does not exist, + // it will be created on the server. + channel.queueDeclare(endpointName, false, false, false, null); + } + + /** + * Close channel and connection. Not necessary as it happens implicitly any + * way. + * + * @throws Exception + */ + public void close() throws Exception { + this.channel.close(); + this.connection.close(); + } +} \ No newline at end of file diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Main.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Main.java new file mode 100644 index 00000000..5760941f --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Main.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.first; + +public class Main { + + public Main() throws Exception { + + QueueConsumer consumer = new QueueConsumer("queue"); + Thread consumerThread = new Thread(consumer); + consumerThread.start(); + + Producer producer = new Producer("queue"); + + long time = System.currentTimeMillis(); + for (int i = 0; i < 1; i++) { + producer.sendMessage("String message#" + i); + System.out.println("Message Number " + i + " sent."); + } + long offset = System.currentTimeMillis() - time; + System.out.println("elapsed time = " + offset); + } + + /** + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + new Main(); + } +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Producer.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Producer.java new file mode 100644 index 00000000..e3e93c7e --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/Producer.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.first; + +import java.io.IOException; +import java.io.Serializable; + + +/** + * The producer endpoint that writes to the queue. + * @author syntx + * + */ +public class Producer extends EndPoint{ + + public Producer(String endPointName) throws Exception{ + super(endPointName); + } + + public void sendMessage(Serializable object) throws IOException { + channel.basicPublish("",endPointName, null, object.toString().getBytes()); + } +} \ No newline at end of file diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/QueueConsumer.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/QueueConsumer.java new file mode 100644 index 00000000..963c455f --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/first/QueueConsumer.java @@ -0,0 +1,51 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.first; + +import java.io.IOException; + +import com.rabbitmq.client.AMQP.BasicProperties; +import com.rabbitmq.client.Consumer; +import com.rabbitmq.client.Envelope; +import com.rabbitmq.client.ShutdownSignalException; + + +/** + * The endpoint that consumes messages off of the queue. Happens to be runnable. + * @author syntx + * + */ +public class QueueConsumer extends EndPoint implements Runnable, Consumer{ + + public QueueConsumer(String endPointName) throws Exception{ + super(endPointName); + } + + public void run() { + try { + //start consuming messages. Auto acknowledge messages. + channel.basicConsume(endPointName, true,this); + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Called when consumer is registered. + */ + public void handleConsumeOk(String consumerTag) { + System.out.println("Consumer "+consumerTag +" registered"); + } + + /** + * Called when new message is available. + */ + public void handleDelivery(String consumerTag, Envelope env, + BasicProperties props, byte[] body) throws IOException { + System.out.println("received : " + new String(body)); + + } + + public void handleCancel(String consumerTag) {} + public void handleCancelOk(String consumerTag) {} + public void handleRecoverOk(String consumerTag) {} + public void handleShutdownSignal(String consumerTag, ShutdownSignalException arg1) {} +} \ No newline at end of file diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main.java new file mode 100644 index 00000000..f5f6a760 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main.java @@ -0,0 +1,69 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.second; + +import com.rabbitmq.client.AMQP.BasicProperties; +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.RpcClient; +import com.rabbitmq.client.RpcClient.Response; +import com.rabbitmq.client.RpcServer; + +public class Main { + + public static void main(String[] args) throws Exception { + Thread serverThread = new Thread(new Runnable() { + + @Override + public void run() { + try { + System.out.println(Thread.currentThread().getName() + ": start server"); + newRpcServer().mainloop(); + } + catch(Exception e) { + e.printStackTrace(); + } + } + }); + serverThread.start(); + System.out.println(Thread.currentThread().getName() + ": rpc server"); + + Thread.sleep(1000L); + + System.out.println(Thread.currentThread().getName() + ": rpc server after sleep"); + + RpcClient client = newRpcClient(); + + String replyQueueName = client.getChannel().queueDeclare().getQueue(); + + AMQP.BasicProperties props = new AMQP.BasicProperties.Builder() + .replyTo(replyQueueName) + .correlationId("1") + .build(); + Response response = client.doCall(props, "hello-world".getBytes()); + System.out.println(new String(response.getBody())); + } + + private static RpcClient newRpcClient() throws Exception { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + Connection connection = factory.newConnection(); + Channel channel = connection.createChannel(); + return new RpcClient(channel, "", "rpc_queue", "rpc_queue", 3 * 1000); + } + + private static RpcServer newRpcServer() throws Exception { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + Connection connection = factory.newConnection(); + Channel channel = connection.createChannel(); + channel.queueDeclare("rpc_queue", false, false, false, null); + channel.basicQos(1); + return new RpcServer(channel, "rpc_queue") { + public byte[] handleCall(byte[] requestBody, BasicProperties replyProperties) { + return (new String(requestBody) + "#FromServer").getBytes(); + }; + }; + } + +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main2.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main2.java new file mode 100644 index 00000000..58e69e91 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/second/Main2.java @@ -0,0 +1,71 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.second; + +import com.rabbitmq.client.AMQP.BasicProperties; +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.RpcClient; +import com.rabbitmq.client.RpcClient.Response; +import com.rabbitmq.client.RpcServer; + +public class Main2 { + + public static void main(String[] args) throws Exception { + Thread serverThread = new Thread(new Runnable() { + + @Override + public void run() { + try { + System.out.println(Thread.currentThread().getName() + ": start server"); + newRpcServer().mainloop(); + } + catch(Exception e) { + e.printStackTrace(); + } + } + }); + serverThread.start(); + System.out.println(Thread.currentThread().getName() + ": rpc server"); + + Thread.sleep(1000L); + + System.out.println(Thread.currentThread().getName() + ": rpc server after sleep"); + + RpcClient client = newRpcClient(); + + String replyQueueName = client.getChannel().queueDeclare().getQueue(); + + AMQP.BasicProperties props = new AMQP.BasicProperties.Builder() + .replyTo(replyQueueName) + .correlationId("1") + .build(); + Response response = client.doCall(props, "hello-world".getBytes()); + System.out.println(new String(response.getBody())); + } + + private static RpcClient newRpcClient() throws Exception { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + Connection connection = factory.newConnection(); + Channel channel = connection.createChannel(); + channel.exchangeDeclare("my-exchange", "direct"); + channel.queueBind("rpc_queue", "my-exchange", "rpc_queue"); + return new RpcClient(channel, "my-exchange", "rpc_queue", "rpc_queue", 3 * 1000); + } + + private static RpcServer newRpcServer() throws Exception { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + Connection connection = factory.newConnection(); + Channel channel = connection.createChannel(); + channel.queueDeclare("rpc_queue", false, false, false, null); + channel.basicQos(1); + return new RpcServer(channel, "rpc_queue") { + public byte[] handleCall(byte[] requestBody, BasicProperties replyProperties) { + return (new String(requestBody) + "#FromServer").getBytes(); + }; + }; + } + +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/Main.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/Main.java new file mode 100644 index 00000000..360e5092 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/Main.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.third; + +public class Main { + + public static void main(String[] args) throws Exception { + new Thread(new Runnable() { + + @Override + public void run() { + new RPCServer().start(); + } + }).start(); + + RPCClient fibonacciRpc = new RPCClient(); + + System.out.println(" [x] Requesting fib(30)"); + String response = fibonacciRpc.call("30"); + System.out.println(" [.] Got '" + response + "'"); + + fibonacciRpc.close(); + } + +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCClient.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCClient.java new file mode 100644 index 00000000..fa903f80 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCClient.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.third; + +import com.rabbitmq.client.*; + +import java.io.IOException; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeoutException; + +public class RPCClient { + + private Connection connection; + private Channel channel; + private String requestQueueName = "rpc_queue"; + private String replyQueueName; + + public RPCClient() throws IOException, TimeoutException { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + + connection = factory.newConnection(); + channel = connection.createChannel(); + + replyQueueName = channel.queueDeclare().getQueue(); + } + + public String call(String message) throws IOException, InterruptedException { + String corrId = UUID.randomUUID().toString(); + + AMQP.BasicProperties props = new AMQP.BasicProperties + .Builder() + .correlationId(corrId) + .replyTo(replyQueueName) + .build(); + + channel.basicPublish("", requestQueueName, props, message.getBytes("UTF-8")); + + final BlockingQueue response = new ArrayBlockingQueue(1); + + channel.basicConsume(replyQueueName, true, new DefaultConsumer(channel) { + @Override + public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { + if (properties.getCorrelationId().equals(corrId)) { + response.offer(new String(body, "UTF-8")); + } + } + }); + + return response.take(); + } + + public void close() throws IOException { + connection.close(); + } +} diff --git a/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCServer.java b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCServer.java new file mode 100644 index 00000000..b21ad5f4 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/java/com/tvd12/ezyfoxserver/rabbitmq/testing/third/RPCServer.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.rabbitmq.testing.third; + +import java.io.IOException; + +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; +import com.rabbitmq.client.Consumer; +import com.rabbitmq.client.DefaultConsumer; +import com.rabbitmq.client.Envelope; + +public class RPCServer { + + private static final String RPC_QUEUE_NAME = "rpc_queue"; + + public void start() { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + + Connection connection = null; + try { + connection = factory.newConnection(); + Channel channel = connection.createChannel(); + + channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null); + + channel.basicQos(1); + + System.out.println(" [x] Awaiting RPC requests"); + + Consumer consumer = new DefaultConsumer(channel) { + @Override + public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { + AMQP.BasicProperties replyProps = new AMQP.BasicProperties + .Builder() + .correlationId(properties.getCorrelationId()) + .build(); + + String response = ""; + + try { + String message = new String(body,"UTF-8"); + int n = Integer.parseInt(message); + + System.out.println(" [.] fib(" + message + ")"); + response += fib(n); + } + catch (RuntimeException e){ + System.out.println(" [.] " + e.toString()); + } + finally { + channel.basicPublish( "", properties.getReplyTo(), replyProps, response.getBytes("UTF-8")); + + channel.basicAck(envelope.getDeliveryTag(), false); + } + } + }; + + channel.basicConsume(RPC_QUEUE_NAME, false, consumer); + + } + catch(Exception e) { + e.printStackTrace(); + } + } + + private static int fib(int n) { + if (n == 0) return 0; + if (n == 1) return 1; + return fib(n-1) + fib(n-2); + } +} + diff --git a/ezyfox-server-rabbitmq/src/test/resources/AllTests.tng.xml b/ezyfox-server-rabbitmq/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-rabbitmq/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-security/.gitignore b/ezyfox-server-security/.gitignore new file mode 100644 index 00000000..16be8f21 --- /dev/null +++ b/ezyfox-server-security/.gitignore @@ -0,0 +1 @@ +/output/ diff --git a/ezyfox-server-security/pom.xml b/ezyfox-server-security/pom.xml index 08b465ad..14998dfd 100644 --- a/ezyfox-server-security/pom.xml +++ b/ezyfox-server-security/pom.xml @@ -6,18 +6,22 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-security - 0.0.2 + 1.0.0 ezyfox-server-security http://maven.apache.org + + 1.0.0 + + com.tvd12 ezyfox-server-io - 0.0.1 + ${ezy.io.version} diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyAsyCrypt.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyAsyCrypt.java index fdecd8fe..2eeb98b6 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyAsyCrypt.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyAsyCrypt.java @@ -1,7 +1,6 @@ package com.tvd12.ezyfoxserver.sercurity; import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; @@ -21,16 +20,21 @@ public class EzyAsyCrypt { protected KeyFactory keyFactory; @SuppressWarnings("rawtypes") - protected static final Map BYTES_CONVERTERS; + protected static final Map BYTES_CONVERTERS = defaultBytesConverters(); - static { - BYTES_CONVERTERS = defaultBytesConverters(); + protected EzyAsyCrypt(Builder builder) { + try { + init(builder); + } + catch(Exception e) { + throw new IllegalStateException("init asymmetric encryption error", e); + } } - protected EzyAsyCrypt(Builder builder) { + protected void init(Builder builder) throws Exception { this.cipher = builder.newCipher(); - this.publicKey = builder.publicKey; - this.privateKey = builder.privateKey; + this.publicKey = builder.getPublicKey(); + this.privateKey = builder.getPrivateKey(); this.keyFactory = builder.newKeyFactory(); } @@ -59,7 +63,7 @@ public byte[] encrypt(String data) throws Exception { } public byte[] decrypt(String data) throws Exception { - return decrypt(data.getBytes("UTF-8")); + return decrypt(EzyBase64.decode(data)); } public T encrypt(String data, Class outType) throws Exception { @@ -67,7 +71,7 @@ public T encrypt(String data, Class outType) throws Exception { } public T decrypt(String data, Class outType) throws Exception { - return decrypt(data.getBytes("UTF-8"), outType); + return decrypt(EzyBase64.decode(data), outType); } @SuppressWarnings("unchecked") @@ -104,7 +108,7 @@ protected PublicKey getPublicKey() throws Exception { private static Map defaultBytesConverters() { Map answer = new ConcurrentHashMap<>(); answer.put(byte[].class, (bytes) -> bytes); - answer.put(String.class, (bytes) -> EzyBase64.encode2utf8((byte[])bytes)); + answer.put(String.class, (bytes) -> EzyBase64.encode2utf((byte[])bytes)); return answer; } @@ -133,24 +137,24 @@ public B privateKey(byte[] privateKey) { return getThis(); } + protected byte[] getPublicKey() { + return publicKey; + } + + protected byte[] getPrivateKey() { + return privateKey; + } + public EzyAsyCrypt build() { return new EzyAsyCrypt(this); } - protected Cipher newCipher() { - try { - return Cipher.getInstance(algorithm); - } catch (Exception e) { - throw new IllegalArgumentException(e); - } + protected Cipher newCipher() throws Exception { + return Cipher.getInstance(algorithm); } - protected KeyFactory newKeyFactory() { - try { - return KeyFactory.getInstance(algorithm); - } catch (NoSuchAlgorithmException e) { - throw new IllegalArgumentException(e); - } + protected KeyFactory newKeyFactory() throws Exception { + return KeyFactory.getInstance(algorithm); } @SuppressWarnings("unchecked") diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyBase64.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyBase64.java index ef868279..77ae4490 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyBase64.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyBase64.java @@ -1,10 +1,10 @@ package com.tvd12.ezyfoxserver.sercurity; -import java.io.UnsupportedEncodingException; - import org.apache.commons.codec.binary.Base64; -public abstract class EzyBase64 { +import com.tvd12.ezyfoxserver.io.EzyStrings; + +public final class EzyBase64 { private EzyBase64() { } @@ -22,43 +22,23 @@ public static byte[] decode(String input) { } public static byte[] encode(String input) { - try { - return Base64.encodeBase64(input.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + return Base64.encodeBase64(EzyStrings.getUtfBytes(input)); } - public static String encodeUTF(String input) { - try { - return Base64.encodeBase64String(input.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + public static String encodeUtf(String input) { + return Base64.encodeBase64String(EzyStrings.getUtfBytes(input)); } - public static String decodeUTF(String input) { - try { - return new String(Base64.decodeBase64(input), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + public static String decodeUtf(String input) { + return EzyStrings.newUtf(Base64.decodeBase64(input)); } - public static String encode2utf8(byte[] input) { - try { - return new String(encode(input), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + public static String encode2utf(byte[] input) { + return EzyStrings.newUtf(encode(input)); } - public static String decode2utf8(byte[] input) { - try { - return new String(decode(input), "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + public static String decode2utf(byte[] input) { + return EzyStrings.newUtf(decode(input)); } } diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileAsyCrypt.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileAsyCrypt.java index 8cc0ed9c..0295bbda 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileAsyCrypt.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileAsyCrypt.java @@ -2,8 +2,8 @@ import java.io.File; -import com.tvd12.ezyfoxserver.io.EzyFileReader; -import com.tvd12.ezyfoxserver.io.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; public class EzyFileAsyCrypt extends EzyAsyCrypt { @@ -16,8 +16,6 @@ protected EzyFileAsyCrypt(Builder builder) { super(builder); this.fileReader = builder.fileReader; this.fileWriter = builder.fileWriter; - this.publicKey = builder.getPublicKey(); - this.privateKey = builder.getPrivateKey(); this.outDecryptedFile = builder.outDecryptedFile; this.outEncryptedFile = builder.outEncryptedFile; } @@ -25,14 +23,14 @@ protected EzyFileAsyCrypt(Builder builder) { @Override public byte[] encrypt(byte[] data) throws Exception { byte[] bytes = super.encrypt(data); - writeToFile(bytes, outEncryptedFile); + writeToFile(outEncryptedFile, bytes); return bytes; } @Override public byte[] decrypt(byte[] data) throws Exception { byte[] bytes = super.decrypt(data); - writeToFile(data, outDecryptedFile); + writeToFile(outDecryptedFile, bytes); return bytes; } @@ -58,9 +56,9 @@ protected byte[] readFile(File file) { return fileReader.readBytes(file); } - protected void writeToFile(byte[] data, File file) { + protected void writeToFile(File file, byte[] data) { if(file != null) - fileWriter.write(data, file); + fileWriter.write(file, data); } public static Builder builder() { @@ -76,7 +74,7 @@ public static class Builder extends EzyAsyCrypt.Builder { protected EzyFileReader fileReader; public Builder publicKeyFile(File publicKeyFile) { - this.publicKeyFile = privateKeyFile; + this.publicKeyFile = publicKeyFile; return this; } @@ -109,10 +107,12 @@ public EzyFileAsyCrypt build() { return new EzyFileAsyCrypt(this); } + @Override protected byte[] getPublicKey() { return publicKey != null ? publicKey : readPublicKeyFile(); } + @Override protected byte[] getPrivateKey() { return privateKey != null ? privateKey : readPrivateKeyFile(); } diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileKeysGenerator.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileKeysGenerator.java index c505bd65..4bf4c586 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileKeysGenerator.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyFileKeysGenerator.java @@ -6,7 +6,7 @@ import java.security.PrivateKey; import java.security.PublicKey; -import com.tvd12.ezyfoxserver.io.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; public class EzyFileKeysGenerator extends EzyKeysGenerator { @@ -30,16 +30,16 @@ public KeyPair generate() { } protected void writePublicKey(PublicKey key) { - writeKey(key, publicKeyFile); + writeKey(publicKeyFile, key); } protected void writePrivateKey(PrivateKey key) { - writeKey(key, privateKeyFile); + writeKey(privateKeyFile, key); } - protected void writeKey(Key key, File file) { + protected void writeKey(File file, Key key) { if(file != null) - fileWriter.write(key.getEncoded(), file); + fileWriter.write(file, key.getEncoded()); } public static Builder builder() { diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyKeysGenerator.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyKeysGenerator.java index 08895637..ced027a5 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyKeysGenerator.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyKeysGenerator.java @@ -6,11 +6,11 @@ public class EzyKeysGenerator { - protected int keyLength; + protected int keysize; protected String algorithm; protected EzyKeysGenerator(Builder builder) { - this.keyLength = builder.keyLength; + this.keysize = builder.keysize; this.algorithm = builder.algorithm; } @@ -19,7 +19,7 @@ public KeyPair generate() { } protected KeyPair generate(KeyPairGenerator generator) { - generator.initialize(keyLength); + generator.initialize(keysize); return generator.generateKeyPair(); } @@ -31,16 +31,17 @@ protected KeyPairGenerator newKeyPairGenerator() { } } - public static Builder builder() { + @SuppressWarnings("rawtypes") + public static Builder builder() { return new Builder<>(); } public static class Builder> { - protected int keyLength; - protected String algorithm; + protected int keysize = 512; + protected String algorithm = "RSA"; - public B keyLength(int keyLength) { - this.keyLength = keyLength; + public B keysize(int keysize) { + this.keysize = keysize; return getThis(); } public B algorithm(String algorithm) { diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyMD5.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyMD5.java index 1e0d2679..6741f409 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyMD5.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyMD5.java @@ -1,20 +1,20 @@ package com.tvd12.ezyfoxserver.sercurity; -import java.io.UnsupportedEncodingException; - import org.apache.commons.codec.digest.Md5Crypt; -public abstract class EzyMD5 { +import com.tvd12.ezyfoxserver.io.EzyStrings; + +public final class EzyMD5 { private EzyMD5() { } - public static String cryptUTF(final String input) { - try { - return Md5Crypt.md5Crypt(input.getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e); - } + public static String cryptUtf(String input) { + return cryptUtf(input, "$1$ezyfox-server"); + } + + public static String cryptUtf(String input, String salt) { + return Md5Crypt.md5Crypt(EzyStrings.getUtfBytes(input), salt); } } diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyUuid.java b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyUuid.java index ab22ce90..d16a07b6 100644 --- a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyUuid.java +++ b/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/sercurity/EzyUuid.java @@ -2,7 +2,7 @@ import java.util.UUID; -public abstract class EzyUuid { +public final class EzyUuid { private EzyUuid() { } diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/AsyCryptTesting.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/AsyCryptTesting.java deleted file mode 100644 index c00a7720..00000000 --- a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/AsyCryptTesting.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.tvd12.ezyfoxserver.sercurity; - -import java.security.KeyPair; - -import org.testng.annotations.Test; - -import com.tvd12.test.base.BaseTest; - -public class AsyCryptTesting extends BaseTest { - - @Test - public void test() throws Exception { - EzyKeysGenerator keysGenerator = EzyKeysGenerator.builder() - .algorithm("RSA") - .keyLength(512) - .build(); - KeyPair keyPair = keysGenerator.generate(); - - EzyAsyCrypt asyCrypt = EzyAsyCrypt.builder() - .algorithm("RSA") - .privateKey(keyPair.getPrivate().getEncoded()) - .publicKey(keyPair.getPublic().getEncoded()) - .build(); - - String text = "i'm dzung"; - String encryptedText = asyCrypt.encrypt(text, String.class); - - System.out.println("encryptedText = " + encryptedText); - - String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); - - System.out.println("decryptedText = " + decryptedText); - - } - -} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/FileAsyCryptTesting.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/FileAsyCryptTesting.java deleted file mode 100644 index aa67dc24..00000000 --- a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/sercurity/FileAsyCryptTesting.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.tvd12.ezyfoxserver.sercurity; - -import java.io.File; -import java.security.KeyPair; - -import org.testng.annotations.Test; - -import com.tvd12.ezyfoxserver.io.EzySimpleFileWriter; -import com.tvd12.test.base.BaseTest; - -public class FileAsyCryptTesting extends BaseTest { - - @Test - public void test() throws Exception { - EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() - .algorithm("RSA") - .keyLength(512) - .publicKeyFile(new File("output/publickey.txt")) - .privateKeyFile(new File("output/privatekey.txt")) - .fileWriter(new EzySimpleFileWriter()) - .build(); - KeyPair keyPair = keysGenerator.generate(); - - EzyAsyCrypt asyCrypt = EzyAsyCrypt.builder() - .algorithm("RSA") - .privateKey(keyPair.getPrivate().getEncoded()) - .publicKey(keyPair.getPublic().getEncoded()) - .build(); - - String text = "i'm dzung"; - String encryptedText = asyCrypt.encrypt(text, String.class); - - System.out.println("encryptedText = " + encryptedText); - - String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); - - System.out.println("decryptedText = " + decryptedText); - - } - -} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt2Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt2Testing.java new file mode 100644 index 00000000..9cddcb6d --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt2Testing.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.sercurity.EzyAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyAsyCrypt2Testing extends BaseTest { + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + KeyPair keyPair = keysGenerator.generate(); + + EzyAsyCrypt asyCrypt = EzyAsyCrypt.builder() + .algorithm("RSA") + .privateKey(keyPair.getPrivate().getEncoded()) + .publicKey(keyPair.getPublic().getEncoded()) + .build(); + + String text = "i'm dzung"; + byte[] encrypt = asyCrypt.encrypt(text); + assertEquals(asyCrypt.decrypt(encrypt), EzyStrings.getUtfBytes("i'm dzung")); + + String encrypt2 = asyCrypt.encrypt(text, String.class); + assertEquals(asyCrypt.decrypt(encrypt2, String.class), + EzyBase64.encodeUtf("i'm dzung")); + assertEquals(asyCrypt.decrypt(encrypt2), EzyStrings.getUtfBytes(text)); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test2() { + + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + + EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + + KeyPair keyPair = keysGenerator.generate(); + + EzyAsyCrypt.builder() + .algorithm("fafafsdfsa") + .privateKey(keyPair.getPrivate().getEncoded()) + .publicKey(keyPair.getPublic().getEncoded()) + .build(); + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt3Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt3Testing.java new file mode 100644 index 00000000..4a3ad899 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCrypt3Testing.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyAsyCrypt3Testing extends BaseTest { + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + KeyPair keyPair = keysGenerator.generate(); + + EzyAsyCrypt asyCrypt = EzyAsyCrypt.builder() + .algorithm("RSA") + .privateKey(keyPair.getPrivate().getEncoded()) + .publicKey(keyPair.getPublic().getEncoded()) + .build(); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCryptTesting.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCryptTesting.java new file mode 100644 index 00000000..dc0801db --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyAsyCryptTesting.java @@ -0,0 +1,44 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.io.File; +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyAsyCryptTesting extends BaseTest { + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + KeyPair keyPair = keysGenerator.generate(); + + EzyAsyCrypt asyCrypt = EzyAsyCrypt.builder() + .algorithm("RSA") + .privateKey(keyPair.getPrivate().getEncoded()) + .publicKey(keyPair.getPublic().getEncoded()) + .build(); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyBase64Test.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyBase64Test.java new file mode 100644 index 00000000..bceb49dd --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyBase64Test.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzyBase64Test extends BaseTest { + + @Override + public Class getTestClass() { + return EzyBase64.class; + } + + @Test + public void test() { + byte[] encode = EzyBase64.encode("dungtv"); + assertEquals(EzyBase64.decode(encode), EzyStrings.getUtfBytes("dungtv")); + assertEquals(EzyBase64.decode2utf(encode), "dungtv"); + + String encodeUtf = EzyBase64.encodeUtf("dungtv"); + assertEquals(EzyBase64.decodeUtf(encodeUtf), "dungtv"); + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt2Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt2Testing.java new file mode 100644 index 00000000..b4940c16 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt2Testing.java @@ -0,0 +1,62 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.io.File; +import java.security.KeyPair; +import java.util.Arrays; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzyFileAsyCrypt2Testing extends BaseTest { + + private EzyFileReader fileReader = EzySimpleFileReader.builder().build(); + private EzyFileWriter fileWriter = EzySimpleFileWriter.builder().build(); + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(fileWriter) + .build(); + keysGenerator.generate(); + KeyPair keyPair = keysGenerator.generate(); + + System.err.println(Arrays.toString(keyPair.getPublic().getEncoded())); + + EzyFileAsyCrypt asyCrypt = EzyFileAsyCrypt.builder() + .algorithm("RSA") + .privateKeyFile(new File("output/privatekey.txt")) + .publicKeyFile(new File("output/publickey.txt")) + .fileReader(fileReader) + .fileWriter(fileWriter) + .build(); + + assertEquals(keyPair.getPublic().getEncoded(), + fileReader.readBytes(new File("output/publickey.txt"))); + assertEquals(keyPair.getPrivate().getEncoded(), + fileReader.readBytes(new File("output/privatekey.txt"))); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt3Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt3Testing.java new file mode 100644 index 00000000..9cb9267f --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt3Testing.java @@ -0,0 +1,74 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.io.File; +import java.security.KeyPair; +import java.util.Arrays; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzyFileAsyCrypt3Testing extends BaseTest { + + private EzyFileReader fileReader = EzySimpleFileReader.builder().build(); + private EzyFileWriter fileWriter = EzySimpleFileWriter.builder().build(); + + private File outEncryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outEncryptedFile.txt"); + private File outDecryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outDecryptedFile.txt"); + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(fileWriter) + .build(); + keysGenerator.generate(); + KeyPair keyPair = keysGenerator.generate(); + + System.err.println(Arrays.toString(keyPair.getPublic().getEncoded())); + + EzyFileAsyCrypt asyCrypt = EzyFileAsyCrypt.builder() + .algorithm("RSA") + .privateKeyFile(new File("output/privatekey.txt")) + .publicKeyFile(new File("output/publickey.txt")) + .fileReader(fileReader) + .fileWriter(fileWriter) + .outDecryptedFile(outDecryptedFile) + .outEncryptedFile(outEncryptedFile) + .build(); + + assertEquals(keyPair.getPublic().getEncoded(), + fileReader.readBytes(new File("output/publickey.txt"))); + assertEquals(keyPair.getPrivate().getEncoded(), + fileReader.readBytes(new File("output/privatekey.txt"))); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + byte[] encrypt = asyCrypt.encrypt(EzyStrings.getUtfBytes("dungtv")); + String decrypt = asyCrypt.decrypt(encrypt, String.class); + assert decrypt.equals(EzyBase64.encodeUtf("dungtv")); + + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt4Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt4Testing.java new file mode 100644 index 00000000..4103a2c5 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt4Testing.java @@ -0,0 +1,90 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.security.KeyPair; +import java.util.Arrays; + +import org.apache.commons.io.FileUtils; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyFileAsyCrypt4Testing extends BaseTest { + + private EzyFileReader fileReader = EzySimpleFileReader.builder().build(); + private EzyFileWriter fileWriter = EzySimpleFileWriter.builder().build(); + + private File fileInput + = new File("output/EzyFileAsyCrypt3Testing_fileInput.txt"); + + private File outEncryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outEncryptedFile.txt"); + private File outDecryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outDecryptedFile.txt"); + + public EzyFileAsyCrypt4Testing() throws IOException { + super(); + FileUtils.forceMkdirParent(fileInput); + fileWriter.write(fileInput, new String("dungtv").getBytes("UTF-8")); + } + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(fileWriter) + .build(); + keysGenerator.generate(); + KeyPair keyPair = keysGenerator.generate(); + + System.err.println(Arrays.toString(keyPair.getPublic().getEncoded())); + + EzyFileAsyCrypt asyCrypt = EzyFileAsyCrypt.builder() + .algorithm("RSA") + .privateKeyFile(new File("output/privatekey.txt")) + .publicKeyFile(new File("output/publickey.txt")) + .fileReader(fileReader) + .fileWriter(fileWriter) + .outDecryptedFile(outDecryptedFile) + .outEncryptedFile(outEncryptedFile) + .build(); + + assertEquals(keyPair.getPublic().getEncoded(), + fileReader.readBytes(new File("output/publickey.txt"))); + assertEquals(keyPair.getPrivate().getEncoded(), + fileReader.readBytes(new File("output/privatekey.txt"))); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + byte[] encrypt = asyCrypt.encrypt(fileInput); + assertEquals(encrypt, fileReader.readBytes(outEncryptedFile)); + System.err.println("before: " + Arrays.toString(fileReader.readBytes(outDecryptedFile))); + byte[] decrypt = asyCrypt.decrypt(outEncryptedFile, byte[].class); + System.err.println("decrypt: " + Arrays.toString(decrypt)); + System.err.println("after: " + Arrays.toString(fileReader.readBytes(outDecryptedFile))); + assertEquals(decrypt, fileReader.readBytes(outDecryptedFile)); + String string = asyCrypt.decrypt(outEncryptedFile, String.class); + assert string.equals(EzyBase64.encodeUtf("dungtv")); + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt5Testing.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt5Testing.java new file mode 100644 index 00000000..c3fea1b5 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCrypt5Testing.java @@ -0,0 +1,87 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import static org.testng.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.security.KeyPair; +import java.util.Arrays; + +import org.apache.commons.io.FileUtils; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyFileAsyCrypt5Testing extends BaseTest { + + private EzyFileReader fileReader = EzySimpleFileReader.builder().build(); + private EzyFileWriter fileWriter = EzySimpleFileWriter.builder().build(); + + private File fileInput + = new File("output/EzyFileAsyCrypt3Testing_fileInput.txt"); + + private File outEncryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outEncryptedFile.txt"); + private File outDecryptedFile + = new File("output/EzyFileAsyCrypt3Testing_outDecryptedFile.txt"); + + public EzyFileAsyCrypt5Testing() throws IOException { + super(); + FileUtils.forceMkdirParent(fileInput); + fileWriter.write(fileInput, new String("dungtv").getBytes("UTF-8")); + } + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(fileWriter) + .build(); + keysGenerator.generate(); + KeyPair keyPair = keysGenerator.generate(); + + System.err.println(Arrays.toString(keyPair.getPublic().getEncoded())); + + EzyFileAsyCrypt asyCrypt = EzyFileAsyCrypt.builder() + .algorithm("RSA") + .privateKeyFile(new File("output/privatekey.txt")) + .publicKeyFile(new File("output/publickey.txt")) + .fileReader(fileReader) + .fileWriter(fileWriter) + .outDecryptedFile(outDecryptedFile) + .outEncryptedFile(outEncryptedFile) + .build(); + + assertEquals(keyPair.getPublic().getEncoded(), + fileReader.readBytes(new File("output/publickey.txt"))); + assertEquals(keyPair.getPrivate().getEncoded(), + fileReader.readBytes(new File("output/privatekey.txt"))); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + byte[] encrypt = asyCrypt.encrypt(fileInput, byte[].class); + assertEquals(encrypt, fileReader.readBytes(outEncryptedFile)); + byte[] decrypt = asyCrypt.decrypt(outEncryptedFile, byte[].class); + assertEquals(decrypt, fileReader.readBytes(outDecryptedFile)); + String string = asyCrypt.decrypt(outEncryptedFile, String.class); + assert string.equals(EzyBase64.encodeUtf("dungtv")); + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCryptTesting.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCryptTesting.java new file mode 100644 index 00000000..4ce07d61 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyFileAsyCryptTesting.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.io.File; +import java.security.KeyPair; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.file.EzyFileReader; +import com.tvd12.ezyfoxserver.file.EzyFileWriter; +import com.tvd12.ezyfoxserver.file.EzySimpleFileReader; +import com.tvd12.ezyfoxserver.file.EzySimpleFileWriter; +import com.tvd12.ezyfoxserver.sercurity.EzyBase64; +import com.tvd12.ezyfoxserver.sercurity.EzyFileAsyCrypt; +import com.tvd12.ezyfoxserver.sercurity.EzyFileKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyFileAsyCryptTesting extends BaseTest { + + private EzyFileReader fileReader = EzySimpleFileReader.builder().build(); + private EzyFileWriter fileWriter = EzySimpleFileWriter.builder().build(); + + @Test + public void test() throws Exception { + EzyFileKeysGenerator keysGenerator = EzyFileKeysGenerator.builder() + .algorithm("RSA") + .keysize(512) + .publicKeyFile(new File("output/publickey.txt")) + .privateKeyFile(new File("output/privatekey.txt")) + .fileWriter(EzySimpleFileWriter.builder().build()) + .build(); + KeyPair keyPair = keysGenerator.generate(); + + EzyFileAsyCrypt asyCrypt = EzyFileAsyCrypt.builder() + .algorithm("RSA") + .privateKey(keyPair.getPrivate().getEncoded()) + .publicKey(keyPair.getPublic().getEncoded()) + .fileReader(fileReader) + .fileWriter(fileWriter) + .build(); + + String text = "i'm dzung"; + String encryptedText = asyCrypt.encrypt(text, String.class); + + System.out.println("encryptedText = " + encryptedText); + + String decryptedText = asyCrypt.decrypt(EzyBase64.decode(encryptedText), String.class); + + System.out.println("decryptedText = " + decryptedText); + + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyKeysGeneratorTest.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyKeysGeneratorTest.java new file mode 100644 index 00000000..870104f9 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyKeysGeneratorTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.sercurity.EzyKeysGenerator; +import com.tvd12.test.base.BaseTest; + +public class EzyKeysGeneratorTest extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test() { + EzyKeysGenerator.builder() + .algorithm("fasdfasdf") + .keysize(512) + .build() + .generate(); + } + +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyMD5Test.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyMD5Test.java new file mode 100644 index 00000000..759ee3e6 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyMD5Test.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import java.io.UnsupportedEncodingException; +import java.util.Random; + +import org.apache.commons.codec.digest.Md5Crypt; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.ezyfoxserver.sercurity.EzyMD5; +import com.tvd12.test.base.BaseTest; + +public class EzyMD5Test extends BaseTest { + + static final String B64T = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + @Override + public Class getTestClass() { + return EzyMD5.class; + } + + @Test + public void test() throws UnsupportedEncodingException { + String salt = "$1$" + B64.getRandomSalt(8); + System.out.println(salt); + System.out.println("a: " + EzyMD5.cryptUtf("dungtv")); + System.out.println("b: " + Md5Crypt.md5Crypt(EzyStrings.getUtfBytes("dungtv"))); + assert EzyMD5.cryptUtf("dungtv", salt).equals(Md5Crypt.md5Crypt(EzyStrings.getUtfBytes("dungtv"), salt)); + } + + public static class B64 { + static String getRandomSalt(int num) { + StringBuilder saltString = new StringBuilder(); + for (int i = 1; i <= num; i++) + saltString.append(B64T.charAt(new Random().nextInt(B64T.length()))); + return saltString.toString(); + } + } +} diff --git a/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyUuidTest.java b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyUuidTest.java new file mode 100644 index 00000000..b4fc1fa1 --- /dev/null +++ b/ezyfox-server-security/src/test/java/com/tvd12/ezyfoxserver/testing/sercurity/EzyUuidTest.java @@ -0,0 +1,20 @@ +package com.tvd12.ezyfoxserver.testing.sercurity; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.sercurity.EzyUuid; +import com.tvd12.test.base.BaseTest; + +public class EzyUuidTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyUuid.class; + } + + @Test + public void test() { + assert !EzyUuid.random().equals(EzyUuid.random()); + } + +} diff --git a/ezyfox-server-security/src/test/resources/AllTests.tng.xml b/ezyfox-server-security/src/test/resources/AllTests.tng.xml index 79020755..578e7ac7 100644 --- a/ezyfox-server-security/src/test/resources/AllTests.tng.xml +++ b/ezyfox-server-security/src/test/resources/AllTests.tng.xml @@ -1,9 +1,9 @@ - + - + \ No newline at end of file diff --git a/ezyfox-server-sfs2x/pom.xml b/ezyfox-server-sfs2x/pom.xml index e16b1a59..92b1d89c 100644 --- a/ezyfox-server-sfs2x/pom.xml +++ b/ezyfox-server-sfs2x/pom.xml @@ -6,7 +6,7 @@ com.tvd12 ezyfox-server - 0.0.1 + 0.0.2 ezyfox-server-sfs2x 1.0.0 @@ -14,20 +14,20 @@ http://maven.apache.org - 1.0.0 - 1.0.0 + 1.0.0 + 1.0.0 com.tvd12 ezyfox-server-common - ${common.version} + ${ezy.common.version} com.tvd12 ezyfox-server-codec - ${codec.version} + ${ezy.codec.version} diff --git a/ezyfox-server-sfs2x/src/main/java/com/tvd12/ezyfoxserver/codec/SFSDataSimpleSerializer.java b/ezyfox-server-sfs2x/src/main/java/com/tvd12/ezyfoxserver/codec/SFSDataSimpleSerializer.java index bc653544..0d3658d4 100644 --- a/ezyfox-server-sfs2x/src/main/java/com/tvd12/ezyfoxserver/codec/SFSDataSimpleSerializer.java +++ b/ezyfox-server-sfs2x/src/main/java/com/tvd12/ezyfoxserver/codec/SFSDataSimpleSerializer.java @@ -58,11 +58,11 @@ protected byte[] parseShort(Short value) { } protected byte[] parseString(String value) { - return toBytes(SFSDataType.STRING, EzyStrings.getUTFBytes(value)); + return toBytes(SFSDataType.STRING, EzyStrings.getUtfBytes(value)); } protected byte[] parseText(String value) { - return toBytes(SFSDataType.TEXT, EzyStrings.getUTFBytes(value)); + return toBytes(SFSDataType.TEXT, EzyStrings.getUtfBytes(value)); } protected byte toByte(SFSDataType type) { diff --git a/ezyfox-server-sfs2x/src/test/resources/AllTests.tng.xml b/ezyfox-server-sfs2x/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..578e7ac7 --- /dev/null +++ b/ezyfox-server-sfs2x/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-util/.gitignore b/ezyfox-server-util/.gitignore new file mode 100644 index 00000000..0d69f59f --- /dev/null +++ b/ezyfox-server-util/.gitignore @@ -0,0 +1 @@ +/util-directories-test/ diff --git a/ezyfox-server-util/assembly.xml b/ezyfox-server-util/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-util/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-util/pom.xml b/ezyfox-server-util/pom.xml new file mode 100644 index 00000000..d28570d0 --- /dev/null +++ b/ezyfox-server-util/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + ezyfox-server-util + 1.0.0 + ezyfox-server-util + http://maven.apache.org + diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyAutoImpl.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyAutoImpl.java new file mode 100644 index 00000000..8256e9f0 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyAutoImpl.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ ElementType.TYPE }) +public @interface EzyAutoImpl { + + String value() default ""; + + EzyKeyValue[] properties() default {}; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyKeyValue.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyKeyValue.java new file mode 100644 index 00000000..225d188d --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyKeyValue.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Documented +@Retention(RetentionPolicy.RUNTIME) +public @interface EzyKeyValue { + + String key(); + + String value(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyProperty.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyProperty.java new file mode 100644 index 00000000..3e1b5d9c --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/annotation/EzyProperty.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Documented +@Target({ + ElementType.FIELD, + ElementType.METHOD +}) +@Retention(RetentionPolicy.RUNTIME) +public @interface EzyProperty { + + String value() default ""; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyFunction.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyFunction.java new file mode 100644 index 00000000..4553b777 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyFunction.java @@ -0,0 +1,68 @@ +package com.tvd12.ezyfoxserver.asm; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.reflect.EzyMethod; + +public class EzyFunction { + + protected final EzyMethod method; + protected final EzyBody body; + protected String modifier = "public"; + + public EzyFunction(Method method) { + this(new EzyMethod(method)); + } + + public EzyFunction(EzyMethod method) { + this.method = method; + this.body = new EzyBody(this); + } + + public EzyFunction modifier(String modifier) { + this.modifier = modifier; + return this; + } + + public EzyBody body() { + return body; + } + + @Override + public String toString() { + return new StringBuilder() + .append(method.getDeclaration(modifier)) + .append(" {\n") + .append(body) + .append("}") + .toString(); + } + + public static class EzyBody { + protected EzyFunction function; + protected List instructions = new ArrayList<>(); + + public EzyBody(EzyFunction function) { + this.function = function; + } + + public EzyBody append(EzyInstruction instruction) { + this.instructions.add(instruction); + return this; + } + + public EzyFunction function() { + return function; + } + + @Override + public String toString() { + return StringUtils.join(instructions, ""); + } + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyInstruction.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyInstruction.java new file mode 100644 index 00000000..e1697d35 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/asm/EzyInstruction.java @@ -0,0 +1,147 @@ +package com.tvd12.ezyfoxserver.asm; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.reflect.EzyTypes; + +public class EzyInstruction { + + protected final String end; + protected final boolean semicolon; + protected final StringBuilder builder = new StringBuilder(); + + @SuppressWarnings("rawtypes") + protected static final Map PRIMITIVE_WRAPPER_TYPES = + EzyTypes.PRIMITIVE_WRAPPER_TYPES_MAP; + + public EzyInstruction() { + this(""); + } + + public EzyInstruction(String begin) { + this(begin, ""); + } + + public EzyInstruction(String begin, String end) { + this(begin, end, true); + } + + public EzyInstruction(String begin, String end, boolean semicolon) { + this.end = end; + this.builder.append(begin); + this.semicolon = semicolon; + } + + public EzyInstruction equal() { + builder.append(" = "); + return this; + } + + public EzyInstruction finish() { + builder.append(";"); + return this; + } + + @SuppressWarnings("rawtypes") + public EzyInstruction constructor(Class clazz) { + return clazz(clazz).append("()"); + } + + public EzyInstruction append(Object value) { + builder.append(value.toString()); + return this; + } + + public EzyInstruction append(String str) { + builder.append(str); + return this; + } + + public EzyInstruction string(String str) { + builder.append("\"").append(str).append("\""); + return this; + } + + @SuppressWarnings("rawtypes") + public EzyInstruction clazz(Class clazz) { + return clazz(clazz, false); + } + + @SuppressWarnings("rawtypes") + public EzyInstruction clazz(Class clazz, boolean extension) { + append(clazz.getTypeName()); + return extension ? append(".class") : this; + } + + public EzyInstruction dot() { + return append("."); + } + + public EzyInstruction comma() { + return append(", "); + } + + public EzyInstruction bracketopen() { + return append("("); + } + + public EzyInstruction bracketclose() { + return append(")"); + } + + @SuppressWarnings("rawtypes") + public EzyInstruction brackets(Class clazz) { + builder.append("(").append(clazz.getTypeName()).append(")"); + return this; + } + + public EzyInstruction brackets(String expression) { + builder.append("(").append(expression).append(")"); + return this; + } + + public EzyInstruction answer() { + return append("return "); + } + + @SuppressWarnings("rawtypes") + public EzyInstruction variable(Class type) { + return variable(type, EzyClasses.getVariableName(type)); + } + + @SuppressWarnings("rawtypes") + public EzyInstruction variable(Class type, String name) { + builder.append(type.getTypeName()).append(" ").append(name); + return this; + } + + @SuppressWarnings("rawtypes") + public EzyInstruction cast(Class type, String expression) { + builder + .append("(") + .append("(").append(type.getTypeName()).append(")") + .append("(").append(expression).append(")") + .append(")"); + return this; + } + + @SuppressWarnings("rawtypes") + public EzyInstruction valueOf(Class type, String expression) { + if(PRIMITIVE_WRAPPER_TYPES.containsKey(type)) + return clazz(PRIMITIVE_WRAPPER_TYPES.get(type)).append(".valueOf").brackets(expression); + return append(expression); + } + + @Override + public String toString() { + return toString(true); + } + + public String toString(boolean autoFinish) { + String string = builder.toString(); + if(autoFinish && semicolon) + string = string.endsWith(";") ? string : string + ";"; + return string + end; + } +} \ No newline at end of file diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java similarity index 75% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java index c4d71e7f..82d046d2 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/builder/EzyBuilder.java @@ -5,7 +5,7 @@ public interface EzyBuilder { /** * build project * - * @return the constructed the product + * @return the constructed product */ T build(); diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/callback/EzyCallback.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/callback/EzyCallback.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/callback/EzyCallback.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/callback/EzyCallback.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyAttribute.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyAttribute.java new file mode 100644 index 00000000..55bbe891 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyAttribute.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.constant; + +import java.util.concurrent.atomic.AtomicInteger; + +import lombok.Getter; + +@Getter +public class EzyAttribute implements EzyConstant { + + protected int id; + protected String name; + + private static final AtomicInteger COUNTER = new AtomicInteger(0); + + public EzyAttribute() { + this(COUNTER.incrementAndGet()); + } + + public EzyAttribute(int id) { + this(id, "attribute#" + id); + } + + public EzyAttribute(String name) { + this(COUNTER.incrementAndGet(), name); + } + + public EzyAttribute(int id, String name) { + this.id = id; + this.name = name; + COUNTER.incrementAndGet(); + } + + public static EzyAttribute one() { + return new EzyAttribute<>(); + } + + public static EzyAttribute valueOf(int id) { + return new EzyAttribute<>(id); + } + + public static EzyAttribute valueOf(String name) { + return new EzyAttribute<>(name); + } + + public static EzyAttribute valueOf(int id, String name) { + return new EzyAttribute<>(id, name); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java new file mode 100644 index 00000000..08e7afc6 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyConstant.java @@ -0,0 +1,79 @@ +package com.tvd12.ezyfoxserver.constant; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.lang3.StringUtils; + +public interface EzyConstant extends EzyHasId, EzyHasName { + + // the counter utility + AtomicInteger COUNTER = new AtomicInteger(0); + + /** + * Get constant name + * + * @return the constant name + */ + default String getName() { + String name = getClass().getSimpleName().trim(); + name = StringUtils.isEmpty(name) ? "attribute" : name; + return name + "#" + getId(); + } + + /** + * Create new constant + * + * @return a constant + */ + static EzyConstant one() { + return one(COUNTER.incrementAndGet()); + } + + /** + * Create new constant + * + * @return a constant + */ + static EzyConstant one(String name) { + return one(COUNTER.incrementAndGet(), name); + } + + /** + * Create new constant with id + * + * @param id the constant id + * @return a constant + */ + static EzyConstant one(int id) { + COUNTER.incrementAndGet(); + return new EzyConstant() { + @Override + public int getId() { + return id; + } + }; + }; + + /** + * Create new constant with id + * + * @param id the constant id + * @param name the constant name + * @return a constant + */ + static EzyConstant one(int id, String name) { + COUNTER.incrementAndGet(); + return new EzyConstant() { + @Override + public int getId() { + return id; + } + + @Override + public String getName() { + return name; + } + }; + }; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java new file mode 100644 index 00000000..c8c12553 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyError.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyError { + + int getCode(); + + String getMessage(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasAttribute.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasAttribute.java new file mode 100644 index 00000000..6db44ad4 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasAttribute.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyHasAttribute { + + T getAttribute(EzyAttribute attr); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasId.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasId.java new file mode 100644 index 00000000..708f9c7a --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasId.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyHasId { + + int getId(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasName.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasName.java new file mode 100644 index 00000000..8391c64d --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/constant/EzyHasName.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.constant; + +public interface EzyHasName { + + String getName(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNegativeValueException.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNegativeValueException.java new file mode 100644 index 00000000..c871c728 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/exception/EzyNegativeValueException.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.exception; + +public class EzyNegativeValueException extends IllegalArgumentException { + private static final long serialVersionUID = 3934085408440316839L; + + public EzyNegativeValueException(Number value) { + super("negative value: " + value + " is not acceptable"); + } +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyApply.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyApply.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyApply.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyApply.java diff --git a/ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/function/EzyBytesFunction.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyBytesFunction.java similarity index 100% rename from ezyfox-server-security/src/main/java/com/tvd12/ezyfoxserver/function/EzyBytesFunction.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyBytesFunction.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyCastIntToByte.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyCastIntToByte.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyCastIntToByte.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyCastIntToByte.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyCreation.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyCreation.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyCreation.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyCreation.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java new file mode 100644 index 00000000..61d8db25 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyDeserializer.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyDeserializer { + + O deserialize(I input); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionApply.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionApply.java new file mode 100644 index 00000000..594cf513 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionApply.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyExceptionApply { + + void apply(T t) throws Exception; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionFunction.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionFunction.java new file mode 100644 index 00000000..5f881f34 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionFunction.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyExceptionFunction { + + R apply(T t) throws Exception; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionVoid.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionVoid.java new file mode 100644 index 00000000..3cafb0a5 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyExceptionVoid.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyExceptionVoid { + + void apply() throws Exception; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyHandler.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyHandler.java new file mode 100644 index 00000000..e62ab731 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyHandler.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyHandler { + + void handle(); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyInitialize.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyInitialize.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyInitialize.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyInitialize.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyLoader.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyLoader.java new file mode 100644 index 00000000..8ccfa323 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyLoader.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyLoader { + + R load(T t); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyNewArray.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyNewArray.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyNewArray.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyNewArray.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java new file mode 100644 index 00000000..561efb86 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyNumber.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.function; + +import java.util.function.Function; + +public interface EzyNumber extends Function { +} diff --git a/ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzyParser.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyParser.java similarity index 100% rename from ezyfox-server-codec/src/main/java/com/tvd12/ezyfoxserver/function/EzyParser.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyParser.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java new file mode 100644 index 00000000..bef00980 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySerializer.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzySerializer { + + O serialize(I input); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySupplier.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySupplier.java new file mode 100644 index 00000000..8f8e1f3d --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzySupplier.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzySupplier { + + T get() throws Exception; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyTemplate.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyTemplate.java new file mode 100644 index 00000000..e4067242 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyTemplate.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyTemplate + extends EzySerializer, EzyDeserializer { + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyToObject.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyToObject.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyToObject.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyToObject.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyTransform.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyTransform.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/function/EzyTransform.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyTransform.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyValidator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyValidator.java new file mode 100644 index 00000000..bc1fca96 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyValidator.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyValidator { + + boolean validate(T value); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyVoid.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyVoid.java new file mode 100644 index 00000000..8f6432d5 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/function/EzyVoid.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.function; + +public interface EzyVoid { + + void apply(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java new file mode 100644 index 00000000..857a3199 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/helper/EzyLazyInitHelper.java @@ -0,0 +1,46 @@ +package com.tvd12.ezyfoxserver.helper; + +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.function.EzyInitialize; +import com.tvd12.ezyfoxserver.function.EzyVoid; + +public final class EzyLazyInitHelper { + + private EzyLazyInitHelper() { + } + + public static T init( + Object context, EzyInitialize initer) { + return init(context, () -> null, initer); + } + + public static T init( + Object context, Supplier current, EzyInitialize initer) { + T value = current.get(); + return value != null ? value : syncInit(context, current, initer); + } + + private static T syncInit( + Object context, Supplier current, EzyInitialize initer) { + synchronized (context) { + T value = current.get(); + return value != null ? value : initer.init(); + } + } + + public static void voidInit( + Object context, Supplier condition, EzyVoid applier) { + if(condition.get()) + syncVoidInit(context, condition, applier); + } + + private static void syncVoidInit( + Object context, Supplier condition, EzyVoid applier) { + synchronized (context) { + if(condition.get()) + applier.apply(); + } + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java new file mode 100644 index 00000000..4b0fab37 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyArrays.java @@ -0,0 +1,63 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.stream.Stream; + +public final class EzyArrays { + + private EzyArrays() { + } + + public static void copy(byte[] from, byte[] to, int toPos) { + for(int i = 0 ; i < from.length ; i++) + to[toPos + i] = from[i]; + } + + public static byte[] merge(byte first, byte[] other) { + byte[] bytes = new byte[other.length + 1]; + bytes[0] = first; + for(int i = 0 ; i < other.length ; i++) + bytes[i + 1] = other[i]; + return bytes; + } + + public static O[] newArray(Collection coll, + IntFunction generator, Function applier) { + int count = 0; + O[] answer = generator.apply(coll.size()); + for(I input : coll) + answer[count ++] = applier.apply(input); + return answer; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static T min(T[] array) { + return min(array, (a, b) -> a.compareTo(b)); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static T max(T[] array) { + return max(array, (a, b) -> a.compareTo(b)); + } + + public static T min(T[] array, Comparator comparator) { + return min(Arrays.stream(array), comparator); + } + + public static T max(T[] array, Comparator comparator) { + return max(Arrays.stream(array), comparator); + } + + public static T min(Stream stream, Comparator comparator) { + return stream.min(comparator).get(); + } + + public static T max(Stream stream, Comparator comparator) { + return stream.max(comparator).get(); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java similarity index 80% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java index 363ccab3..a4d33e95 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyByteBuffers.java @@ -2,12 +2,14 @@ import java.nio.ByteBuffer; -public abstract class EzyByteBuffers { +public final class EzyByteBuffers { private EzyByteBuffers() { } public static byte[] getBytes(ByteBuffer buffer) { + if(!buffer.hasRemaining()) + buffer.flip(); return getBytes(buffer, buffer.remaining()); } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java similarity index 90% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java index 31aa361f..9d8d3be6 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyBytes.java @@ -2,9 +2,13 @@ import java.nio.ByteBuffer; -public abstract class EzyBytes { +public final class EzyBytes { - protected EzyBytes() { + private EzyBytes() { + } + + public static byte[] getBytes(ByteBuffer buffer) { + return EzyByteBuffers.getBytes(buffer); } public static byte[] copy(ByteBuffer buffer, int size) { @@ -79,9 +83,4 @@ public static byte[] getBytes(long value, int size) { return bytes; } - public static void main(String[] args) { - byte[] bytes = EzyBytes.getBytes(0x3c, -1, 3); - System.out.println(EzyPrints.printBits(bytes)); - } - } diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollections.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollections.java new file mode 100644 index 00000000..92f47167 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyCollections.java @@ -0,0 +1,80 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Collection; +import java.util.function.Function; +import java.util.function.IntFunction; +import java.util.function.Predicate; +import java.util.stream.IntStream; + +public final class EzyCollections { + + private EzyCollections() { + } + + public static boolean isEmpty(Collection coll) { + return coll != null ? coll.isEmpty() : true; + } + + /** + * Returns an array containing all of the elements in the collection + * + * @param coll the collection + * @param applier the applier + * @return the new array + */ + public static T[] toArray(Collection coll, IntFunction applier) { + return coll.toArray(applier.apply(coll.size())); + } + + /** + * + * Check whether collection no.1 contains any item of collection no.2 + * + * @param c1 the collection no.1 + * @param c2 the collection no.2 + * @return true or false + */ + public static boolean containsAny(Collection c1, Collection c2) { + return c2.stream().anyMatch((i) -> c1.contains(i)); + } + + /** + * Filter the collection and count item + * + * @param the value type + * @param coll the collection + * @param predicate the predicate + * @return the item count + */ + public static int countItems(Collection coll, Predicate predicate) { + return (int) coll.stream().filter(predicate).count(); + } + + /** + * Loop the collection and calculate sum of value related to item in the collection + * + * @param the value type + * @param coll the collection + * @param measurer the measurer + * @return the sum value + */ + public static int flatMapToInt(Collection coll, Function measurer) { + return coll.stream().flatMapToInt((t) -> IntStream.of(measurer.apply(t))).sum(); + } + + /** + * Filter the collection and get an item + * + * @param the value type + * @param coll the collection + * @param predicate the predicate + * @return an item + */ + public static T getItem(Collection coll, Predicate predicate) { + for(T t : coll) + if(predicate.test(t)) + return t; + return null; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyDataConverter.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDataConverter.java similarity index 91% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyDataConverter.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDataConverter.java index d7d0e56f..154f81fa 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyDataConverter.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDataConverter.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.util; +package com.tvd12.ezyfoxserver.io; import java.lang.reflect.Array; import java.util.ArrayList; @@ -17,7 +17,7 @@ * */ -public abstract class EzyDataConverter { +public final class EzyDataConverter { // prevent new instance private EzyDataConverter() {} @@ -159,7 +159,11 @@ public static Short[] collectionToWrapperShortArray( */ public static boolean[] collectionToPrimitiveBoolArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Boolean[value.size()])); + int count = 0; + boolean[] answer = new boolean[value.size()]; + for(Boolean item : value) + answer[count ++] = item; + return answer; } /** @@ -170,7 +174,11 @@ public static boolean[] collectionToPrimitiveBoolArray( */ public static byte[] collectionToPrimitiveByteArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Byte[value.size()])); + int count = 0; + byte[] answer = new byte[value.size()]; + for(Byte item : value) + answer[count ++] = item; + return answer; } /** @@ -181,7 +189,11 @@ public static byte[] collectionToPrimitiveByteArray( */ public static char[] collectionToPrimitiveCharArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Character[value.size()])); + int count = 0; + char[] answer = new char[value.size()]; + for(Character item : value) + answer[count ++] = item; + return answer; } /** @@ -192,8 +204,11 @@ public static char[] collectionToPrimitiveCharArray( */ public static byte[] charCollectionToPrimitiveByteArray( Collection value) { - return charArrayToByteArray(ArrayUtils.toPrimitive( - value.toArray(new Character[value.size()]))); + int count = 0; + byte[] answer = new byte[value.size()]; + for(Character item : value) + answer[count ++] = (byte) item.charValue(); + return answer; } /** @@ -204,7 +219,11 @@ public static byte[] charCollectionToPrimitiveByteArray( */ public static double[] collectionToPrimitiveDoubleArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Double[value.size()])); + int count = 0; + double[] answer = new double[value.size()]; + for(Double item : value) + answer[count ++] = item; + return answer; } /** @@ -215,7 +234,11 @@ public static double[] collectionToPrimitiveDoubleArray( */ public static float[] collectionToPrimitiveFloatArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Float[value.size()])); + int count = 0; + float[] answer = new float[value.size()]; + for(Float item : value) + answer[count ++] = item; + return answer; } /** @@ -237,7 +260,11 @@ public static int[] collectionToPrimitiveIntArray( */ public static long[] collectionToPrimitiveLongArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Long[value.size()])); + int count = 0; + long[] answer = new long[value.size()]; + for(Long item : value) + answer[count ++] = item; + return answer; } /** @@ -248,7 +275,11 @@ public static long[] collectionToPrimitiveLongArray( */ public static short[] collectionToPrimitiveShortArray( Collection value) { - return ArrayUtils.toPrimitive(value.toArray(new Short[value.size()])); + int count = 0; + short[] answer = new short[value.size()]; + for(Short item : value) + answer[count ++] = item; + return answer; } /** @@ -386,8 +417,11 @@ public static List arrayToList(short[] value) { * @param value primitive byte array * @return Character collection */ - public static List byteArrayToCharList(byte[] value) { - return arrayToList(byteArrayToCharArray(value)); + public static List byteArrayToCharList(byte[] value) { + List answer = new ArrayList<>(); + for(byte b : value) + answer.add((char)b); + return answer; } //===== primitive array to wrapper array ===== diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDates.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDates.java new file mode 100644 index 00000000..c226abfe --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyDates.java @@ -0,0 +1,107 @@ +package com.tvd12.ezyfoxserver.io; + +import java.text.ParseException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAccessor; +import java.util.Date; + +import org.apache.commons.lang3.time.FastDateFormat; +import org.joda.time.DateTime; + +public final class EzyDates { + + private static final DateTimeFormatter DATE_TIME_FORMATTER + = getDateTimeFormatter(getPattern()); + + private EzyDates() { + } + + // ============= java 8 ============ + public static String format(TemporalAccessor temporal) { + return format(temporal, getDateTimeFormatter()); + } + + public static String format(TemporalAccessor temporal, String pattern) { + return format(temporal, getDateTimeFormatter(pattern)); + } + + public static String format(TemporalAccessor temporal, DateTimeFormatter formatter) { + return temporal == null ? null : formatter.format(temporal); + } + + public static LocalDate parseDate(String source) { + return parseDate(source, getDateTimeFormatter()); + } + + public static LocalDate parseDate(String source, String pattern) { + return parseDate(source, getDateTimeFormatter(pattern)); + } + + public static LocalDate parseDate(String source, DateTimeFormatter formatter) { + return LocalDate.parse(source, formatter); + } + + public static LocalDateTime parseDateTime(String source) { + return parseDateTime(source, getDateTimeFormatter()); + } + + public static LocalDateTime parseDateTime(String source, String pattern) { + return parseDateTime(source, getDateTimeFormatter(pattern)); + } + + public static LocalDateTime parseDateTime(String source, DateTimeFormatter formatter) { + return LocalDateTime.parse(source, formatter); + } + + public static DateTimeFormatter getDateTimeFormatter() { + return DATE_TIME_FORMATTER; + } + + public static DateTimeFormatter getDateTimeFormatter(String pattern) { + return DateTimeFormatter.ofPattern(pattern); + } + //================================= + + + // =================== java 7 =============== + public static String format(Date date) { + return format(date, getPattern()); + } + + public static Date parse(String source) { + return parse(source, getPattern()); + } + + public static String format(Date date, String pattern) { + return date == null ? null : FastDateFormat.getInstance(pattern).format(date); + } + + public static Date parse(String source, String pattern) { + try { + return FastDateFormat.getInstance(pattern).parse(source); + } catch (ParseException e) { + throw new IllegalArgumentException(e); + } + } + + public static String getPattern() { + return "yyyy-MM-dd'T'HH:mm:ss:SSS"; + } + + // ========================================= + public static boolean between(Date date, Date before, Date after) { + long time = date.getTime(); + return time >= before.getTime() && time <= after.getTime(); + } + + public static int formatAsInteger(Date date) { + DateTime dateTime = new DateTime(date.getTime()); + int year = dateTime.getYear(); + int month = dateTime.getMonthOfYear(); + int day = dateTime.getDayOfMonth(); + return year * 10000 + month * 100 + day; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java new file mode 100644 index 00000000..4e7bf21e --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyInts.java @@ -0,0 +1,38 @@ +package com.tvd12.ezyfoxserver.io; + +import java.nio.ByteBuffer; + +public final class EzyInts { + + private EzyInts() { + } + + public static int bin2int(int length) { + return EzyMath.bin2int(length); + } + + public static int bin2int(byte[] bytes) { + return EzyMath.bin2int(bytes); + } + + public static int bin2uint(byte[] bytes) { + return EzyMath.bin2uint(bytes); + } + + public static int bin2int(ByteBuffer buffer) { + return bin2int(buffer, 4); + } + + public static int bin2uint(ByteBuffer buffer) { + return bin2uint(buffer, 4); + } + + public static int bin2int(ByteBuffer buffer, int size) { + return bin2int(EzyBytes.copy(buffer, size)); + } + + public static int bin2uint(ByteBuffer buffer, int size) { + return bin2uint(EzyBytes.copy(buffer, size)); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyIterables.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyIterables.java new file mode 100644 index 00000000..bdc1a68f --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyIterables.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.io; + +public final class EzyIterables { + + private EzyIterables() { + } + + public static boolean isEmpty(Iterable iterable) { + if(iterable == null) + return true; + return !iterable.iterator().hasNext(); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLists.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLists.java new file mode 100644 index 00000000..3ef395e7 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLists.java @@ -0,0 +1,161 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.io; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import com.google.common.collect.Lists; + +/** + * @author tavandung12 + * + */ +public class EzyLists { + + // prevent new instance + private EzyLists() { + } + + /** + * Combine some collections to one + * + * @param the value type + * @param lists the collections to combine + * @return a new list + */ + @SuppressWarnings("unchecked") + public static List combine(Collection... lists) { + List answer = new ArrayList<>(); + for(Collection list : lists) + answer.addAll(list); + return answer; + } + + /** + * Transform for each item in a collection to new collection + * and add to new list + * + * @param coll the collection + * @param trans the transformer + * @return the new list + */ + public static List newHashSetByAddAll( + Collection coll, Function> trans) { + List set = new ArrayList<>(); + for(I input : coll) + set.addAll(trans.apply(input)); + return set; + } + + + /** + * Filter the collection and create a new list + * + * @param the value type + * @param coll the collection + * @param predicate the predicate + * @return a new list + */ + public static List filter(Collection coll, Predicate predicate) { + return coll.stream().filter(predicate).collect(Collectors.toList()); + } + + /** + * Remove some item from the collection and create a new list + * + * @param the value type + * @param coll the collection + * @param except the unexpected items + * @return a new list + */ + public static List newArrayList(Collection coll, Collection except) { + List answer = new ArrayList<>(coll); + answer.removeAll(except); + return answer; + } + + /** + * Remove some item from the collection and create a new list + * + * @param the value type + * @param coll the collection + * @param except the unexpected items + * @return a new list + */ + @SuppressWarnings("unchecked") + public static List newArrayList(Collection coll, T... except) { + return newArrayList(coll, Arrays.asList(except)); + } + + /** + * Transform an array to a new list + * + * @param the input type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return a new list + */ + public static List newArrayList(I[] input, Function refactor) { + return newArrayList(Lists.newArrayList(input), refactor); + } + + /** + * Transform a collection to a new list + * + * @param the input type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return a new list + */ + public static List newArrayList(Collection input, Function refactor) { + List answer = new ArrayList<>(); + for(I value : input) + answer.add(refactor.apply(value)); + return answer; + } + + /** + * + * Transform a map to new list + * + * @param the key type + * @param the value type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return the new list + */ + public static List newArrayList(Map input, BiFunction refactor) { + List answer = new ArrayList<>(); + for(K key : input.keySet()) + answer.add(refactor.apply(key, input.get(key))); + return answer; + } + + /** + * Combine a collection and an array of elements to a new list + * + * @param the value type + * @param coll the collection + * @param elements the array of elements + * @return the new list + */ + @SuppressWarnings("unchecked") + public static List addElementsToNewList(Collection coll, T... elements) { + List answer = new ArrayList<>(coll); + answer.addAll(Arrays.asList(elements)); + return answer; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java new file mode 100644 index 00000000..abad03c0 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyLongs.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.io; + +import java.nio.ByteBuffer; + +public final class EzyLongs { + + private EzyLongs() { + } + + public static long bin2long(int length) { + return EzyMath.bin2long(length); + } + + public static long bin2long(byte[] bytes) { + return EzyMath.bin2long(bytes); + } + + public static long bin2ulong(byte[] bytes) { + return EzyMath.bin2ulong(bytes); + } + + public static long bin2long(ByteBuffer buffer) { + return bin2long(buffer, 8); + } + + public static long bin2ulong(ByteBuffer buffer) { + return bin2ulong(buffer, 8); + } + + public static long bin2long(ByteBuffer buffer, int size) { + return bin2long(EzyBytes.copy(buffer, size)); + } + + public static long bin2ulong(ByteBuffer buffer, int size) { + return bin2ulong(EzyBytes.copy(buffer, size)); + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMaps.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMaps.java new file mode 100644 index 00000000..fe521cf9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMaps.java @@ -0,0 +1,157 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.helper.EzyLazyInitHelper; +import com.tvd12.ezyfoxserver.util.EzyObjects; + +public final class EzyMaps { + + private EzyMaps() { + } + + // ============================================= + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static T getValue(Map map, Class type) { + if(type == Object.class) + return null; + Object answer = map.get(type); + if(answer == null) + answer = getValueOfInterfaces(map, type); + if(answer == null && type.getSuperclass() != null) + answer = getValueOfSuper(map, type); + return (T)answer; + } + + @SuppressWarnings("rawtypes") + private static Object getValueOfSuper(Map map, Class type) { + return getValue(map, type.getSuperclass()); + } + + @SuppressWarnings("rawtypes") + private static Object getValueOfInterfaces(Map map, Class type) { + Object answer = null; + for(Class clazz : type.getInterfaces()) + if((answer = getValue(map, clazz)) != null) + return answer; + return answer; + } + + // ============================================= + + // ============================================= + public static List getValueList(Map map) { + return new ArrayList<>(map.values()); + } + + public static Set getValueSet(Map map) { + return new HashSet<>(map.values()); + } + // ============================================= + + // ============================================= + public static Map newHashMap( + Collection coll, Function keyGentor) { + Map map = new HashMap<>(); + for(V v : coll) + map.put(keyGentor.apply(v), v); + return map; + } + + public static Map newHashMapNewKeys( + Map origin, Function keyGentor) { + return newHashMap(origin, keyGentor, (v) -> v); + } + + public static Map newHashMapNewValues( + Map origin, Function valueGentor) { + return newHashMap(origin, (k) -> k, valueGentor); + } + + public static Map newHashMap(Map origin, + Function keyGentor, Function valueGentor) { + Map map = new HashMap<>(); + for(K k : origin.keySet()) + map.put(keyGentor.apply(k), valueGentor.apply(origin.get(k))); + return map; + } + + public static Map newHashMap(K key, V value) { + return newMap(key, value, new HashMap<>()); + } + + public static > M newMap(K key, V value, M map) { + map.put(key, value); + return map; + } + + //================================================================= + + public static Map getValues(Map map, Collection keys) { + Map answer = new HashMap<>(); + for(K k : keys) + if(map.containsKey(k)) + answer.put(k, map.get(k)); + return answer; + } + + public static List getValues(Map map, Predicate predicate) { + return map.values().stream().filter(predicate).collect(Collectors.toList()); + } + + public static V putIfAbsent(Map map, K key, V value) { + return EzyLazyInitHelper.init(map, + () -> map.get(key), + () -> map.computeIfAbsent(key, (k) -> value)); + } + + @SuppressWarnings("unchecked") + public static void addItemsToSet(Map> map, K key, E... items) { + addItemsToSet(map, key, Lists.newArrayList(items)); + } + + @SuppressWarnings("unchecked") + public static void addItemsToList(Map> map, K key, E... items) { + addItemsToList(map, key, Lists.newArrayList(items)); + } + + public static void addItemsToSet(Map> map, K key, Collection items) { + putIfAbsent(map, key, new HashSet<>()).addAll(items); + } + + public static void addItemsToList(Map> map, K key, Collection items) { + putIfAbsent(map, key, new ArrayList<>()).addAll(items); + } + + @SuppressWarnings("unchecked") + public static void removeItems(Map> map, K key, E... items) { + removeItems(map, key, Lists.newArrayList(items)); + } + + public static void removeItems(Map> map, K key, Collection items) { + if(map.containsKey(key)) + map.get(key).removeAll(items); + } + + // ============================================= + @SuppressWarnings("rawtypes") + public static boolean containsAll(Map map1, Map map2) { + for(Object key : map2.keySet()) { + if(!map1.containsKey(key)) + return false; + if(!EzyObjects.equals(map2.get(key), map1.get(key))) + return false; + } + return true; + } +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java similarity index 97% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java index b8f3483f..adfdca34 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyMath.java @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.io; -public abstract class EzyMath { +public final class EzyMath { private EzyMath() { } diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyNumbersConverter.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyNumbersConverter.java new file mode 100644 index 00000000..1aed30d2 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyNumbersConverter.java @@ -0,0 +1,477 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Arrays; +import java.util.Collection; +import java.util.function.Function; + +import com.tvd12.ezyfoxserver.function.EzyNewArray; +import com.tvd12.ezyfoxserver.function.EzyNumber; + +@SuppressWarnings({"rawtypes"}) +public final class EzyNumbersConverter { + + private EzyNumbersConverter() { + } + + // primitive + public static byte[] numbersToPrimitiveBytes(Collection coll) { + int index = 0; + byte[] answer = new byte[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).byteValue(); + return answer; + } + + public static char[] numbersToPrimitiveChars(Collection coll) { + int index = 0; + char[] answer = new char[coll.size()]; + for(Object obj : coll) + answer[index ++] = objectToChar(obj); + return answer; + } + + public static double[] numbersToPrimitiveDoubles(Collection coll) { + int index = 0; + double[] answer = new double[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).doubleValue(); + return answer; + } + + public static float[] numbersToPrimitiveFloats(Collection coll) { + int index = 0; + float[] answer = new float[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).floatValue(); + return answer; + } + + public static int[] numbersToPrimitiveInts(Collection coll) { + int index = 0; + int[] answer = new int[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).intValue(); + return answer; + } + + public static long[] numbersToPrimitiveLongs(Collection coll) { + int index = 0; + long[] answer = new long[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).longValue(); + return answer; + } + + public static short[] numbersToPrimitiveShorts(Collection coll) { + int index = 0; + short[] answer = new short[coll.size()]; + for(Object obj : coll) + answer[index ++] = ((Number)obj).shortValue(); + return answer; + } + + // wrapper + public static O[] objectsToWrapperNumbers( + Collection coll, EzyNewArray newer, Function mapper) { + return coll.stream().map(mapper).toArray((size) -> newer.apply(size)); + } + + public static O[] numbersToWrapperNumbers( + Collection coll, EzyNewArray applier, EzyNumber converter) { + return objectsToWrapperNumbers(coll, applier, (num) -> convertNumber(num, converter)); + } + + public static O[] objectsToWrapperNumbers( + I[] array, EzyNewArray newer, Function mapper) { + return Arrays.stream(array).map(mapper).toArray((size) -> newer.apply(size)); + } + + public static O[] numbersToWrapperNumbers( + Number[] numbers, EzyNewArray applier, EzyNumber converter) { + return objectsToWrapperNumbers(numbers, applier, (num) -> convertNumber(num, converter)); + } + + public static Byte[] numbersToWrapperBytes(Collection coll) { + return numbersToWrapperNumbers(coll, Byte[]::new, (num) -> numberToByte(num)); + } + + public static Character[] numbersToWrapperChars(Collection coll) { + int index = 0; + Character[] answer = new Character[coll.size()]; + for(Object obj : coll) + answer[index ++] = objectToChar(obj); + return answer; + } + + public static Double[] numbersToWrapperDoubles(Collection coll) { + return numbersToWrapperNumbers(coll, Double[]::new, (num) -> numberToDouble(num)); + } + + public static Float[] numbersToWrapperFloats(Collection coll) { + return numbersToWrapperNumbers(coll, Float[]::new, (num) -> numberToFloat(num)); + } + + public static Integer[] numbersToWrapperInts(Collection coll) { + return numbersToWrapperNumbers(coll, Integer[]::new, (num) -> numberToInt(num)); + } + + public static Long[] numbersToWrapperLongs(Collection coll) { + return numbersToWrapperNumbers(coll, Long[]::new, (num) -> numberToLong(num)); + } + + public static Short[] numbersToWrapperShorts(Collection coll) { + return numbersToWrapperNumbers(coll, Short[]::new, (num) -> numberToShort(num)); + } + + //================================================= + public static Byte[] numbersToWrapperBytes(Number[] array) { + return numbersToWrapperNumbers(array, Byte[]::new, (num) -> numberToByte(num)); + } + + public static Character[] numbersToWrapperChars(Object[] value) { + Character[] answer = new Character[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = objectToChar(value[i]); + return answer; + } + + public static Double[] numbersToWrapperDoubles(Number[] array) { + return numbersToWrapperNumbers(array, Double[]::new, (num) -> numberToDouble(num)); + } + + public static Float[] numbersToWrapperFloats(Number[] array) { + return numbersToWrapperNumbers(array, Float[]::new, (num) -> numberToFloat(num)); + } + + public static Integer[] numbersToWrapperInts(Number[] array) { + return numbersToWrapperNumbers(array, Integer[]::new, (num) -> numberToInt(num)); + } + + public static Long[] numbersToWrapperLongs(Number[] array) { + return numbersToWrapperNumbers(array, Long[]::new, (num) -> numberToLong(num)); + } + + public static Short[] numbersToWrapperShorts(Number[] array) { + return numbersToWrapperNumbers(array, Short[]::new, (num) -> numberToShort(num)); + } + //================================================= + + public static Byte numberToByte(Number number) { + return convertNumber(number, (num) -> num.byteValue()); + } + + public static Character numberToChar(Number number) { + return convertNumber(number, (num) -> (char)num.byteValue()); + } + + public static Character objectToChar(Object object) { + return (object instanceof Number) + ? numberToChar((Number)object) : (Character) object; + } + + public static Double numberToDouble(Number number) { + return convertNumber(number, (num) -> num.doubleValue()); + } + + public static Float numberToFloat(Number number) { + return convertNumber(number, (num) -> num.floatValue()); + } + + public static Integer numberToInt(Number number) { + return convertNumber(number, (num) -> num.intValue()); + } + + public static Long numberToLong(Number number) { + return convertNumber(number, (num) -> num.longValue()); + } + + public static Short numberToShort(Number number) { + return convertNumber(number, (num) -> num.shortValue()); + } + + public static T convertNumber(Object number, EzyNumber converter) { + return converter.apply((Number)number); + } + + public static T convertNumber(Number number, EzyNumber converter) { + return converter.apply(number); + } + + //================ wrapper to primitive array =========== + public static boolean[] boolArrayWrapperToPrimitive(Boolean[] value) { + boolean[] answer = new boolean[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static byte[] numbersToPrimitiveBytes(Number[] value) { + byte[] answer = new byte[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].byteValue(); + return answer; + } + + public static char[] numbersToPrimitiveChars(Object[] value) { + char[] answer = new char[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = objectToChar(value[i]); + return answer; + } + + public static double[] numbersToPrimitiveDoubles(Number[] value) { + double[] answer = new double[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].doubleValue(); + return answer; + } + + public static float[] numbersToPrimitiveFloats(Number[] value) { + float[] answer = new float[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].floatValue(); + return answer; + } + + public static int[] numbersToPrimitiveInts(Number[] value) { + int[] answer = new int[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].intValue(); + return answer; + } + + public static long[] numbersToPrimitiveLongs(Number[] value) { + long[] answer = new long[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].longValue(); + return answer; + } + + public static short[] numbersToPrimitiveShorts(Number[] value) { + short[] answer = new short[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i].shortValue(); + return answer; + } + + //====================== primitive to wrapper array ========= + public static Boolean[] boolArrayPrimitiveToWrapper(boolean[] value) { + Boolean[] answer = new Boolean[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Byte[] byteArrayPrimitiveToWrapper(byte[] value) { + Byte[] answer = new Byte[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Character[] charArrayPrimitiveToWrapper(char[] value) { + Character[] answer = new Character[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Double[] doubleArrayPrimitiveToWrapper(double[] value) { + Double[] answer = new Double[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Float[] floatArrayPrimitiveToWrapper(float[] value) { + Float[] answer = new Float[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Integer[] intArrayPrimitiveToWrapper(int[] value) { + Integer[] answer = new Integer[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Long[] longArrayPrimitiveToWrapper(long[] value) { + Long[] answer = new Long[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + public static Short[] shortArrayPrimitiveToWrapper(short[] value) { + Short[] answer = new Short[value.length]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = value[i]; + return answer; + } + + //====================== two-dimensions wrapper array to primitive array ========= + public static boolean[][] boolArraysWrapperToPrimitive(Boolean[][] value) { + boolean[][] answer = new boolean[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = boolArrayWrapperToPrimitive(value[i]); + return answer; + } + + public static byte[][] numbersToPrimitiveByteArrays(Number[][] value) { + byte[][] answer = new byte[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveBytes(value[i]); + return answer; + } + + public static char[][] numbersToPrimitiveCharArrays(Object[][] value) { + char[][] answer = new char[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveChars(value[i]); + return answer; + } + + public static double[][] numbersToPrimitiveDoubleArrays(Number[][] value) { + double[][] answer = new double[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveDoubles(value[i]); + return answer; + } + + public static float[][] numbersToPrimitiveFloatArrays(Number[][] value) { + float[][] answer = new float[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveFloats(value[i]); + return answer; + } + + public static int[][] numbersToPrimitiveIntArrays(Number[][] value) { + int[][] answer = new int[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveInts(value[i]); + return answer; + } + + public static long[][] numbersToPrimitiveLongArrays(Number[][] value) { + long[][] answer = new long[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveLongs(value[i]); + return answer; + } + + public static short[][] numbersToPrimitiveShortArrays(Number[][] value) { + short[][] answer = new short[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToPrimitiveShorts(value[i]); + return answer; + } + + //====================== two-dimensions wrapper array to primitive array ========= + public static Boolean[][] boolArraysPrimitiveToWrapper(boolean[][] value) { + Boolean[][] answer = new Boolean[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = boolArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Byte[][] byteArraysPrimitiveToWrapper(byte[][] value) { + Byte[][] answer = new Byte[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = byteArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Character[][] charArraysPrimitiveToWrapper(char[][] value) { + Character[][] answer = new Character[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = charArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Double[][] doubleArraysPrimitiveToWrapper(double[][] value) { + Double[][] answer = new Double[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = doubleArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Float[][] floatArraysPrimitiveToWrapper(float[][] value) { + Float[][] answer = new Float[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = floatArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Integer[][] intArraysPrimitiveToWrapper(int[][] value) { + Integer[][] answer = new Integer[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = intArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Long[][] longArraysPrimitiveToWrapper(long[][] value) { + Long[][] answer = new Long[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = longArrayPrimitiveToWrapper(value[i]); + return answer; + } + + public static Short[][] shortArraysPrimitiveToWrapper(short[][] value) { + Short[][] answer = new Short[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = shortArrayPrimitiveToWrapper(value[i]); + return answer; + } + + //============ numbers to wrapper arrays ========== + public static Byte[][] numbersToWrapperByteArrays(Number[][] value) { + Byte[][] answer = new Byte[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperBytes(value[i]); + return answer; + } + + public static Character[][] numbersToWrapperCharArrays(Object[][] value) { + Character[][] answer = new Character[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperChars(value[i]); + return answer; + } + + public static Double[][] numbersToWrapperDoubleArrays(Number[][] value) { + Double[][] answer = new Double[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperDoubles(value[i]); + return answer; + } + + public static Float[][] numbersToWrapperFloatArrays(Number[][] value) { + Float[][] answer = new Float[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperFloats(value[i]); + return answer; + } + + public static Integer[][] numbersToWrapperIntArrays(Number[][] value) { + Integer[][] answer = new Integer[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperInts(value[i]); + return answer; + } + + public static Long[][] numbersToWrapperLongArrays(Number[][] value) { + Long[][] answer = new Long[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperLongs(value[i]); + return answer; + } + + public static Short[][] numbersToWrapperShortArrays(Number[][] value) { + Short[][] answer = new Short[value.length][]; + for(int i = 0 ; i < value.length ; i++) + answer[i] = numbersToWrapperShorts(value[i]); + return answer; + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java new file mode 100644 index 00000000..749cf8d9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyPrints.java @@ -0,0 +1,53 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Arrays; + +public final class EzyPrints { + + private EzyPrints() { + } + + public static String print(Object object) { + if(object == null) + return "null"; + if(object instanceof boolean[]) + return Arrays.toString((boolean[])object); + if(object instanceof byte[]) + return Arrays.toString((byte[])object); + if(object instanceof char[]) + return Arrays.toString((char[])object); + if(object instanceof double[]) + return Arrays.toString((double[])object); + if(object instanceof float[]) + return Arrays.toString((float[])object); + if(object instanceof int[]) + return Arrays.toString((int[])object); + if(object instanceof long[]) + return Arrays.toString((long[])object); + if(object instanceof short[]) + return Arrays.toString((short[])object); + if(object instanceof Object[]) + return Arrays.toString((Object[])object); + return object.toString(); + } + + public static String printBits(byte[] bytes) { + StringBuilder builder = new StringBuilder(); + for(int i = 0 ; i < bytes.length ; i++) + builder.append(printBits(bytes[i])); + return builder.toString(); + } + + public static String printBits(byte value) { + String str = insertBegin(Integer.toBinaryString(value & 0xff), "0", 8); + return str.substring(str.length() - 8); + } + + public static String insertBegin(String str, String ch, int maxlen) { + String answer = str; + while(answer.length() < maxlen) + answer = ch + answer; + return answer; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySets.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySets.java new file mode 100644 index 00000000..abd25d73 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySets.java @@ -0,0 +1,151 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import com.google.common.collect.Sets; + +public final class EzySets { + + private EzySets() { + } + + /** + * Combine some set of items + * + * @param sets some set of items + * @return the new HashSet + */ + @SuppressWarnings({ "unchecked"}) + public static Set combine(Collection... sets) { + Set all = new HashSet<>(); + for(Collection set : sets) + all.addAll(set); + return all; + } + + /** + * Transform for each item in a collection to new collection + * and add to new HashSet + * + * @param coll the collection + * @param trans the transformer + * @return the new HashSet + */ + public static Set newHashSetByAddAll( + Collection coll, Function> trans) { + Set set = new HashSet<>(); + for(I input : coll) + set.addAll(trans.apply(input)); + return set; + } + + /** + * Filter the collection and create a new hash set + * + * @param the value type + * @param coll the collection + * @param predicate the predicate + * @return the new hash set + */ + public static Set filter(Collection coll, Predicate predicate) { + return coll.stream().filter(predicate).collect(Collectors.toSet()); + } + + /** + * Remove some item from the collection and create a new hash set + * + * @param the value type + * @param coll the collection + * @param except the unexpected items + * @return a new hash set + */ + public static Set newHashSet(Collection coll, Collection except) { + Set answer = new HashSet<>(coll); + answer.removeAll(except); + return answer; + } + + /** + * Remove some item from the collection and create a new hash set + * + * @param the value type + * @param coll the collection + * @param except the unexpected items + * @return a new hash set + */ + @SuppressWarnings("unchecked") + public static Set newHashSet(Collection coll, T... except) { + return newHashSet(coll, Arrays.asList(except)); + } + + /** + * Transform an array to a new hash set + * + * @param the input type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return a new hash set + */ + public static Set newHashSet(I[] input, Function refactor) { + return newHashSet(Sets.newHashSet(input), refactor); + } + + /** + * Transform a collection to a new hash set + * + * @param the input type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return a new hash set + */ + public static Set newHashSet(Collection input, Function refactor) { + Set answer = new HashSet<>(); + for(I value : input) + answer.add(refactor.apply(value)); + return answer; + } + + /** + * + * Transform a map to new hash set + * + * @param the key type + * @param the value type + * @param the output type + * @param input the input + * @param refactor the refactor + * @return the new hash set + */ + public static Set newHashSet(Map input, BiFunction refactor) { + Set answer = new HashSet<>(); + for(K key : input.keySet()) + answer.add(refactor.apply(key, input.get(key))); + return answer; + } + + /** + * Combine a collection and an array of elements to a new hash set + * + * @param the value type + * @param coll the collection + * @param elements the array of elements + * @return the new hash set + */ + @SuppressWarnings("unchecked") + public static Set addElementsToNewSet(Collection coll, T... elements) { + Set answer = new HashSet<>(coll); + answer.addAll(Arrays.asList(elements)); + return answer; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleValueConverter.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleValueConverter.java new file mode 100644 index 00000000..7632ccf4 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzySimpleValueConverter.java @@ -0,0 +1,816 @@ +package com.tvd12.ezyfoxserver.io; + +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToStringArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.boolArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.boolArrayWrapperToPrimitive; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.boolArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.boolArraysWrapperToPrimitive; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.byteArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.byteArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.charArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.charArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.doubleArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.doubleArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.floatArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.floatArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.intArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.intArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.longArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.longArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveByteArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveBytes; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveCharArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveChars; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveDoubleArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveDoubles; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveFloatArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveFloats; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveIntArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveInts; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveLongArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveLongs; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveShortArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToPrimitiveShorts; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperByteArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperBytes; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperCharArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperChars; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperDoubleArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperDoubles; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperFloatArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperFloats; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperIntArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperInts; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperLongArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperLongs; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperShortArrays; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.numbersToWrapperShorts; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.shortArrayPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.shortArraysPrimitiveToWrapper; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToChar; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveBoolArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveByteArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveByteArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveCharArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveCharArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveDoubleArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveFloatArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveIntArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveIntArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveLongArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveLongArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveShortArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToPrimitiveShortArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToStringArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperBoolArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperByteArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperByteArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperCharArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperCharArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperDoubleArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperFloatArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperIntArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperIntArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperLongArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperLongArrays; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperShortArray; +import static com.tvd12.ezyfoxserver.io.EzyStringConveter.stringToWrapperShortArrays; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import com.tvd12.ezyfoxserver.function.EzyToObject; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class EzySimpleValueConverter + extends EzyLoggable + implements EzyValueConverter { + + protected final Map transformers; + + public EzySimpleValueConverter() { + this.transformers = defaultTransformers(); + } + + @Override + public T convert(Object value, Class outType) { + if(value == null) + return null; + if(transformers.containsKey(outType)) + return (T) transformers.get(outType).transform(value); + return (T)value; + } + + protected IllegalArgumentException + newTransformerException(Class type, Object value) { + return new IllegalArgumentException( + "can't transform: " + value + " to " + type.getSimpleName() + " value"); +} + + //tank + private Map + defaultTransformers() { + Map answer = new ConcurrentHashMap<>(); + addOtherTransformers(answer); + addWrapperTransformers(answer); + addPrimitiveTransformers(answer); + addWrapperArrayTransformers(answer); + addPrimitiveArrayTransformers(answer); + addTwoDimensionsWrapperArrayTransformers(answer); + addTwoDimensionsPrimitiveArrayTransformers(answer); + return answer; + } + + protected void addPrimitiveTransformers(Map answer) { + answer.put(boolean.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Boolean.valueOf((String)value); + if(value instanceof Boolean) + return (Boolean)value; + throw newTransformerException(boolean.class, value); + } + }); + answer.put(byte.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Byte.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).byteValue(); + throw newTransformerException(byte.class, value); + } + }); + answer.put(char.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof Character) + return ((Character)value); + if(value instanceof Number) + return (char)((Number)value).byteValue(); + if(value instanceof String) + return stringToChar((String)value); + throw newTransformerException(char.class, value); + } + }); + answer.put(double.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Double.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).doubleValue(); + throw newTransformerException(double.class, value); + } + }); + answer.put(float.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Float.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).floatValue(); + throw newTransformerException(float.class, value); + } + }); + answer.put(int.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Integer.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).intValue(); + throw newTransformerException(int.class, value); + } + }); + answer.put(long.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Long.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).longValue(); + throw newTransformerException(long.class, value); + } + }); + answer.put(short.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Short.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).shortValue(); + throw newTransformerException(short.class, value); + } + }); + } + + protected void addWrapperTransformers(Map answer) { + answer.put(Boolean.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Boolean.valueOf((String)value); + if(value instanceof Boolean) + return (Boolean)value; + throw newTransformerException(Boolean.class, value); + } + }); + answer.put(Byte.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Byte.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).byteValue(); + throw newTransformerException(Byte.class, value); + } + }); + answer.put(Character.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof Character) + return ((Character)value); + if(value instanceof Number) + return (char)((Number)value).byteValue(); + if(value instanceof String) + return stringToChar((String)value); + throw newTransformerException(Character.class, value); + } + }); + answer.put(Double.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Double.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).doubleValue(); + throw newTransformerException(Double.class, value); + } + }); + answer.put(Float.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Float.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).floatValue(); + throw newTransformerException(float.class, value); + } + }); + answer.put(Integer.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Integer.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).intValue(); + throw newTransformerException(Integer.class, value); + } + }); + answer.put(Long.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Long.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).longValue(); + throw newTransformerException(Long.class, value); + } + }); + answer.put(Short.class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return Short.valueOf((String)value); + if(value instanceof Number) + return ((Number)value).shortValue(); + throw newTransformerException(Short.class, value); + } + }); + + answer.put(String.class, new EzyToObject() { + @Override + public Object transform(Object value) { + return value.toString(); + } + }); + } + + protected void addPrimitiveArrayTransformers(Map answer) { + answer.put(boolean[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveBoolArray((String)value); + if(value instanceof boolean[]) + return value; + if(value instanceof Boolean[]) + return boolArrayWrapperToPrimitive((Boolean[])value); + if(value instanceof Collection) + return collectionToPrimitiveBoolArray((Collection)value); + throw newTransformerException(boolean[].class, value); + } + }); + answer.put(byte[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveByteArray((String)value); + if(value instanceof byte[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveBytes((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveBytes((Collection)value); + throw newTransformerException(byte[].class, value); + } + }); + answer.put(char[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveCharArray((String)value); + if(value instanceof char[]) + return value; + if(value instanceof Object[]) + return numbersToPrimitiveChars((Object[])value); + if(value instanceof Collection) + return numbersToPrimitiveChars((Collection)value); + throw newTransformerException(char[].class, value); + } + }); + + answer.put(double[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveDoubleArray((String)value); + if(value instanceof double[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveDoubles((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveDoubles((Collection)value); + throw newTransformerException(double[].class, value); + } + }); + answer.put(float[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveFloatArray((String)value); + if(value instanceof float[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveFloats((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveFloats((Collection)value); + throw newTransformerException(float[].class, value); + } + }); + answer.put(int[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveIntArray((String)value); + if(value instanceof int[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveInts((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveInts((Collection)value); + throw newTransformerException(int[].class, value); + } + }); + answer.put(long[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveLongArray((String)value); + if(value instanceof long[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveLongs((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveLongs((Collection)value); + throw newTransformerException(long[].class, value); + } + }); + answer.put(short[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveShortArray((String)value); + if(value instanceof short[]) + return value; + if(value instanceof Number[]) + return numbersToPrimitiveShorts((Number[])value); + if(value instanceof Collection) + return numbersToPrimitiveShorts((Collection)value); + throw newTransformerException(short[].class, value); + } + }); + } + protected void addWrapperArrayTransformers(Map answer) { + answer.put(Boolean[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperBoolArray((String)value); + if(value instanceof Boolean[]) + return value; + if(value instanceof boolean[]) + return boolArrayPrimitiveToWrapper((boolean[])value); + if(value instanceof Collection) + return collectionToWrapperBoolArray((Collection)value); + throw newTransformerException(Boolean[].class, value); + } + }); + answer.put(Byte[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperByteArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperBytes((Number[])value); + if(value instanceof byte[]) + return byteArrayPrimitiveToWrapper((byte[])value); + if(value instanceof Collection) + return numbersToWrapperBytes((Collection)value); + throw newTransformerException(Boolean[].class, value); + } + }); + answer.put(Character[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperCharArray((String)value); + if(value instanceof Character[]) + return value; + if(value instanceof char[]) + return charArrayPrimitiveToWrapper((char[])value); + if(value instanceof Collection) + return numbersToWrapperChars((Collection)value); + throw newTransformerException(Character[].class, value); + } + }); + answer.put(Double[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperDoubleArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperDoubles((Number[])value); + if(value instanceof double[]) + return doubleArrayPrimitiveToWrapper((double[])value); + if(value instanceof Collection) + return numbersToWrapperDoubles((Collection)value); + throw newTransformerException(Double[].class, value); + } + }); + answer.put(Float[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperFloatArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperFloats((Number[])value); + if(value instanceof float[]) + return floatArrayPrimitiveToWrapper((float[])value); + if(value instanceof Collection) + return numbersToWrapperFloats((Collection)value); + throw newTransformerException(Float[].class, value); + } + }); + answer.put(Integer[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperIntArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperInts((Number[])value); + if(value instanceof int[]) + return intArrayPrimitiveToWrapper((int[])value); + if(value instanceof Collection) + return numbersToWrapperInts((Collection)value); + throw newTransformerException(Integer[].class, value); + } + }); + answer.put(Long[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperLongArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperLongs((Number[])value); + if(value instanceof long[]) + return longArrayPrimitiveToWrapper((long[])value); + if(value instanceof Collection) + return numbersToWrapperLongs((Collection)value); + throw newTransformerException(Long[].class, value); + } + }); + answer.put(Short[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperShortArray((String)value); + if(value instanceof Number[]) + return numbersToWrapperShorts((Number[])value); + if(value instanceof short[]) + return shortArrayPrimitiveToWrapper((short[])value); + if(value instanceof Collection) + return numbersToWrapperShorts((Collection)value); + throw newTransformerException(Short[].class, value); + } + }); + + answer.put(String[].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return ((String)value).split(","); + if(value instanceof String[]) + return value; + if(value instanceof Collection) + return collectionToStringArray((Collection)value); + throw newTransformerException(String[].class, value); + } + }); + } + + protected void addOtherTransformers(Map answer) { + answer.put(Date.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyDates.parse(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + + answer.put(LocalDate.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyDates.parseDate(value, "yyyy-MM-dd"); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + + answer.put(LocalDateTime.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyDates.parseDateTime(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + + //other + answer.put(Class.class, new EzyToObject() { + @Override + public Object transform(String value) { + try { + return EzyClasses.getClass(value); + } catch (Exception e) { + getLogger().info("value = " + value + " is invalid", e); + } + return null; + } + }); + } + + protected void addTwoDimensionsPrimitiveArrayTransformers(Map answer) { + answer.put(boolean[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveBoolArrays((String)value); + if(value instanceof boolean[][]) + return value; + if(value instanceof Boolean[][]) + return boolArraysWrapperToPrimitive((Boolean[][])value); + throw newTransformerException(boolean[][].class, value); + } + }); + answer.put(byte[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveByteArrays((String)value); + if(value instanceof byte[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveByteArrays((Number[][])value); + throw newTransformerException(byte[][].class, value); + } + }); + answer.put(char[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveCharArrays((String)value); + if(value instanceof char[][]) + return value; + if(value instanceof Object[][]) + return numbersToPrimitiveCharArrays((Object[][])value); + throw newTransformerException(char[][].class, value); + } + }); + answer.put(double[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveDoubleArrays((String)value); + if(value instanceof double[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveDoubleArrays((Number[][])value); + throw newTransformerException(double[][].class, value); + } + }); + answer.put(float[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveFloatArrays((String)value); + if(value instanceof float[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveFloatArrays((Number[][])value); + throw newTransformerException(float[][].class, value); + } + }); + answer.put(int[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveIntArrays((String)value); + if(value instanceof int[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveIntArrays((Number[][])value); + throw newTransformerException(boolean[][].class, value); + } + }); + answer.put(long[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveLongArrays((String)value); + if(value instanceof long[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveLongArrays((Number[][])value); + throw newTransformerException(long[][].class, value); + } + }); + answer.put(short[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToPrimitiveShortArrays((String)value); + if(value instanceof short[][]) + return value; + if(value instanceof Number[][]) + return numbersToPrimitiveShortArrays((Number[][])value); + throw newTransformerException(short[][].class, value); + } + }); + } + + protected void addTwoDimensionsWrapperArrayTransformers(Map answer) { + answer.put(Boolean[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperBoolArrays((String)value); + if(value instanceof Boolean[][]) + return value; + if(value instanceof boolean[][]) + return boolArraysPrimitiveToWrapper((boolean[][])value); + throw newTransformerException(Boolean[][].class, value); + } + }); + answer.put(Byte[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperByteArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperByteArrays((Number[][])value); + if(value instanceof byte[][]) + return byteArraysPrimitiveToWrapper((byte[][])value); + throw newTransformerException(Byte[][].class, value); + } + }); + answer.put(Character[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperCharArrays((String)value); + if(value instanceof Object[][]) + return numbersToWrapperCharArrays((Number[][])value); + if(value instanceof char[][]) + return charArraysPrimitiveToWrapper((char[][])value); + throw newTransformerException(Character[][].class, value); + } + }); + answer.put(Double[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperDoubleArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperDoubleArrays((Number[][])value); + if(value instanceof double[][]) + return doubleArraysPrimitiveToWrapper((double[][])value); + throw newTransformerException(Double[][].class, value); + } + }); + answer.put(Float[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperFloatArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperFloatArrays((Number[][])value); + if(value instanceof float[][]) + return floatArraysPrimitiveToWrapper((float[][])value); + throw newTransformerException(Float[][].class, value); + } + }); + answer.put(Integer[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperIntArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperIntArrays((Number[][])value); + if(value instanceof int[][]) + return intArraysPrimitiveToWrapper((int[][])value); + throw newTransformerException(Integer[][].class, value); + } + }); + answer.put(Long[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperLongArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperLongArrays((Number[][])value); + if(value instanceof long[][]) + return longArraysPrimitiveToWrapper((long[][])value); + throw newTransformerException(Long[][].class, value); + } + }); + answer.put(Short[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToWrapperShortArrays((String)value); + if(value instanceof Number[][]) + return numbersToWrapperShortArrays((Number[][])value); + if(value instanceof short[][]) + return shortArraysPrimitiveToWrapper((short[][])value); + throw newTransformerException(Short[][].class, value); + } + }); + answer.put(String[][].class, new EzyToObject() { + @Override + public Object transform(Object value) { + if(value instanceof String) + return stringToStringArrays((String)value); + if(value instanceof String[][]) + return value; + throw newTransformerException(String[][].class, value); + } + }); + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStringConveter.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStringConveter.java new file mode 100644 index 00000000..716002a6 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStringConveter.java @@ -0,0 +1,238 @@ +package com.tvd12.ezyfoxserver.io; + +import java.util.function.Function; +import java.util.function.IntFunction; + +public final class EzyStringConveter { + + private EzyStringConveter() { + } + + // ====================== primitive array ================= + public static boolean[] stringToPrimitiveBoolArray(String string) { + String[] strs = string.split(","); + boolean[] array = new boolean[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Boolean.valueOf(strs[i].trim()); + return array; + } + + public static byte[] stringToPrimitiveByteArray(String string) { + String[] strs = string.split(","); + byte[] array = new byte[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Byte.valueOf(strs[i].trim()); + return array; + } + + public static char[] stringToPrimitiveCharArray(String string) { + return string.toCharArray(); + } + + public static double[] stringToPrimitiveDoubleArray(String string) { + String[] strs = string.split(","); + double[] array = new double[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Double.valueOf(strs[i].trim()); + return array; + } + + public static float[] stringToPrimitiveFloatArray(String string) { + String[] strs = string.split(","); + float[] array = new float[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Float.valueOf(strs[i].trim()); + return array; + } + + public static int[] stringToPrimitiveIntArray(String string) { + String[] strs = string.split(","); + int[] array = new int[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Integer.valueOf(strs[i].trim()); + return array; + } + + public static long[] stringToPrimitiveLongArray(String string) { + String[] strs = string.split(","); + long[] array = new long[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Long.valueOf(strs[i].trim()); + return array; + } + + public static short[] stringToPrimitiveShortArray(String string) { + String[] strs = string.split(","); + short[] array = new short[strs.length]; + for(int i = 0 ; i < strs.length ; i++) + array[i] = Short.valueOf(strs[i].trim()); + return array; + } + + // ====================== wrapper array ================= + public static Boolean[] stringToWrapperBoolArray(String string) { + return stringToArray(string, i -> Boolean.valueOf(i), Boolean[]::new); + } + + public static Byte[] stringToWrapperByteArray(String string) { + return stringToArray(string, i -> Byte.valueOf(i), Byte[]::new); + } + + public static Character[] stringToWrapperCharArray(String string) { + Character[] array = new Character[string.length()]; + for(int i = 0 ; i < string.length() ; i++) + array[i] = string.charAt(i); + return array; + } + + public static Double[] stringToWrapperDoubleArray(String string) { + return stringToArray(string, i -> Double.valueOf(i), Double[]::new); + } + + public static Float[] stringToWrapperFloatArray(String string) { + return stringToArray(string, i -> Float.valueOf(i), Float[]::new); + } + + public static Integer[] stringToWrapperIntArray(String string) { + return stringToArray(string, i -> Integer.valueOf(i), Integer[]::new); + } + + public static Long[] stringToWrapperLongArray(String string) { + return stringToArray(string, i -> Long.valueOf(i), Long[]::new); + } + + public static Short[] stringToWrapperShortArray(String string) { + return stringToArray(string, i -> Short.valueOf(i), Short[]::new); + } + + // ====================== two-dimensions primitive array ================= + public static boolean[][] stringToPrimitiveBoolArrays(String string) { + String[] strs = string.split(";"); + boolean[][] arrays = new boolean[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveBoolArray(strs[i]); + return arrays; + } + + public static byte[][] stringToPrimitiveByteArrays(String string) { + String[] strs = string.split(";"); + byte[][] arrays = new byte[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveByteArray(strs[i]); + return arrays; + } + + public static char[][] stringToPrimitiveCharArrays(String string) { + String[] strs = string.split(";"); + char[][] arrays = new char[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveCharArray(strs[i]); + return arrays; + } + + public static double[][] stringToPrimitiveDoubleArrays(String string) { + String[] strs = string.split(";"); + double[][] arrays = new double[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveDoubleArray(strs[i]); + return arrays; + } + + public static float[][] stringToPrimitiveFloatArrays(String string) { + String[] strs = string.split(";"); + float[][] arrays = new float[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveFloatArray(strs[i]); + return arrays; + } + + public static int[][] stringToPrimitiveIntArrays(String string) { + String[] strs = string.split(";"); + int[][] arrays = new int[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveIntArray(strs[i]); + return arrays; + } + + public static long[][] stringToPrimitiveLongArrays(String string) { + String[] strs = string.split(";"); + long[][] arrays = new long[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveLongArray(strs[i]); + return arrays; + } + + public static short[][] stringToPrimitiveShortArrays(String string) { + String[] strs = string.split(";"); + short[][] arrays = new short[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToPrimitiveShortArray(strs[i]); + return arrays; + } + + // ====================== two-dimensions wrapper array ================= + public static Boolean[][] stringToWrapperBoolArrays(String string) { + return stringToArrays(string, i -> Boolean.valueOf(i), Boolean[][]::new, Boolean[]::new); + } + + public static Byte[][] stringToWrapperByteArrays(String string) { + return stringToArrays(string, i -> Byte.valueOf(i), Byte[][]::new, Byte[]::new); + } + + public static Character[][] stringToWrapperCharArrays(String string) { + String[] strs = string.split(";"); + Character[][] arrays = new Character[strs.length][]; + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToWrapperCharArray(strs[i]); + return arrays; + } + + public static Double[][] stringToWrapperDoubleArrays(String string) { + return stringToArrays(string, i -> Double.valueOf(i), Double[][]::new, Double[]::new); + } + + public static Float[][] stringToWrapperFloatArrays(String string) { + return stringToArrays(string, i -> Float.valueOf(i), Float[][]::new, Float[]::new); + } + + public static Integer[][] stringToWrapperIntArrays(String string) { + return stringToArrays(string, i -> Integer.valueOf(i), Integer[][]::new, Integer[]::new); + } + + public static Long[][] stringToWrapperLongArrays(String string) { + return stringToArrays(string, i -> Long.valueOf(i), Long[][]::new, Long[]::new); + } + + public static Short[][] stringToWrapperShortArrays(String string) { + return stringToArrays(string, i -> Short.valueOf(i), Short[][]::new, Short[]::new); + } + + public static String[][] stringToStringArrays(String string) { + return stringToArrays(string, i -> i, String[][]::new, String[]::new); + } + + public static T[] stringToArray( + String string, Function converter, IntFunction newer) { + String[] strs = string.split(","); + T[] array = newer.apply(strs.length); + for(int i = 0 ; i < strs.length ; i++) + array[i] = converter.apply(strs[i]); + return array; + } + + public static T[][] stringToArrays( + String string, Function converter, IntFunction newer1, IntFunction newer2) { + String[] strs = string.split(";"); + T[][] arrays = newer1.apply(strs.length); + for(int i = 0 ; i < strs.length ; i++) + arrays[i] = stringToArray(strs[i], converter, newer2); + return arrays; + } + + public static char stringToChar(String string) { + if(string.length() == 1) + return string.charAt(0); + throw new IllegalArgumentException("can't convert string " + string + " to char value"); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java new file mode 100644 index 00000000..3c7c3ec5 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyStrings.java @@ -0,0 +1,48 @@ +package com.tvd12.ezyfoxserver.io; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; + +public final class EzyStrings { + + private EzyStrings() { + } + + public static String newUtf(byte[] bytes) { + return newString(bytes, "UTF-8"); + } + + public static String newUtf(ByteBuffer buffer, int size) { + return newString(buffer, size, "UTF-8"); + } + + public static byte[] getUtfBytes(String str) { + return getBytes(str, "UTF-8"); + } + + public static String newString(byte[] bytes, String charset) { + try { + return new String(bytes, charset); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e); + } + } + + public static byte[] getBytes(String str, String charset) { + try { + return str.getBytes(charset); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e); + } + } + + public static String newString(ByteBuffer buffer, int size, String charset) { + byte[] bytes = new byte[size]; + buffer.get(bytes); + return newString(bytes, charset); + } + + public static String getString(String[] array, int index, String def) { + return array.length > index ? array[index] : def; + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyValueConverter.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyValueConverter.java new file mode 100644 index 00000000..8001fedb --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/io/EzyValueConverter.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.io; + +public interface EzyValueConverter { + + T convert(Object value, Class outType); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzyPropertiesReader.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzyPropertiesReader.java new file mode 100644 index 00000000..6032911e --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzyPropertiesReader.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.properties; + +import java.util.Map; + +@SuppressWarnings("rawtypes") +public interface EzyPropertiesReader { + + T get(Map properties, Object key); + + T get(Map properties, Object key, T defValue); + + T get(Map properties, Object key, Class outType); + + T get(Map properties, Object key, Class outType, T defValue); + + boolean containsKey(Map properties, Object key); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzySimplePropertiesReader.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzySimplePropertiesReader.java new file mode 100644 index 00000000..614f39a9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/properties/EzySimplePropertiesReader.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.properties; + +import java.util.Map; + +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class EzySimplePropertiesReader + extends EzyLoggable + implements EzyPropertiesReader { + + protected final EzyValueConverter conveter; + + public EzySimplePropertiesReader() { + this(new EzySimpleValueConverter()); + } + + public EzySimplePropertiesReader(EzyValueConverter conveter) { + this.conveter = conveter; + } + + @Override + public T get(Map properties, Object key) { + return (T) properties.get(key); + } + + @Override + public T get(Map properties, Object key, Class outType) { + return conveter.convert(get(properties, key), outType); + } + + @Override + public T get(Map properties, Object key, T defValue) { + return containsKey(properties, key) ? get(properties, key) : defValue; + } + + @Override + public T get(Map properties, Object key, Class outType, T defValue) { + return containsKey(properties, key) ? get(properties, key, outType) : defValue; + } + + @Override + public boolean containsKey(Map properties, Object key) { + return properties.containsKey(key); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyAnnotatedElement.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyAnnotatedElement.java new file mode 100644 index 00000000..1745acdf --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyAnnotatedElement.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; + +public interface EzyAnnotatedElement { + + T getAnnotation(Class annClass); + + boolean isAnnotated(Class annClass); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyByFieldMethod.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyByFieldMethod.java new file mode 100644 index 00000000..24879886 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyByFieldMethod.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.Map; + +public abstract class EzyByFieldMethod + extends EzyMethod + implements EzyGenericElement, EzyKnownTypeElement { + + public EzyByFieldMethod(Method method) { + super(method); + } + + public String getFieldName() { + String name = method.getName(); + name = name.substring(3); + return name.substring(0, 1).toLowerCase() + name.substring(1); + } + + public boolean isMapType() { + return Map.class.isAssignableFrom(getType()); + } + + public boolean isCollection() { + return Collection.class.isAssignableFrom(getType()); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClass.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClass.java new file mode 100644 index 00000000..084cbfbd --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClass.java @@ -0,0 +1,200 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.util.EzyReturner; + +import lombok.Getter; + +@SuppressWarnings("rawtypes") +@Getter +public class EzyClass implements EzyReflectElement { + + protected final Class clazz; + protected final List fields; + protected final List methods; + protected final List declaredFields; + protected final List declaredMethods; + protected final Map fieldsByName; + protected final Map methodsByName; + + public EzyClass(Class clazz) { + this.clazz = clazz; + this.methods = newMethods(clazz); + this.fields = newFields(clazz); + this.declaredFields = newDeclaredFields(clazz); + this.declaredMethods = newDeclaredMethods(clazz); + this.fieldsByName = mapFieldsByName(); + this.methodsByName = mapMethodsByName(); + } + + @SuppressWarnings("unchecked") + public T newInstance() { + return (T) EzyClasses.newInstance(clazz); + } + + @Override + public String getName() { + return clazz.getName(); + } + + public int getModifiers() { + return clazz.getModifiers(); + } + + public EzyField getField(String name) { + return fieldsByName.get(name); + } + + public EzyMethod getMethod(String name) { + return methodsByName.get(name); + } + + @SuppressWarnings("unchecked") + @Override + public boolean isAnnotated(Class annClass) { + return clazz.isAnnotationPresent(annClass); + } + + @SuppressWarnings("unchecked") + @Override + public T getAnnotation(Class annClass) { + return (T) clazz.getAnnotation(annClass); + } + + public List getDeclaredConstructors() { + return Lists.newArrayList(clazz.getDeclaredConstructors()); + } + + @SuppressWarnings("unchecked") + public Constructor getDeclaredConstructor(Class... parameterTypes) { + return EzyReturner.returnWithIllegalArgumentException( + () -> clazz.getDeclaredConstructor(parameterTypes)); + } + + public List getPublicMethods() { + return getMethods(m -> m.isPublic()); + } + + public List getSetterMethods() { + return getMethods(m -> m.isSetter(), EzySetterMethod::new); + } + + public List getGetterMethods() { + return getMethods(m -> m.isGetter(), EzyGetterMethod::new); + } + + public List getPublicMethods(Predicate predicate) { + return getMethods(m -> m.isPublic() && predicate.test(m)); + } + + public List getSetterMethods(Predicate predicate) { + return getSetterMethods().stream() + .filter(predicate).collect(Collectors.toList()); + } + + public List getGetterMethods(Predicate predicate) { + return getGetterMethods().stream() + .filter(predicate).collect(Collectors.toList()); + } + + public List getMethods(Predicate predicate) { + return methods.stream().filter(predicate).collect(Collectors.toList()); + } + + public List getWritableFields() { + return getFields(f -> f.isWritable()); + } + + public List getPublicFields() { + return getFields(f -> f.isPublic()); + } + + public List getPublicFields(Predicate predicate) { + return getFields(f -> f.isPublic() && predicate.test(f)); + } + + public List getFields(Predicate predicate) { + return fields.stream().filter(predicate).collect(Collectors.toList()); + } + + public List getMethods( + Predicate predicate, Function creator) { + return methods.stream() + .filter(predicate) + .flatMap(m -> Stream.of(creator.apply(m))) + .collect(Collectors.toList()); + } + + public List getDeclaredSetterMethods() { + return getDeclaredMethods(m -> m.isSetter(), EzySetterMethod::new); + } + + public List getDeclaredGetterMethods() { + return getDeclaredMethods(m -> m.isGetter(), EzyGetterMethod::new); + } + + public List getDeclaredMethods( + Predicate predicate, Function creator) { + return declaredMethods.stream() + .filter(predicate) + .flatMap(m -> Stream.of(creator.apply(m))) + .collect(Collectors.toList()); + } + + public List getDeclaredMethods(Predicate predicate) { + return declaredMethods.stream().filter(predicate).collect(Collectors.toList()); + } + + private List newFields(Class clazz) { + List answer = new ArrayList<>(); + EzyFields.getFields(clazz).forEach(f -> answer.add(new EzyField(f))); + return answer; + } + + private List newMethods(Class clazz) { + List answer = new ArrayList<>(); + EzyMethods.getMethods(clazz).forEach(m -> answer.add(new EzyMethod(m))); + return answer; + } + + private List newDeclaredFields(Class clazz) { + List answer = new ArrayList<>(); + EzyFields.getDeclaredFields(clazz).forEach(f -> answer.add(new EzyField(f))); + return answer; + } + + private List newDeclaredMethods(Class clazz) { + List answer = new ArrayList<>(); + EzyMethods.getDeclaredMethods(clazz).forEach(m -> answer.add(new EzyMethod(m))); + return answer; + } + + private Map mapFieldsByName() { + Map map = new HashMap<>(); + fields.forEach(f -> map.put(f.getName(), f)); + return map; + } + + private Map mapMethodsByName() { + Map map = new HashMap<>(); + methods.forEach(m -> map.put(m.getName(), m)); + return map; + } + + @Override + public String toString() { + return clazz.toString(); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClasses.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClasses.java new file mode 100644 index 00000000..14705103 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyClasses.java @@ -0,0 +1,130 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Constructor; +import java.util.HashSet; +import java.util.Set; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.util.EzyReturner; + +public final class EzyClasses { + + private static final String DOT = "."; + + private EzyClasses() { + } + + @SuppressWarnings("rawtypes") + public static String getSimpleName(Class clazz) { + String simpleName = clazz.getSimpleName(); + if(!simpleName.isEmpty()) return simpleName; + String fullName = clazz.getName(); + if(!fullName.contains(DOT)) return fullName; + return fullName.substring(fullName.lastIndexOf(DOT) + 1); + } + + @SuppressWarnings("rawtypes") + public static String getVariableName(Class clazz) { + return getVariableName(clazz, ""); + } + + @SuppressWarnings("rawtypes") + public static String getVariableName(Class clazz, String ignoredSuffix) { + String name = getSimpleName(clazz); + String vname = name.substring(0, 1).toLowerCase() + name.substring(1); + if(ignoredSuffix.isEmpty() + || !vname.endsWith(ignoredSuffix) + || vname.length() == ignoredSuffix.length()) + return vname; + int endIndex = vname.indexOf(ignoredSuffix); + return vname.substring(0, endIndex); + + } + + @SuppressWarnings("unchecked") + public static T newInstance(String className) { + return EzyReturner.returnWithIllegalArgumentException( + () -> (T) getClass(className).newInstance()); + } + + @SuppressWarnings("unchecked") + public static T newInstance(String className, ClassLoader classLoader) { + return EzyReturner.returnWithIllegalArgumentException( + () -> (T) getClass(className, classLoader).newInstance()); + } + + @SuppressWarnings("rawtypes") + public static Class getClass(String className) { + return EzyReturner.returnWithIllegalArgumentException( + () -> Class.forName(className)); + } + + @SuppressWarnings("rawtypes") + public static Class getClass(String className, ClassLoader classLoader) { + return EzyReturner.returnWithIllegalArgumentException( + () -> Class.forName(className, true, classLoader)); + } + + public static T newInstance(Class clazz) { + return EzyReturner.returnWithIllegalArgumentException( + () -> clazz.newInstance()); + } + + public static T newInstance(Constructor constructor, Object... arguments) { + return EzyReturner.returnWithIllegalArgumentException( + () -> constructor.newInstance(arguments)); + } + + public static Constructor getConstructor(Class clazz, Class... paramTypes) { + return EzyReturner.returnWithIllegalArgumentException( + () -> clazz.getDeclaredConstructor(paramTypes)); + } + + @SuppressWarnings("rawtypes") + public static Set flatSuperClasses(Class clazz) { + return flatSuperClasses(clazz, false); + } + + @SuppressWarnings("rawtypes") + public static Set flatSuperClasses(Class clazz, boolean includeObject) { + Set classes = new HashSet<>(); + Class superClass = clazz.getSuperclass(); + while(superClass != null) { + if(superClass.equals(Object.class) && !includeObject ) + break; + classes.add(superClass); + superClass = superClass.getSuperclass(); + } + return classes; + } + + @SuppressWarnings("rawtypes") + public static Set flatInterfaces(Class clazz) { + Set classes = new HashSet<>(); + Class[] interfaces = clazz.getInterfaces(); + classes.addAll(Sets.newHashSet(interfaces)); + for(Class itf : interfaces) + classes.addAll(flatInterfaces(itf)); + return classes; + } + + @SuppressWarnings("rawtypes") + public static Set flatSuperAndInterfaceClasses(Class clazz) { + return flatSuperAndInterfaceClasses(clazz, false); + } + + @SuppressWarnings("rawtypes") + public static Set flatSuperAndInterfaceClasses(Class clazz, boolean includeObject) { + Set classes = new HashSet<>(); + Set interfaces = flatInterfaces(clazz); + Set superClasses = flatSuperClasses(clazz, includeObject); + classes.addAll(interfaces); + for(Class superClass : superClasses) { + Set superAndInterfaceClasses = flatSuperAndInterfaceClasses(superClass, includeObject); + classes.add(superClass); + classes.addAll(superAndInterfaceClasses); + } + return classes; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyField.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyField.java new file mode 100644 index 00000000..d67039e3 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyField.java @@ -0,0 +1,139 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; + +import lombok.Getter; + +public class EzyField + implements EzyReflectElement, EzyGenericElement, EzyKnownTypeElement { + + @Getter + protected final Field field; + + public EzyField(Field field) { + this.field = field; + } + + public Object get(Object obj) { + return EzyFields.get(field, obj); + } + + public void set(Object obj, Object value) { + EzyFields.set(field, obj, value); + } + + @Override + public String getName() { + return field.getName(); + } + + public boolean isPublic() { + return Modifier.isPublic(field.getModifiers()); + } + + public boolean isWritable() { + return !Modifier.isFinal(field.getModifiers()); + } + + public boolean isMapType() { + return Map.class.isAssignableFrom(getType()); + } + + public boolean isCollection() { + return Collection.class.isAssignableFrom(getType()); + } + + @SuppressWarnings("rawtypes") + @Override + public Class getType() { + return field.getType(); + } + + public String getGetterMethod() { + return "get" + getMethodSuffix(); + } + + public String getSetterMethod() { + return "set" + getMethodSuffix(); + } + + protected String getMethodSuffix() { + String name = getName(); + String first = name.substring(0, 1).toUpperCase(); + return name.length() == 1 ? first : first + name.substring(1); + } + + @Override + public Type getGenericType() { + return field.getGenericType(); + } + + @Override + public T getAnnotation(Class annClass) { + return field.getAnnotation(annClass); + } + + @Override + public boolean isAnnotated(Class annClass) { + return field.isAnnotationPresent(annClass); + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(f -> f.field) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .append(field) + .toHashCode(); + } + + @Override + public String toString() { + return field.toString(); + } + + public static Builder builder() { + return new Builder(); + } + + @SuppressWarnings("rawtypes") + public static class Builder implements EzyBuilder { + protected Class clazz; + protected String fieldName; + + public Builder clazz(Class clazz) { + this.clazz = clazz; + return this; + } + + public Builder fieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + @Override + public EzyField build() { + return new EzyField(getField()); + } + + protected Field getField() { + return EzyFields.getField(clazz, fieldName); + } + + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFieldFinder.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFieldFinder.java new file mode 100644 index 00000000..ab666fac --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFieldFinder.java @@ -0,0 +1,72 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Field; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +import lombok.AllArgsConstructor; + +@SuppressWarnings("rawtypes") +@AllArgsConstructor +public class EzyFieldFinder { + protected Class clazz; + protected String fieldName; + + public Field find() { + return getField(clazz); + } + + protected Field getField(Class clazz) { + Field field = tryGetField(clazz); + if(field != null) + return field; + Class[] interfaces = getInterfaces(clazz); + for(Class itf : interfaces) { + field = getField(itf); + if(field != null) + return field; + } + Class superClass = getSupperClasses(clazz); + return superClass != null ? getField(superClass) : null; + } + + protected Field tryGetField(Class clazz) { + try { + return clazz.getDeclaredField(fieldName); + } catch (Exception e) { + return null; + } + } + + protected Class getSupperClasses(Class clazz) { + return clazz.getSuperclass(); + } + + protected Class[] getInterfaces(Class clazz) { + return clazz.getInterfaces(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected Class clazz; + protected String fieldName; + + public Builder clazz(Class clazz) { + this.clazz = clazz; + return this; + } + public Builder fieldName(String fieldName) { + this.fieldName = fieldName; + return this; + } + + @Override + public EzyFieldFinder build() { + return new EzyFieldFinder(clazz, fieldName); + } + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFields.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFields.java new file mode 100644 index 00000000..08f7ccfd --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyFields.java @@ -0,0 +1,55 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.List; + +import org.apache.commons.lang3.reflect.FieldUtils; + +import com.google.common.collect.Lists; + +public final class EzyFields { + + private EzyFields() { + } + + public static Object get(Field field, Object obj) { + try { + return field.get(obj); + } + catch(Exception e) { + throw new IllegalArgumentException("can't get value from field " + field.getName(), e); + } + } + + public static void set(Field field, Object obj, Object value) { + try { + field.set(obj, value); + } + catch(Exception e) { + throw new IllegalArgumentException("can't set value to field " + field.getName(), e); + } + } + + @SuppressWarnings("rawtypes") + public static List getFields(Class clazz) { + return Lists.newArrayList(FieldUtils.getAllFields(clazz)); + } + + @SuppressWarnings("rawtypes") + public static Field getField(Class clazz, String fieldName) { + return new EzyFieldFinder(clazz, fieldName).find(); + } + + @SuppressWarnings("rawtypes") + public static List getAnnotatedFields( + Class clazz, Class annClass) { + return FieldUtils.getFieldsListWithAnnotation(clazz, annClass); + } + + @SuppressWarnings("rawtypes") + public static List getDeclaredFields(Class clazz) { + return Lists.newArrayList(clazz.getDeclaredFields()); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericElement.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericElement.java new file mode 100644 index 00000000..c8cc7da9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericElement.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Type; + +public interface EzyGenericElement { + + Type getGenericType(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericSetterValidator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericSetterValidator.java new file mode 100644 index 00000000..f4a7070d --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenericSetterValidator.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; +import java.util.Set; + +import com.tvd12.ezyfoxserver.function.EzyValidator; + +public class EzyGenericSetterValidator implements EzyValidator { + + @Override + public boolean validate(Type genericType) { + if(genericType instanceof WildcardType) + return false; + if(genericType instanceof Class) + return validateClassType(genericType); + if(genericType instanceof ParameterizedType) + return validate((ParameterizedType)genericType); + return false; + } + + protected boolean validate(ParameterizedType parameterizedType) { + Type[] types = parameterizedType.getActualTypeArguments(); + for(Type type : types) { + if(!validate(type)) + return false; + } + return true; + } + + protected boolean validateClassType(Type classType) { + return !getCommonGenericTypes().contains(classType); + } + + @SuppressWarnings("rawtypes") + protected Set getCommonGenericTypes() { + return EzyTypes.COMMON_GENERIC_TYPES; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenerics.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenerics.java new file mode 100644 index 00000000..356076d4 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGenerics.java @@ -0,0 +1,69 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +public final class EzyGenerics { + + private EzyGenerics() { + } + + @SuppressWarnings("rawtypes") + public static Class getOneGenericClassArgument(Type genericType) { + return getGenericClassArguments(genericType, 1)[0]; + } + + @SuppressWarnings("rawtypes") + public static Class[] getTwoGenericClassArguments(Type genericType) { + return getGenericClassArguments(genericType, 2); + } + + @SuppressWarnings("rawtypes") + public static Class[] getGenericClassArguments(Type genericType, int size) { + if (!(genericType instanceof ParameterizedType)) + throw new IllegalArgumentException("1: " + genericType.getTypeName() + " is not generic type"); + List answer = new ArrayList<>(); + Type[] types = ((ParameterizedType)genericType).getActualTypeArguments(); + if(types.length != size) + throw new IllegalArgumentException("2: " + genericType.getTypeName() + " has != " + size + " generic argument"); + for(Type type : types) { + if(type instanceof Class) + answer.add((Class)type); + else if(type instanceof ParameterizedType) + answer.add((Class)((ParameterizedType)type).getRawType()); + else + throw new IllegalArgumentException("3: unknown generic argument type of " + genericType.getTypeName()); + } + return answer.toArray(new Class[answer.size()]); + } + + @SuppressWarnings("rawtypes") + public static Class[] getGenericInterfacesArguments(Class clazz, Class interfaceClass, int size) { + Type[] genericInterfaces = clazz.getGenericInterfaces(); + for (Type genericInterface : genericInterfaces) { + if (!(genericInterface instanceof ParameterizedType)) + continue; + ParameterizedType parameterizedType = (ParameterizedType) genericInterface; + if(!parameterizedType.getRawType().equals(interfaceClass)) + continue; + Type[] genericTypes = parameterizedType.getActualTypeArguments(); + if(genericTypes.length != size) + throw new IllegalArgumentException("1:" + genericInterface.getTypeName() + " has != " + size + " generic argument"); + List answer = new ArrayList<>(); + for (Type genericType : genericTypes) { + if(genericType instanceof Class) + answer.add((Class)genericType); + else if(genericType instanceof ParameterizedType) + answer.add((Class)((ParameterizedType)genericType).getRawType()); + else + throw new IllegalArgumentException("2: unknown generic argument type of " + genericType.getTypeName()); + } + return answer.toArray(new Class[answer.size()]); + } + if(EzyInterfaces.getInterface(clazz, interfaceClass) != null) + throw new IllegalArgumentException("3: " + interfaceClass + " is not generics"); + throw new IllegalArgumentException("4: " + clazz + " is not extends/implements " + interfaceClass); + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGetterMethod.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGetterMethod.java new file mode 100644 index 00000000..ef6f3637 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyGetterMethod.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +public class EzyGetterMethod extends EzyByFieldMethod { + + public EzyGetterMethod(Method method) { + this(new EzyMethod(method)); + } + + public EzyGetterMethod(EzyMethod method) { + super(method.getMethod()); + } + + @SuppressWarnings("rawtypes") + @Override + public Class getType() { + return getReturnType(); + } + + @Override + public Type getGenericType() { + return getGenericReturnType(); + } + + @Override + public String getFieldName() { + String name = method.getName(); + if(name.length() <= 3) + return name; + if(name.startsWith("get")) + return super.getFieldName(); + return name; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyInterfaces.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyInterfaces.java new file mode 100644 index 00000000..7e10edad --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyInterfaces.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.util.Set; + +public final class EzyInterfaces { + + private EzyInterfaces() { + } + + @SuppressWarnings("rawtypes") + public static Class getInterface(Class clazz, Class interfaceClass) { + Set interfaces = EzyClasses.flatInterfaces(clazz); + for(Class itf : interfaces) { + if(itf.equals(interfaceClass)) + return itf; + } + return null; + + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownNameElement.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownNameElement.java new file mode 100644 index 00000000..2a90096a --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownNameElement.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.reflect; + +public interface EzyKnownNameElement { + + String getName(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownTypeElement.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownTypeElement.java new file mode 100644 index 00000000..65e6536f --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyKnownTypeElement.java @@ -0,0 +1,12 @@ +package com.tvd12.ezyfoxserver.reflect; + +public interface EzyKnownTypeElement { + + @SuppressWarnings("rawtypes") + Class getType(); + + default String getTypeName() { + return getType().getTypeName(); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethod.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethod.java new file mode 100644 index 00000000..2ac424d2 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethod.java @@ -0,0 +1,188 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.Parameter; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; + +import lombok.Getter; +import lombok.Setter; + +@Getter +public class EzyMethod implements EzyReflectElement { + + protected final Method method; + + @Setter + protected String displayName; + + public EzyMethod(Method method) { + this.method = method; + this.displayName = method.getName(); + } + + public Object invoke(Object obj, Object... args) { + return EzyMethods.invoke(method, obj, args); + } + + @Override + public String getName() { + return method.getName(); + } + + public boolean isSetter() { + return isPublic() && + method.getName().startsWith("set") && + method.getParameterCount() == 1; + } + + public boolean isGetter() { + return isPublic() && + method.getName().startsWith("get") && + method.getParameterCount() == 0 && + method.getReturnType() != void.class; + } + + public boolean isPublic() { + return Modifier.isPublic(method.getModifiers()); + } + + @SuppressWarnings("rawtypes") + public Class getReturnType() { + return method.getReturnType(); + } + + public Type getGenericReturnType() { + return method.getGenericReturnType(); + } + + @SuppressWarnings("rawtypes") + public Class[] getParameterTypes() { + return method.getParameterTypes(); + } + + public int getParameterCount() { + return method.getParameterCount(); + } + + public Type[] getGenericParameterTypes() { + return method.getGenericParameterTypes(); + } + + @Override + public T getAnnotation(Class annClass) { + return method.getAnnotation(annClass); + } + + @Override + public boolean isAnnotated(Class annClass) { + return method.isAnnotationPresent(annClass); + } + + public String getFieldName() { + String name = getName(); + if(!name.startsWith("set") && !name.startsWith("get") && !name.startsWith("new")) + return name; + if(name.length() <= 3) + return name; + String remain = name.substring(3); + return remain.substring(0, 1).toLowerCase() + remain.substring(1); + } + + public String getDeclaration() { + int modifiers = method.getModifiers(); + return getDeclaration(Modifier.toString(modifiers)); + } + + public String getPublicDeclaration() { + return getDeclaration("public"); + } + + public String getDeclaration(String modifierName) { + Parameter[] params = method.getParameters(); + Class returnType = method.getReturnType(); + StringBuilder builder = new StringBuilder(); + builder + .append(modifierName) + .append(" ") + .append(returnType.getTypeName()) + .append(" ") + .append(displayName) + .append("("); + for(int i = 0 ; i < params.length ; i++) { + builder.append(params[i].getType().getTypeName()) + .append(" ") + .append(params[i].getName()); + if(i < params.length - 1) + builder.append(", "); + } + builder.append(")"); + return builder.toString(); + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(m -> m.method) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .append(method) + .toHashCode(); + } + + @Override + public String toString() { + return method.toString(); + } + + public static Builder builder() { + return new Builder(); + } + + @SuppressWarnings("rawtypes") + public static class Builder implements EzyBuilder { + protected Class clazz; + protected String methodName; + protected List parameterTypes = new ArrayList<>(); + + public Builder clazz(Class clazz) { + this.clazz = clazz; + return this; + } + + public Builder methodName(String methodName) { + this.methodName = methodName; + return this; + } + + public Builder parameterTypes(Class... parameterTypes) { + this.parameterTypes.addAll(Lists.newArrayList(parameterTypes)); + return this; + } + + @Override + public EzyMethod build() { + return new EzyMethod(getMethod()); + } + + protected Method getMethod() { + return EzyMethods.getMethod(clazz, methodName, getParameterTypes()); + } + + protected Class[] getParameterTypes() { + return parameterTypes.toArray(new Class[parameterTypes.size()]); + } + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethodFinder.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethodFinder.java new file mode 100644 index 00000000..eec94349 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethodFinder.java @@ -0,0 +1,86 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +import lombok.AllArgsConstructor; + +@SuppressWarnings("rawtypes") +@AllArgsConstructor +public class EzyMethodFinder { + protected Class clazz; + protected String methodName; + protected Class[] parameterTypes; + + public Method find() { + return getMethod(clazz); + } + + protected Method getMethod(Class clazz) { + Method method = tryGetMethod(clazz); + if(method != null) + return method; + Class[] interfaces = getInterfaces(clazz); + for(Class itf : interfaces) { + method = getMethod(itf); + if(method != null) + return method; + } + Class superClass = getSupperClasses(clazz); + return superClass != null ? getMethod(superClass) : null; + } + + @SuppressWarnings({ "unchecked" }) + protected Method tryGetMethod(Class clazz) { + try { + return clazz.getDeclaredMethod(methodName, parameterTypes); + } catch (Exception e) { + return null; + } + } + + protected Class getSupperClasses(Class clazz) { + return clazz.getSuperclass(); + } + + protected Class[] getInterfaces(Class clazz) { + return clazz.getInterfaces(); + } + + public static Builder builder() { + return new Builder(); + } + + public static class Builder implements EzyBuilder { + protected Class clazz; + protected String methodName; + protected List parameterTypes = new ArrayList<>(); + + public Builder clazz(Class clazz) { + this.clazz = clazz; + return this; + } + public Builder methodName(String methodName) { + this.methodName = methodName; + return this; + } + + public Builder parameterTypes(Class... parameterTypes) { + this.parameterTypes.addAll(Lists.newArrayList(parameterTypes)); + return this; + } + + @Override + public EzyMethodFinder build() { + return new EzyMethodFinder( + clazz, + methodName, + parameterTypes.toArray(new Class[parameterTypes.size()])); + } + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethods.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethods.java new file mode 100644 index 00000000..3031f32b --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyMethods.java @@ -0,0 +1,54 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.reflect.MethodUtils; +import org.reflections.ReflectionUtils; + +import com.google.common.collect.Lists; + +public final class EzyMethods { + + private EzyMethods() { + } + + public static Object invoke(Method method, Object obj, Object... args) { + try { + return method.invoke(obj, args); + } + catch(Exception e) { + throw new IllegalArgumentException("can not call method " + method.getName(), e); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static List getMethods(Class clazz) { + return new ArrayList<>(ReflectionUtils.getAllMethods(clazz)); + } + + @SuppressWarnings("rawtypes") + public static Method getMethod( + Class clazz, String methodName, Class... parameterTypes) { + return new EzyMethodFinder(clazz, methodName, parameterTypes).find(); + } + + @SuppressWarnings("rawtypes") + public static Method getPublicMethod( + Class clazz, String methodName, Class... parameterTypes) { + return MethodUtils.getAccessibleMethod(clazz, methodName, parameterTypes); + } + + @SuppressWarnings("rawtypes") + public static List getAnnotatedMethods( + Class clazz, Class annClass) { + return MethodUtils.getMethodsListWithAnnotation(clazz, annClass); + } + + @SuppressWarnings("rawtypes") + public static List getDeclaredMethods(Class clazz) { + return Lists.newArrayList(clazz.getDeclaredMethods()); + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyPackages.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyPackages.java new file mode 100644 index 00000000..e756d509 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyPackages.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.annotation.Annotation; +import java.util.Set; +import java.util.function.Function; + +import org.reflections.Reflections; +import org.reflections.util.Utils; + +public final class EzyPackages { + + public static Set> getAnnotatedClasses( + String packageName, Class annClass) { + return scanPackage(packageName, ref -> ref.getTypesAnnotatedWith(annClass)); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static Set> getExtendsClasses(String packageName, Class superClass) { + return scanPackage(packageName, ref -> ref.getSubTypesOf(superClass)); + } + + private static Set> + scanPackage(String packageName, Function>> function) { + Reflections.log = null; + Reflections reflections = new Reflections(packageName); + Set> classes = function.apply(reflections); + Reflections.log = Utils.findLogger(Reflections.class); + return classes; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyReflectElement.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyReflectElement.java new file mode 100644 index 00000000..8497045c --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyReflectElement.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.reflect; + +public interface EzyReflectElement extends EzyKnownNameElement, EzyAnnotatedElement { + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzySetterMethod.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzySetterMethod.java new file mode 100644 index 00000000..d77669b7 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzySetterMethod.java @@ -0,0 +1,37 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.lang.reflect.Method; +import java.lang.reflect.Type; + +public class EzySetterMethod extends EzyByFieldMethod { + + public EzySetterMethod(Method method) { + this(new EzyMethod(method)); + } + + public EzySetterMethod(EzyMethod method) { + super(method.getMethod()); + } + + @SuppressWarnings("rawtypes") + @Override + public Class getType() { + return getParameterTypes()[0]; + } + + @Override + public Type getGenericType() { + return getGenericParameterTypes()[0]; + } + + @Override + public String getFieldName() { + String name = method.getName(); + if(name.length() <= 3) + return name; + if(name.startsWith("set")) + return super.getFieldName(); + return name; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyTypes.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyTypes.java new file mode 100644 index 00000000..484fe81f --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/reflect/EzyTypes.java @@ -0,0 +1,179 @@ +package com.tvd12.ezyfoxserver.reflect; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.TreeMap; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +@SuppressWarnings("rawtypes") +public final class EzyTypes { + + public static final Set PRIMITIVE_TYPES = primitiveTypes(); + public static final Set WRAPPER_TYPES = wrapperTypes(); + public static final Set ARRAY_PRIMITIVE_TYPES = arrayPrimitiveTypes(); + public static final Set ARRAY_WRAPPER_TYPES = arrayWrapperTypes(); + public static final Set TWO_DIMENSIONS_ARRAY_PRIMITIVE_TYPES = twoDimensionsArrayPrimitiveTypes(); + public static final Set TWO_DIMENSIONS_ARRAY_WRAPPER_TYPES = twoDimensionsArrayWrapperTypes(); + public static final Set STRING_TYPES = stringTypes(); + public static final Set ALL_TYPES = mergeAllTypes(); + public static final Set COMMON_GENERIC_TYPES = commonGenericTypes(); + public static final Map PRIMITIVE_WRAPPER_TYPES_MAP = mapPrimitiveAndWrapperTypes(); + + private EzyTypes() { + } + + private static final Set primitiveTypes() { + Set set = Sets.newHashSet( + boolean.class, + byte.class, + char.class, + double.class, + float.class, + int.class, + long.class, + short.class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set wrapperTypes() { + Set set = Sets.newHashSet( + Boolean.class, + Byte.class, + Character.class, + Double.class, + Float.class, + Integer.class, + Long.class, + Short.class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set arrayPrimitiveTypes() { + Set set = Sets.newHashSet( + boolean[].class, + byte[].class, + char[].class, + double[].class, + float[].class, + int[].class, + long[].class, + short[].class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set arrayWrapperTypes() { + Set set = Sets.newHashSet( + Boolean[].class, + Byte[].class, + Character[].class, + Double[].class, + Float[].class, + Integer[].class, + Long[].class, + Short[].class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set twoDimensionsArrayPrimitiveTypes() { + Set set = Sets.newHashSet( + boolean[][].class, + byte[][].class, + char[][].class, + double[][].class, + float[][].class, + int[][].class, + long[][].class, + short[][].class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set twoDimensionsArrayWrapperTypes() { + Set set = Sets.newHashSet( + Boolean[][].class, + Byte[][].class, + Character[][].class, + Double[][].class, + Float[][].class, + Integer[][].class, + Long[][].class, + Short[][].class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set stringTypes() { + Set set = Sets.newHashSet( + String.class, + String[].class, + String[][].class + ); + return Collections.unmodifiableSet(set); + } + + private static final Set mergeAllTypes() { + Set merge = new HashSet<>(); + merge.addAll(Lists.newArrayList(PRIMITIVE_TYPES)); + merge.addAll(Lists.newArrayList(WRAPPER_TYPES)); + merge.addAll(Lists.newArrayList(ARRAY_PRIMITIVE_TYPES)); + merge.addAll(Lists.newArrayList(ARRAY_WRAPPER_TYPES)); + merge.addAll(Lists.newArrayList(TWO_DIMENSIONS_ARRAY_PRIMITIVE_TYPES)); + merge.addAll(Lists.newArrayList(TWO_DIMENSIONS_ARRAY_WRAPPER_TYPES)); + merge.addAll(Lists.newArrayList(STRING_TYPES)); + return Collections.unmodifiableSet(merge); + } + + private static final Map mapPrimitiveAndWrapperTypes() { + Map map = new ConcurrentHashMap<>(); + map.put(boolean.class, Boolean.class); + map.put(byte.class, Byte.class); + map.put(char.class, Character.class); + map.put(double.class, Double.class); + map.put(float.class, Float.class); + map.put(int.class, Integer.class); + map.put(long.class, Long.class); + map.put(short.class, Short.class); + return Collections.unmodifiableMap(map); + } + + private static final Set commonGenericTypes() { + Set set = Sets.newHashSet( + Collection.class, + List.class, + ArrayList.class, + CopyOnWriteArrayList.class, + LinkedList.class, + Set.class, + HashSet.class, + CopyOnWriteArraySet.class, + Vector.class, + Stack.class, + Queue.class, + Map.class, + HashMap.class, + TreeMap.class, + ConcurrentHashMap.class + ); + return Collections.unmodifiableSet(set); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyArrayIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyArrayIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyArrayIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyArrayIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyAutoImplAnnotations.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyAutoImplAnnotations.java new file mode 100644 index 00000000..390a70a6 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyAutoImplAnnotations.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.util; + +import org.apache.commons.lang3.StringUtils; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; + +public final class EzyAutoImplAnnotations { + + private EzyAutoImplAnnotations() { + } + + public static String getBeanName(Class annotatedClass) { + EzyAutoImpl anno = annotatedClass.getAnnotation(EzyAutoImpl.class); + String beanName = anno.value().trim(); + if(!StringUtils.isEmpty(beanName)) + return beanName; + beanName = EzyKeyValueAnnotations.getProperty("name", anno.properties()); + if(!StringUtils.isEmpty(beanName)) + return beanName; + return EzyClasses.getVariableName(annotatedClass); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyBoolsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyBoolsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyBoolsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyBoolsIterator.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyBytesIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyBytesIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyBytesIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyBytesIterator.java diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyCharsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCharsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyCharsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCharsIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCloseable.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCloseable.java new file mode 100644 index 00000000..465d9dcf --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCloseable.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.util; + +import java.io.Closeable; + +public interface EzyCloseable extends Closeable { +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionFactory.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionFactory.java new file mode 100644 index 00000000..77ee3adf --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyCollectionFactory.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.Vector; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.function.Supplier; + +public class EzyCollectionFactory { + + @SuppressWarnings("rawtypes") + protected final Map> suppliers = defaultSuppliers(); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public T newCollection(Class collectionType) { + if(suppliers.containsKey(collectionType)) + return (T) suppliers.get(collectionType).get(); + throw new IllegalArgumentException("unknown implementation of " + collectionType); + } + + @SuppressWarnings("rawtypes") + private Map> defaultSuppliers() { + Map> map = new ConcurrentHashMap<>(); + map.put(Collection.class, () -> new ArrayList<>()); + map.put(List.class, () -> new ArrayList<>()); + map.put(ArrayList.class, () -> new ArrayList<>()); + map.put(LinkedList.class, () -> new LinkedList<>()); + map.put(CopyOnWriteArrayList.class, () -> new CopyOnWriteArrayList<>()); + map.put(Set.class, () -> new HashSet<>()); + map.put(HashSet.class, () -> new HashSet<>()); + map.put(LinkedHashSet.class, () -> new LinkedHashSet<>()); + map.put(CopyOnWriteArraySet.class, () -> new CopyOnWriteArraySet<>()); + map.put(Vector.class, () -> new Vector<>()); + map.put(Queue.class, () -> new LinkedList<>()); + map.put(Stack.class, () -> new Stack<>()); + return map; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDestroyable.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDestroyable.java new file mode 100644 index 00000000..62baf3a8 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDestroyable.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyDestroyable { + + void destroy(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDirectories.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDirectories.java new file mode 100644 index 00000000..789c35b7 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDirectories.java @@ -0,0 +1,59 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.util; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Collection; + +import org.apache.commons.io.FileUtils; + +/** + * @author tavandung12 + * + */ +public class EzyDirectories { + + private File directory; + + public URL[] getURLs() throws IOException { + return getURLs(getFiles(null)); + } + + public URL[] getURLs(String[] extensions) throws IOException { + return getURLs(extensions, true); + } + + public URL[] getURLs(String[] extensions, boolean recursive) throws IOException { + return getURLs(getFiles(extensions, recursive)); + } + + public Collection getFiles() { + return getFiles(null); + } + + public Collection getFiles(String[] extensions) { + return getFiles(extensions, true); + } + + public Collection getFiles(String[] extensions, boolean recursive) { + return FileUtils.listFiles(directory, extensions, recursive); + } + + private URL[] getURLs(Collection files) throws IOException { + return FileUtils.toURLs(files.toArray(new File[files.size()])); + } + + public EzyDirectories directory(File directory) { + this.directory = directory; + return this; + } + + @Override + public String toString() { + return directory.toString(); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyDoublesIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDoublesIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyDoublesIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyDoublesIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntry.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntry.java new file mode 100644 index 00000000..922be7f2 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEntry.java @@ -0,0 +1,49 @@ +package com.tvd12.ezyfoxserver.util; + +import java.io.Serializable; +import java.util.Map.Entry; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class EzyEntry implements Entry, Serializable { + private static final long serialVersionUID = -6562095834319774526L; + + protected K key; + protected V value; + + public static EzyEntry of(K key, V value) { + return new EzyEntry<>(key, value); + } + + public void setKey(K key) { + this.key = key; + } + + @Override + public V setValue(V value) { + V old = this.value; + this.value = value; + return old; + } + + @Override + public boolean equals(Object obj) { + return new EzyEquals>() + .function(e -> e.key) + .function(e -> e.value) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .append(key, value) + .toHashCode(); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEnums.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEnums.java new file mode 100644 index 00000000..fd2fee8c --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEnums.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.util; + +import com.tvd12.ezyfoxserver.constant.EzyHasId; + +public final class EzyEnums { + + private EzyEnums() { + } + + public static T valueOf(T[] values, int id) { + for(T v : values) + if(v.getId() == id) + return v; + throw new IllegalArgumentException("has no enum value with id = " + id); + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEquals.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEquals.java new file mode 100644 index 00000000..1df4f5dd --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyEquals.java @@ -0,0 +1,40 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public class EzyEquals { + + protected List> functions = new ArrayList<>(); + + @SuppressWarnings("unchecked") + public boolean isEquals(T thiz, Object other) { + if(other == null) + return false; + if(other == thiz) + return true; + if(!other.getClass().equals(thiz.getClass())) + return false; + T t = (T)other; + for(Function func : functions) { + Object v1 = func.apply(t); + Object v2 = func.apply(thiz); + if(v1 == v2) + continue; + if(v1 == null) + return false; + if(v2 == null) + return false; + if(!v1.equals(v2)) + return false; + } + return true; + } + + public EzyEquals function(Function function) { + this.functions.add(function); + return this; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyFloatsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyFloatsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyFloatsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyFloatsIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyForeach.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyForeach.java new file mode 100644 index 00000000..e5ec72af --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyForeach.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.function.Consumer; + +public interface EzyForeach { + + void forEach(Consumer action); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashCodes.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashCodes.java new file mode 100644 index 00000000..5fb6c6bd --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashCodes.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import com.google.common.collect.Sets; + +public class EzyHashCodes { + + protected int prime = 31; + protected int initial = 1; + protected List values = new ArrayList<>(); + + public int toHashCode() { + int result = initial; + for(Object value : values) + result = result * prime + (value == null ? 43 : value.hashCode()); + return result; + } + + public EzyHashCodes prime(int prime) { + this.prime = prime; + return this; + } + + public EzyHashCodes initial(int initial) { + this.initial = initial; + return this; + } + + public EzyHashCodes append(Object value) { + this.values.add(value); + return this; + } + + public EzyHashCodes append(Object... values) { + return append(Sets.newHashSet(values)); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public EzyHashCodes append(Collection values) { + this.values.addAll(values); + return this; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapCollection.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapCollection.java new file mode 100644 index 00000000..1b7106cb --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapCollection.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.Collection; +import java.util.HashMap; + +public abstract class EzyHashMapCollection> + extends HashMap + implements EzyMapCollection { + private static final long serialVersionUID = 3535251482476794711L; + + @Override + public void addItems(K key, Collection items) { + computeIfAbsent(key, k -> newCollection()).addAll(items); + } + + public V getItems(K key) { + return containsKey(key) ? get(key) : newCollection(); + } + + protected abstract V newCollection(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapList.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapList.java new file mode 100644 index 00000000..365d8b35 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapList.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.ArrayList; +import java.util.List; + +public class EzyHashMapList + extends EzyHashMapCollection> + implements EzyMapList { + private static final long serialVersionUID = 3678081740856760565L; + + @Override + protected List newCollection() { + return new ArrayList<>(); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapSet.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapSet.java new file mode 100644 index 00000000..2b062fc0 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyHashMapSet.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.HashSet; +import java.util.Set; + +public class EzyHashMapSet + extends EzyHashMapCollection> + implements EzyMapSet { + private static final long serialVersionUID = 4067364721031740580L; + + @Override + protected Set newCollection() { + return new HashSet<>(); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java similarity index 92% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java index 3273e8e2..a54e5f86 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyIfElse.java @@ -1,6 +1,6 @@ package com.tvd12.ezyfoxserver.util; -public abstract class EzyIfElse { +public final class EzyIfElse { private EzyIfElse() { } diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyInitable.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyInitable.java new file mode 100644 index 00000000..06c3c1ed --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyInitable.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyInitable { + + void init(); + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyIntsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyIntsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyIntsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyIntsIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyKeyValueAnnotations.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyKeyValueAnnotations.java new file mode 100644 index 00000000..e1828211 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyKeyValueAnnotations.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +public final class EzyKeyValueAnnotations { + + private EzyKeyValueAnnotations() { + } + + public static String getProperty(String key, EzyKeyValue[] kvs) { + for(EzyKeyValue kv : kvs) + if(key.equals(kv.key())) + return kv.value(); + return null; + } + + public static Map getProperties(EzyKeyValue[] kvs) { + Map answer = new HashMap<>(); + for(EzyKeyValue kv : kvs) + answer.put(kv.key(), kv.value()); + return answer; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLifecycle.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLifecycle.java new file mode 100644 index 00000000..c5719d5a --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLifecycle.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyLifecycle extends EzyInitable, EzyDestroyable { + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java new file mode 100644 index 00000000..b6dbffe3 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLoggable.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.util; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EzyLoggable { + + protected Logger logger = LoggerFactory.getLogger(getClass()); + + protected Logger getLogger() { + return logger; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLongsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLongsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyLongsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyLongsIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapBuilder.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapBuilder.java new file mode 100644 index 00000000..296af60c --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapBuilder.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.HashMap; +import java.util.Map; + +import com.tvd12.ezyfoxserver.builder.EzyBuilder; + +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class EzyMapBuilder implements EzyBuilder { + + protected Map map; + protected Map container = new HashMap<>(); + + public static EzyMapBuilder mapBuilder() { + return new EzyMapBuilder(); + } + + public EzyMapBuilder map(Map map) { + this.map = map; + return this; + } + + public EzyMapBuilder putAll(Map map) { + this.container.putAll(map); + return this; + } + + public EzyMapBuilder put(Object key, Object value) { + this.container.put(key, value); + return this; + } + + @Override + public Map build() { + if(map == null) return container; + map.putAll(container); + return map; + } +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapCollection.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapCollection.java new file mode 100644 index 00000000..aacd181e --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapCollection.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +public interface EzyMapCollection> extends Map { + + void addItems(K key, Collection items); + + @SuppressWarnings("unchecked") + default void addItems(K key, E... items) { + addItems(key, Arrays.asList(items)); + } + + @SuppressWarnings("unchecked") + default void removeItems(K key, E... items) { + removeItems(key, Arrays.asList(items)); + } + + default void removeItems(K key, Collection items) { + Collection coll = get(key); + if(coll != null) + coll.removeAll(items); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapFactory.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapFactory.java new file mode 100644 index 00000000..be8a52a4 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapFactory.java @@ -0,0 +1,31 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; + +public class EzyMapFactory { + + @SuppressWarnings("rawtypes") + protected final Map> suppliers = defaultSuppliers(); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public T newMap(Class mapType) { + if(suppliers.containsKey(mapType)) + return (T) suppliers.get(mapType).get(); + throw new IllegalArgumentException("unknown implementation of " + mapType); + } + + @SuppressWarnings("rawtypes") + private Map> defaultSuppliers() { + Map> map = new ConcurrentHashMap<>(); + map.put(Map.class, () -> new HashMap<>()); + map.put(HashMap.class, () -> new HashMap<>()); + map.put(TreeMap.class, () -> new TreeMap<>()); + map.put(ConcurrentHashMap.class, () -> new ConcurrentHashMap<>()); + return map; + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapList.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapList.java new file mode 100644 index 00000000..86259f78 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapList.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.List; + +public interface EzyMapList extends EzyMapCollection> { + + List getItems(K key); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapSet.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapSet.java new file mode 100644 index 00000000..608181a9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyMapSet.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.Set; + +public interface EzyMapSet extends EzyMapCollection> { + + Set getItems(K key); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyNameAware.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyNameAware.java new file mode 100644 index 00000000..5323f8ff --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyNameAware.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyNameAware { + + void setName(String name); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyObjects.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyObjects.java new file mode 100644 index 00000000..fb071fa0 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyObjects.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.util; + +public final class EzyObjects { + + private EzyObjects() { + } + + public static boolean equals(Object o1, Object o2) { + if(o1 == o2) return true; + if(o1 == null) return false; + if(o2 == null) return false; + return o1.equals(o2); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostConstruct.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostConstruct.java new file mode 100644 index 00000000..325e7bb3 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostConstruct.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyPostConstruct { + + void postConstruct(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostInit.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostInit.java new file mode 100644 index 00000000..dabe6129 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostInit.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyPostInit { + + void postInit(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostLoad.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostLoad.java new file mode 100644 index 00000000..624aca54 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPostLoad.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyPostLoad { + + void postLoad(); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProcessor.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProcessor.java new file mode 100644 index 00000000..9b15c312 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProcessor.java @@ -0,0 +1,94 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.function.Function; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.tvd12.ezyfoxserver.function.EzyExceptionVoid; +import com.tvd12.ezyfoxserver.function.EzyVoid; + +public final class EzyProcessor { + + private static final Logger LOGGER = LoggerFactory.getLogger(EzyProcessor.class); + + private EzyProcessor() { + } + + public static void processWithException(EzyExceptionVoid applier) { + processWithException(applier, e -> new IllegalStateException(e)); + } + + public static void processWithIllegalArgumentException(EzyExceptionVoid applier) { + processWithException(applier, e -> new IllegalArgumentException(e)); + } + + public static void processWithException( + EzyExceptionVoid applier, Function handler) { + try { + applier.apply(); + } + catch(Exception e) { + throw handler.apply(e); + } + } + + public static void processWithLogException(EzyExceptionVoid applier) { + try { + applier.apply(); + } + catch(Exception e) { + warn("can't process " + applier, e); + } + } + + public static void processWithSync(EzyVoid applier, Object context) { + synchronized (context) { + applier.apply(); + } + } + + public static void processWithLock(EzyVoid applier, Lock lock) { + lock.lock(); + try { + applier.apply(); + } + finally { + lock.unlock(); + } + } + + public static void processWithTryLock(EzyVoid applier, Lock lock) { + if(!lock.tryLock()) + return; + try { + applier.apply(); + } + finally { + lock.unlock(); + } + } + + public static void processWithTryLock( + EzyVoid applier, Lock lock, long time) throws InterruptedException { + if(!tryLock(lock, time)) + return; + try { + applier.apply(); + } + finally { + lock.unlock(); + } + } + + private static boolean tryLock(Lock lock, long time) throws InterruptedException { + return lock.tryLock(time, TimeUnit.MILLISECONDS); + } + + private static void warn(String message, Throwable throwable) { + LOGGER.warn(message, throwable); + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyProperties.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProperties.java similarity index 94% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyProperties.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProperties.java index 9e2d21d5..b47649bd 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyProperties.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyProperties.java @@ -1,7 +1,7 @@ /** * */ -package com.tvd12.ezyfoxserver.entity; +package com.tvd12.ezyfoxserver.util; import java.util.Map; diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertiesAware.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertiesAware.java new file mode 100644 index 00000000..5be34ee9 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertiesAware.java @@ -0,0 +1,9 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.Properties; + +public interface EzyPropertiesAware { + + void setProperties(Properties properties); + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertyAnnotations.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertyAnnotations.java new file mode 100644 index 00000000..0a2a4048 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyPropertyAnnotations.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.util; + +import com.tvd12.ezyfoxserver.annotation.EzyProperty; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; + +public final class EzyPropertyAnnotations { + + private EzyPropertyAnnotations() { + } + + public static String getPropertyName(EzyClass clazz, EzyReflectElement element) { + if(element instanceof EzyField) + return getPropertyName(clazz, (EzyField)element); + return getPropertyName(clazz, (EzyMethod)element); + } + + public static String getPropertyName(EzyClass clazz, EzyField field) { + EzyProperty annotation = field.getAnnotation(EzyProperty.class); + if(annotation.value().length() > 0) + return annotation.value(); + return field.getName(); + } + + public static String getPropertyName(EzyClass clazz, EzyMethod method) { + EzyProperty annotation = method.getAnnotation(EzyProperty.class); + if(annotation != null && annotation.value().length() > 0) + return annotation.value(); + String fieldName = method.getFieldName(); + EzyField field = clazz.getField(fieldName); + return field != null ? getPropertyName(clazz, field) : fieldName; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyReference.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReference.java similarity index 91% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyReference.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReference.java index 30f02125..cb061f2a 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyReference.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReference.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.entity; +package com.tvd12.ezyfoxserver.util; public interface EzyReference { diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java new file mode 100644 index 00000000..b773234e --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyReturner.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.concurrent.locks.Lock; +import java.util.function.Function; +import java.util.function.Supplier; + +import com.tvd12.ezyfoxserver.function.EzySupplier; + +public final class EzyReturner { + + private EzyReturner() { + } + + public static T returnNotNull(T rvalue, T svalue) { + return rvalue != null ? rvalue : svalue; + } + + public static T returnAndApply(T rvalue, Runnable applier) { + T temp = rvalue; applier.run(); return temp; + } + + public static T returnWithException(EzySupplier supplier) { + return returnWithException(supplier, e -> new IllegalStateException(e)); + } + + public static T returnWithIllegalArgumentException(EzySupplier supplier) { + return returnWithException(supplier, e -> new IllegalArgumentException(e)); + } + + public static T returnWithException( + EzySupplier supplier, Function handler) { + try { + return supplier.get(); + } + catch(Exception e) { + throw handler.apply(e); + } + } + + public static T returnWithSync(Supplier supplier, Object context) { + synchronized (context) { + return supplier.get(); + } + } + + public static T returnWithLock(Supplier supplier, Lock lock) { + lock.lock(); + try { + return supplier.get(); + } + finally { + lock.unlock(); + } + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoProperties.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyRoProperties.java similarity index 96% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoProperties.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyRoProperties.java index 74a627e3..217da683 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/entity/EzyRoProperties.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyRoProperties.java @@ -1,4 +1,4 @@ -package com.tvd12.ezyfoxserver.entity; +package com.tvd12.ezyfoxserver.util; import java.util.Properties; diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyShortsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyShortsIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyShortsIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyShortsIterator.java diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStartable.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStartable.java new file mode 100644 index 00000000..c7d80497 --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStartable.java @@ -0,0 +1,7 @@ +package com.tvd12.ezyfoxserver.util; + +public interface EzyStartable { + + void start() throws Exception; + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java new file mode 100644 index 00000000..9945bdbb --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyStringsIterator.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.util; + +public class EzyStringsIterator extends EzyWrapperIterator { + + public EzyStringsIterator(String[] array) { + super(array); + } + + public static EzyStringsIterator wrap(String[] array) { + return new EzyStringsIterator(array); + } + +} diff --git a/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzySum.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzySum.java new file mode 100644 index 00000000..e73c7dcf --- /dev/null +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzySum.java @@ -0,0 +1,122 @@ +package com.tvd12.ezyfoxserver.util; + +import java.util.function.Function; + +public final class EzySum { + + private EzySum() { + } + + public static int sumBytes(byte[] numbers) { + int total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static double sumDoubles(double[] numbers) { + double total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static float sumFloats(float[] numbers) { + float total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static int sumInts(int[] numbers) { + int total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static long sumLongs(long[] numbers) { + long total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static int sumShorts(short[] numbers) { + int total = 0; + for(int i = 0 ; i < numbers.length ; i++) + total += numbers[i]; + return total; + } + + public static int sumBytes(Iterable numbers) { + int total = 0; + for(Byte number : numbers) + total += number; + return total; + } + + public static double sumDoubles(Iterable numbers) { + double total = 0; + for(Double number : numbers) + total += number; + return total; + } + + public static float sumFloats(Iterable numbers) { + float total = 0; + for(Float number : numbers) + total += number; + return total; + } + + public static int sumInts(Iterable numbers) { + int total = 0; + for(Integer number : numbers) + total += number; + return total; + } + + public static long sumLongs(Iterable numbers) { + long total = 0; + for(Long number : numbers) + total += number; + return total; + } + + public static int sumShorts(Iterable numbers) { + int total = 0; + for(Short number : numbers) + total += number; + return total; + } + + public static int sumToInt(T[] array, Function func) { + int total = 0; + for(T t : array) + total += func.apply(t); + return total; + } + + public static int sumToInt(Iterable iterable, Function func) { + int total = 0; + for(T t : iterable) + total += func.apply(t); + return total; + } + + public static long sumToLong(T[] array, Function func) { + long total = 0; + for(T t : array) + total += func.apply(t); + return total; + } + + public static long sumToLong(Iterable iterable, Function func) { + long total = 0; + for(T t : iterable) + total += func.apply(t); + return total; + } + +} diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java similarity index 86% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java index fa47adef..1dfa0735 100644 --- a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java +++ b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyTimes.java @@ -7,7 +7,7 @@ * @author tavandung12 * */ -public abstract class EzyTimes { +public final class EzyTimes { private EzyTimes() { } @@ -22,7 +22,7 @@ private EzyTimes() { * @return thoi gian con lai cua trang thai. Tra ve 0 neu maxTime = 0 */ public static int getRemainTime(long maxTime, long startingTime) { - if(maxTime == 0) + if(maxTime <= 0) return 0; return (int)(maxTime - (System.currentTimeMillis() - startingTime)); } @@ -37,9 +37,7 @@ public static int getRemainTime(long maxTime, long startingTime) { * @return thoi gian con lai cua trang thai. Tra ve 0 neu maxTime = 0 */ public static int getPositiveRemainTime(long maxTime, long startingTime) { - if(maxTime == 0) - return 0; - int result = (int)(maxTime - (System.currentTimeMillis() - startingTime)); + int result = getRemainTime(maxTime, startingTime); return result > 0 ? result : 0; } diff --git a/ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyWrapperIterator.java b/ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyWrapperIterator.java similarity index 100% rename from ezyfox-server-common/src/main/java/com/tvd12/ezyfoxserver/util/EzyWrapperIterator.java rename to ezyfox-server-util/src/main/java/com/tvd12/ezyfoxserver/util/EzyWrapperIterator.java diff --git a/ezyfox-server-util/src/test/java/DefaultClassX.java b/ezyfox-server-util/src/test/java/DefaultClassX.java new file mode 100644 index 00000000..4ca361fe --- /dev/null +++ b/ezyfox-server-util/src/test/java/DefaultClassX.java @@ -0,0 +1,8 @@ + +public class DefaultClassX { + + public Object obj = new Object() { + + }; + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/EzyMapServiceAutoImpl.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/EzyMapServiceAutoImpl.java new file mode 100644 index 00000000..84f98ab1 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/EzyMapServiceAutoImpl.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.annotation; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; + +@Documented +@Retention(RUNTIME) +@Target({ TYPE }) +@EzyAutoImpl(properties = @EzyKeyValue(key = "map-name", value = "")) +public @interface EzyMapServiceAutoImpl { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/Implementor.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/Implementor.java new file mode 100644 index 00000000..cd60b70a --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/Implementor.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.annotation; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.test.base.BaseTest; + +public class Implementor extends BaseTest { + + public static void main(String[] args) { + System.out.println(PersonMapService.class.isAnnotationPresent(EzyMapServiceAutoImpl.class)); + System.out.println(PersonMapService.class.isAnnotationPresent(EzyAutoImpl.class)); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/PersonMapService.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/PersonMapService.java new file mode 100644 index 00000000..84030a8f --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/annotation/PersonMapService.java @@ -0,0 +1,6 @@ +package com.tvd12.ezyfoxserver.testing.annotation; + +@EzyMapServiceAutoImpl +public interface PersonMapService { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyFunctionTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyFunctionTest.java new file mode 100644 index 00000000..8d5337c1 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyFunctionTest.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.testing.asm; + +import java.lang.reflect.Method; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.asm.EzyFunction; +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.test.base.BaseTest; + +public class EzyFunctionTest extends BaseTest { + + @Test + public void test() throws Exception { + Method method = Reader.class.getMethod("read", String.class); + EzyFunction function = new EzyFunction(method) + .modifier("public"); + EzyFunction.EzyBody body = function.body(); + body.append(new EzyInstruction("\t", "\n", true) + .variable(Integer.class, "number") + .equal() + .clazz(Integer.class) + .append(".valueOf(arg0)")) + .append(new EzyInstruction("\t", "\n") + .append("number += 1")) + .append(new EzyInstruction("\t", "\n") + .answer() + .append("java.lang.String.valueOf(number)")); + System.out.println(body.function().toString()); + } + + public static interface Reader { + public String read(String value); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyInstructionTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyInstructionTest.java new file mode 100644 index 00000000..85f60e3e --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/asm/EzyInstructionTest.java @@ -0,0 +1,85 @@ +package com.tvd12.ezyfoxserver.testing.asm; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.asm.EzyInstruction; +import com.tvd12.test.base.BaseTest; + +public class EzyInstructionTest extends BaseTest { + + @Test + public void test() { + EzyInstruction instruction = new EzyInstruction(); + assertEquals(instruction.finish().toString(), ";"); + + instruction = new EzyInstruction(); + assertEquals(instruction.constructor(A.class).toString(), + A.class.getName() + "();"); + + instruction = new EzyInstruction(); + assertEquals(instruction.append((Object)"hello").toString(), "hello;"); + + instruction = new EzyInstruction(); + assertEquals(instruction.string("hello").toString(), "\"hello\";"); + + instruction = new EzyInstruction(); + assertEquals(instruction.clazz(A.class, true).toString(), + A.class.getName() + ".class;"); + + instruction = new EzyInstruction(); + assertEquals(instruction.dot().toString(), ".;"); + + instruction = new EzyInstruction(); + assertEquals(instruction.comma().toString(), ", ;"); + + instruction = new EzyInstruction(); + assertEquals(instruction.bracketopen().bracketclose().toString(), "();"); + + instruction = new EzyInstruction(); + assertEquals(instruction.brackets(A.class).toString(), + "(" + A.class.getTypeName() + ");"); + + instruction = new EzyInstruction(); + assertEquals(instruction.brackets("hello").toString(), "(hello);"); + + instruction = new EzyInstruction(); + assertEquals(instruction.variable(A.class).toString(), + A.class.getTypeName() + " a;"); + + instruction = new EzyInstruction(); + assertEquals(instruction.cast(A.class, "va").toString(), + "((" + A.class.getTypeName() + ")(va));"); + + instruction = new EzyInstruction(); + assertEquals(instruction.valueOf(int.class, "value").toString(), + Integer.class.getName() + ".valueOf(value);"); + + instruction = new EzyInstruction(); + assertEquals(instruction.valueOf(Integer.class, "value").toString(), "value;"); + + instruction = new EzyInstruction("", "", true); + assertEquals(instruction.append((Object)"hello").toString(), "hello;"); + + instruction = new EzyInstruction("", "", true); + assertEquals(instruction.append((Object)"hello;").toString(), "hello;"); + + instruction = new EzyInstruction("", "", false); + assertEquals(instruction.append((Object)"hello").toString(true), "hello"); + + instruction = new EzyInstruction("", "", true); + assertEquals(instruction.append((Object)"hello;").toString(true), "hello;"); + + instruction = new EzyInstruction("", "", true); + assertEquals(instruction.append((Object)"hello;").toString(false), "hello;"); + + instruction = new EzyInstruction("", "", true); + assertEquals(instruction.append((Object)"hello").toString(false), "hello"); + } + + public static class A { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAttributeTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAttributeTest.java new file mode 100644 index 00000000..d517a7c9 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyAttributeTest.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyAttribute; +import com.tvd12.test.base.BaseTest; + +public class EzyAttributeTest extends BaseTest { + + @Test + public void test() { + EzyAttribute A = EzyAttribute.valueOf(1, "a"); + assert A.getName().equals("a"); + EzyAttribute B = EzyAttribute.valueOf(2); + assert B.getName().equals("attribute#2"); + EzyAttribute C = EzyAttribute.valueOf("c"); + assert C.getId() > 2; + EzyAttribute D = EzyAttribute.one(); + System.err.println("D.id = " + D.getId() + ", D.name = " + D.getName()); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyConstantTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyConstantTest.java new file mode 100644 index 00000000..8d195aed --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/constant/EzyConstantTest.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.testing.constant; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.test.base.BaseTest; + +public class EzyConstantTest extends BaseTest { + + @Test + public void test() { + EzyConstant a = EzyConstant.one(); + System.err.println("a.id = " + a.getId() + ", a.name = " + a.getName()); + + EzyConstant b = EzyConstant.one("b"); + System.err.println("b.id = " + b.getId() + ", b.name = " + b.getName()); + + EzyConstant c = EzyConstant.one("c"); + System.err.println("c.id = " + c.getId() + ", c.name = " + c.getName()); + + MyConstant d = new MyConstant(); + System.err.println("d.id = " + c.getId() + ", d.name = " + d.getName()); + } + + public static class MyConstant implements EzyConstant { + + @Override + public int getId() { + return 0; + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyNegativeValueExceptionTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyNegativeValueExceptionTest.java new file mode 100644 index 00000000..3bb696a8 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/exception/EzyNegativeValueExceptionTest.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.testing.exception; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.exception.EzyNegativeValueException; +import com.tvd12.test.base.BaseTest; + +public class EzyNegativeValueExceptionTest extends BaseTest { + + @Test + public void test() { + new EzyNegativeValueException(-10); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/function/EzyCastIntToByteTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/function/EzyCastIntToByteTest.java new file mode 100644 index 00000000..02866ac2 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/function/EzyCastIntToByteTest.java @@ -0,0 +1,17 @@ +package com.tvd12.ezyfoxserver.testing.function; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyCastIntToByte; +import com.tvd12.test.base.BaseTest; + +public class EzyCastIntToByteTest extends BaseTest { + + @Test + public void test() { + EzyCastIntToByte cast = new EzyCastIntToByte() {}; + assert cast.cast(100) == (byte)100; + assert cast.cast(100L) == (byte)100; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelperTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelperTest.java new file mode 100644 index 00000000..05543972 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelperTest.java @@ -0,0 +1,159 @@ +package com.tvd12.ezyfoxserver.testing.helper; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyInitialize; +import com.tvd12.ezyfoxserver.function.EzyVoid; +import com.tvd12.ezyfoxserver.helper.EzyLazyInitHelper; +import com.tvd12.test.base.BaseTest; +import com.tvd12.test.reflect.ReflectMethodUtil; + +public class EzyLazyInitHelperTest extends BaseTest { + + @Test + public void test() { + EzyLazyInitHelper.init(this, () -> new String()); + EzyLazyInitHelper.init(this, () -> new String(), () -> new String()); + } + + @Test + public void test2() { + Map map = new HashMap<>(); + EzyLazyInitHelper.voidInit(this, + () -> !map.containsKey("1"), + () -> map.put("1", "a")); + assert map.get("1").equals("a"); + EzyLazyInitHelper.voidInit(this, + () -> !map.containsKey("1"), + () -> map.put("1", "v")); + assert map.get("1").equals("a"); + } + + @Test + public void test1() throws Exception { + Method method = ReflectMethodUtil.getMethod("syncInit", + EzyLazyInitHelper.class, Object.class, Supplier.class, EzyInitialize.class); + method.setAccessible(true); + method.invoke(null, this, new Supplier() { + @Override + public String get() { + return null; + } + }, new EzyInitialize() { + @Override + public String init() { + return new String(); + } + }); + + method.invoke(null, this, new Supplier() { + @Override + public String get() { + return new String(); + } + }, new EzyInitialize() { + @Override + public String init() { + return new String(); + } + }); + } + + + @Test + public void test3() throws Exception { + Map map = new HashMap<>(); + Method method = ReflectMethodUtil.getMethod("syncVoidInit", + EzyLazyInitHelper.class, Object.class, Supplier.class, EzyVoid.class); + method.setAccessible(true); + method.invoke(null, this, new Supplier() { + @Override + public Boolean get() { + return !map.containsKey("1"); + } + }, new EzyVoid() { + @Override + public void apply() { + map.put("1", "a"); + } + }); + + assert map.get("1").equals("a"); + + method.invoke(null, this, new Supplier() { + @Override + public Boolean get() { + return !map.containsKey("1"); + } + }, new EzyVoid() { + @Override + public void apply() { + map.put("1", "b"); + } + }); + assert map.get("1").equals("a"); + } + + @Test(expectedExceptions = {InvocationTargetException.class}) + public void test4() throws Exception { + Map map = new HashMap<>(); + Method method = ReflectMethodUtil.getMethod("syncVoidInit", + EzyLazyInitHelper.class, Object.class, Supplier.class, EzyVoid.class); + method.setAccessible(true); + method.invoke(EzyLazyInitHelper.class, map, new Supplier() { + @Override + public Boolean get() { + return !map.containsKey("1"); + } + }, new EzyVoid() { + @Override + public void apply() { + map.put("1", "a"); + } + }); + + assert map.get("1").equals("a"); + + method.invoke(EzyLazyInitHelper.class, map, new Supplier() { + @Override + public Boolean get() { + throw new RuntimeException(); + } + }, new EzyVoid() { + @Override + public void apply() { + map.put("1", "b"); + } + }); + assert map.get("1").equals("a"); + } + + @Override + public Class getTestClass() { + return EzyLazyInitHelper.class; + } + + public static void main(String[] args) { + String main="2014-11-30 13:30:00"; + String pattern = "yyyy-MM-dd HH:mm:ss"; + DateFormat formatter = new SimpleDateFormat(pattern); + try { + Date date = formatter.parse(main); + if(!main.equals(formatter.format(date))) + System.out.println("Wrong input"); + } catch (ParseException e) { + System.out.println("Wrong input"); + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelper_ESTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelper_ESTest.java new file mode 100644 index 00000000..f5c6b730 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/helper/EzyLazyInitHelper_ESTest.java @@ -0,0 +1,47 @@ +/* + * This file was automatically generated by EvoSuite + * Wed May 03 09:49:34 ICT 2017 + */ + +package com.tvd12.ezyfoxserver.testing.helper; + +import static org.testng.Assert.fail; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyInitialize; +import com.tvd12.ezyfoxserver.helper.EzyLazyInitHelper; + +public class EzyLazyInitHelper_ESTest { + + @Test + public void test3() throws Throwable { + Integer integer0 = new Integer(1203); + // Undeclared exception! + try { + EzyLazyInitHelper.init((Object) integer0, (EzyInitialize) null); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // +// assertThrownBy("com.tvd12.ezyfoxserver.helper.EzyLazyInitHelper", e); + } + } + + @Test + public void test4() throws Throwable { + // Undeclared exception! + try { + EzyLazyInitHelper.init((Object) null, (EzyInitialize) null); + fail("Expecting exception: NullPointerException"); + + } catch(NullPointerException e) { + // + // no message in exception (getMessage() returned null) + // +// assertThrownBy("com.tvd12.ezyfoxserver.helper.EzyLazyInitHelper", e); + } + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyArraysTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyArraysTest.java new file mode 100644 index 00000000..3fb9367f --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyArraysTest.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import java.util.Collection; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzyArrays; +import com.tvd12.test.base.BaseTest; + +public class EzyArraysTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyArrays.class; + } + + @Test + public void test() { + Collection coll = Lists.newArrayList("1", "2", "3"); + Long[] array = EzyArrays.newArray(coll, + (s) -> new Long[s], + s -> Long.valueOf(s)); + Assert.assertEquals(array, new Long[] {1L, 2L, 3L}); + } + + @Test + public void test1() { + assert EzyArrays.min(new Long[] {3L,1L,2L}) == 1L; + assert EzyArrays.max(new Long[] {3L,1L,5L,6L,2L}) == 6L; + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyByteBuffersTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyByteBuffersTest.java new file mode 100644 index 00000000..10af8316 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyByteBuffersTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyByteBuffers; +import com.tvd12.test.base.BaseTest; + +public class EzyByteBuffersTest extends BaseTest { + + @Test + public void test() { + ByteBuffer buffer = ByteBuffer.allocate(8).putLong(1000L); + buffer.flip(); + EzyByteBuffers.getBytes(buffer); + } + + @Override + public Class getTestClass() { + return EzyByteBuffers.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyBytesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyBytesTest.java new file mode 100644 index 00000000..daf7cd9c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyBytesTest.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyArrays; +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.test.base.BaseTest; + +public class EzyBytesTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyBytes.copy(ByteBuffer.wrap(new byte[] {1, 2, 3, 4, 5, 6}), 3), + new byte[] {1, 2, 3}); + assertEquals(EzyBytes.getBytes(1, 255 + 1, 2), + new byte[] {1, 1, 0}); + assertEquals(EzyBytes.getBytes((byte)1, 100.5D), + EzyArrays.merge((byte)1, EzyBytes.getBytes(ByteBuffer.allocate(8).putDouble(100.5D)))); + assertEquals(EzyBytes.getBytes((byte)1, 100.5F), + EzyArrays.merge((byte)1, EzyBytes.getBytes(ByteBuffer.allocate(4).putFloat(100.5F)))); + assertEquals(EzyBytes.getBytes(100L), + EzyBytes.getBytes(ByteBuffer.allocate(8).putLong(100L))); + assertEquals(EzyBytes.getBytes(100), + EzyBytes.getBytes(ByteBuffer.allocate(4).putInt(100))); + assertEquals(EzyBytes.getBytes((short)100), + EzyBytes.getBytes(ByteBuffer.allocate(2).putShort((short)100))); + assertEquals(EzyBytes.getBytes((byte)1, new byte[] {2, 3}), + new byte[] {1, 2, 3}); + + } + + @Test + public void test1() { + assert EzyBytes.totalBytes(new byte[][] {{1,2},{1,2,3}}) == 5; + assertEquals(EzyBytes.copy(new byte[][] {{1,2},{1,2,3}}), new byte[] {1,2,1,2,3}); + } + + @Override + public Class getTestClass() { + return EzyBytes.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyCollectionsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyCollectionsTest.java new file mode 100644 index 00000000..d6c5e828 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyCollectionsTest.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.io.EzyCollections; +import com.tvd12.test.base.BaseTest; + +public class EzyCollectionsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyCollections.class; + } + + @Test + public void test() { + assertTrue(EzyCollections.containsAny( + Sets.newHashSet("1", "2", "3"), Sets.newHashSet("2", "4", "5"))); + assertEquals(EzyCollections.countItems( + Sets.newHashSet("ab", "ac", "de", "ef", "ah"), str -> str.startsWith("a")), 3); + assertEquals(EzyCollections.flatMapToInt( + Sets.newHashSet('a', 'b', 'c'), ch -> (int)ch), (int)'a' + (int)'b' + (int)'c'); + Set set = Sets.newHashSet("a", "b", "c"); + assertEquals(EzyCollections.getItem(set, (i) -> i.equals("b")), "b"); + assertNull(EzyCollections.getItem(set, (i) -> i.equals("z"))); + assertEquals(EzyCollections.toArray(Lists.newArrayList("a", "b", "c"), String[]::new), + new String[] {"a", "b", "c"}); + } + + @Test + public void test1() { + assert EzyCollections.isEmpty(null); + assert EzyCollections.isEmpty(Lists.newArrayList()); + assert !EzyCollections.isEmpty(Lists.newArrayList(1)); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDataConverterTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDataConverterTest.java new file mode 100644 index 00000000..59a546d0 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDataConverterTest.java @@ -0,0 +1,301 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveBoolArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveIntArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveLongArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToPrimitiveShortArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToStringArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperDoubleArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperFloatArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperIntArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperLongArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.collectionToWrapperShortArray; +import static com.tvd12.ezyfoxserver.io.EzyDataConverter.toCharWrapperArray; +import static org.testng.Assert.assertEquals; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzyDataConverter; +import com.tvd12.test.base.BaseTest; + +public class EzyDataConverterTest extends BaseTest { + + @Test + public void stringToCharTest() { + char ch0 = EzyDataConverter.stringToChar(""); + assert ch0 == 0; + char ch1 = EzyDataConverter.stringToChar(null); + assert ch1 == 0; + char ch2 = EzyDataConverter.stringToChar("1,23"); + assert ch2 == '1'; + } + + @Test + public void byteArrayToCharArrayTest() { + char[] chs = EzyDataConverter.byteArrayToCharArray(new byte[] {1, 2, 3}); + assertEquals(chs, new char[] {1,2,3}); + } + + @Test + public void charArrayToByteArrayTest() { + byte[] bytes = EzyDataConverter.charArrayToByteArray(new char[] {1, 2, 3}); + assertEquals(bytes, new byte[] {1, 2, 3}); + } + + @Test + public void collectionToPrimitiveByteArrayTest() { + byte[] value = EzyDataConverter.collectionToPrimitiveByteArray( + Lists.newArrayList((byte)1, (byte)2, (byte)3)); + assertEquals(value, new byte[] {1, 2, 3}); + } + + @Test + public void collectionToPrimitiveCharArrayTest() { + char[] value = EzyDataConverter.collectionToPrimitiveCharArray( + Lists.newArrayList('a', 'b', 'c')); + assertEquals(value, new char[] {'a', 'b', 'c'}); + } + + @Test + public void charCollectionToPrimitiveByteArrayTest() { + byte[] value = EzyDataConverter.charCollectionToPrimitiveByteArray( + Lists.newArrayList('a', 'b', 'c')); + assertEquals(value, new byte[] {'a', 'b', 'c'}); + } + + @Test + public void arrayToListTest() { + List bytes = EzyDataConverter.arrayToList(new byte[] {1, 2, 3}); + assertEquals(bytes.containsAll(Lists.newArrayList((byte)1, (byte)2, (byte)3)), true); + } + + @Test + public void arrayToListTest2() { + List bytes = EzyDataConverter.arrayToList(new String[] {"a", "b", "c"}); + assertEquals(bytes.containsAll(Lists.newArrayList("a", "b", "c")), true); + } + + @Test + public void arrayToListBooleanTest() { + List booleans = EzyDataConverter.arrayToList(new boolean[] {true, false, true}); + assertEquals(booleans.containsAll(Lists.newArrayList(true, false, true)), true); + } + + @Test + public void arrayToListCharTest() { + List booleans = EzyDataConverter.arrayToList(new char[] {'a', 'b', 'c'}); + assertEquals(booleans.containsAll(Lists.newArrayList('a', 'b', 'c')), true); + } + + @Test + public void arrayToListDoubleTest() { + List booleans = EzyDataConverter.arrayToList(new double[] {1D, 2D, 3D}); + assertEquals(booleans.containsAll(Lists.newArrayList(1D, 2D, 3D)), true); + } + + @Test + public void arrayToListFloatTest() { + List booleans = EzyDataConverter.arrayToList(new float[] {1F, 2F, 3F}); + assertEquals(booleans.containsAll(Lists.newArrayList(1F, 2F, 3F)), true); + } + + @Test + public void arrayToListIntTest() { + List ints = EzyDataConverter.arrayToList(new int[] {1, 2, 3}); + assertEquals(ints.containsAll(Lists.newArrayList(1, 2, 3)), true); + } + + @Test + public void arrayToListLongTest() { + List booleans = EzyDataConverter.arrayToList(new long[] {1L, 2L, 3L}); + assertEquals(booleans.containsAll(Lists.newArrayList(1L, 2L, 3L)), true); + } + + @Test + public void arrayToListShortTest() { + List booleans = EzyDataConverter.arrayToList(new short[] {(short)1, (short)2, (short)3}); + assertEquals(booleans.containsAll(Lists.newArrayList((short)1, (short)2, (short)3)), true); + } + + @Test + public void byteArrayToCharListTest() { + List chars = EzyDataConverter.byteArrayToCharList(new byte[] {'a', 'b', 'c'}); + assertEquals(chars.containsAll(Lists.newArrayList('a', 'b', 'c')), true); + } + + @Test + public void toBoolWrapperArrayTest() { + assertEquals(EzyDataConverter.toBoolWrapperArray( + new boolean[] {true, false, true}), + new Boolean[] {true, false, true}); + } + + @Test + public void toByteWrapperArrayTest() { + assertEquals(EzyDataConverter.toByteWrapperArray( + new byte[] {1, 2, 3}), + new Byte[] {1, 2, 3}); + } + + @Test + public void toPrimitiveByteArrayTest() { + assertEquals(EzyDataConverter.toPrimitiveByteArray( + new Byte[] {1, 2, 3}), + new byte[] {1, 2, 3}); + } + + @Test + public void toPrimitiveCharArrayTest() { + assertEquals(EzyDataConverter.toPrimitiveCharArray( + new Character[] {'a', 'b', 'c'}), + new char[] {'a', 'b', 'c'}); + } + + @Test + public void charWrapperArrayToPrimitiveByteArrayTest() { + assertEquals(EzyDataConverter.charWrapperArrayToPrimitiveByteArray( + new Character[] {'a', 'b', 'c'}), + new byte[] {'a', 'b', 'c'}); + } + + @Test + public void primitiveArrayToBoolCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToBoolCollection( + new boolean[] {true, false, true}), + Lists.newArrayList(true, false, true)); + } + + @Test + public void primitiveArrayToByteCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToByteCollection( + new byte[] {1, 2, 3}), + Lists.newArrayList((byte)1, (byte)2, (byte)3)); + } + + @Test + public void primitiveArrayToCharCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToCharCollection( + new char[] {'a', 'b', 'c'}), + Lists.newArrayList('a', 'b', 'c')); + } + + @Test + public void primitiveArrayToDoubleCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToDoubleCollection( + new double[] {1D, 2D, 3D}), + Lists.newArrayList(1D, 2D, 3D)); + } + + @Test + public void primitiveArrayToFloatCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToFloatCollection( + new float[] {1F, 2F, 3F}), + Lists.newArrayList(1F, 2F, 3F)); + } + + @Test + public void primitiveArrayToIntCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToIntCollection( + new int[] {1, 2, 3}), + Lists.newArrayList(1, 2, 3)); + } + + @Test + public void primitiveArrayToLongCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToLongCollection( + new long[] {1, 2, 3}), + Lists.newArrayList(1L, 2L, 3L)); + } + + @Test + public void primitiveArrayToShortCollectionTest() { + assertEquals(EzyDataConverter.primitiveArrayToShortCollection( + new short[] {1, 2, 3}), + Lists.newArrayList((short)1, (short)2, (short)3)); + } + + @Test + public void stringArrayToCollectionTest() { + assertEquals(EzyDataConverter.stringArrayToCollection( + new String[] {"a", "b", "c"}), + Lists.newArrayList("a", "b", "c")); + } + + @Test + public void wrapperArrayToCollectionTest() { + assertEquals(EzyDataConverter.wrapperArrayToCollection( + new String[] {"a", "b", "c"}), + Lists.newArrayList("a", "b", "c")); + } + + @Test + public void wrapperArrayToCollection2Test() { + assertEquals(EzyDataConverter.wrapperArrayToCollection( + (Object) new String[] {"a", "b", "c"}), + Lists.newArrayList("a", "b", "c")); + } + + @Test + public void collectionToWrapperBoolArrayTest() { + Boolean[] bools = EzyDataConverter.collectionToWrapperBoolArray( + Lists.newArrayList(true, false, true)); + assertEquals(bools, new Boolean[] {true, false, true}); + } + + @Test + public void collectionToWrapperByteArrayTest() { + Byte[] bytes = EzyDataConverter.collectionToWrapperByteArray( + Lists.newArrayList(new Byte[] {1, 2, 3})); + assertEquals(bytes, new Byte[] {1, 2, 3}); + } + + @Test + public void collectionToWrapperCharArrayTest() { + Character[] chars = EzyDataConverter.collectionToWrapperCharArray( + Lists.newArrayList(new Character[] {1, 2, 3})); + assertEquals(chars, new Character[] {1, 2, 3}); + } + + @Test + public void testAll() { + assertEquals(collectionToWrapperDoubleArray(Lists.newArrayList(1D, 2D, 3D)), + new Double[] {1D, 2D, 3D}); + assertEquals(collectionToWrapperFloatArray(Lists.newArrayList(1F, 2F, 3F)), + new Float[] {1F, 2F, 3F}); + assertEquals(collectionToWrapperIntArray(Lists.newArrayList(1, 2, 3)), + new Integer[] {1, 2, 3}); + assertEquals(collectionToWrapperLongArray(Lists.newArrayList(1L, 2L, 3L)), + new Long[] {1L, 2L, 3L}); + assertEquals(collectionToWrapperShortArray(Lists.newArrayList((short)1, (short)2, (short)3)), + new Short[] {1, 2, 3}); + + assertEquals(collectionToPrimitiveBoolArray(Lists.newArrayList(true, false, true)), + new boolean[] {true, false, true}); + assertEquals(collectionToPrimitiveDoubleArray(Lists.newArrayList(1D, 2D, 3D)), + new double[] {1D, 2D, 3D}); + assertEquals(collectionToPrimitiveFloatArray(Lists.newArrayList(1F, 2F, 3F)), + new float[] {1F, 2F, 3F}); + assertEquals(collectionToPrimitiveIntArray(Lists.newArrayList(1, 2, 3)), + new int[] {1, 2, 3}); + assertEquals(collectionToPrimitiveLongArray(Lists.newArrayList(1L, 2L, 3L)), + new long[] {1L, 2L, 3L}); + assertEquals(collectionToPrimitiveShortArray(Lists.newArrayList((short)1, (short)2, (short)3)), + new short[] {(short)1, (short)2, (short)3}); + assertEquals(collectionToStringArray(Lists.newArrayList("1", "2", "3")), + new String[] {"1", "2", "3"}); + + assertEquals(toCharWrapperArray(new byte[] {'a', 'b', 'c'}), + new Character[] {'a', 'b', 'c'}); + } + + @Override + public Class getTestClass() { + return EzyDataConverter.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDatesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDatesTest.java new file mode 100644 index 00000000..58b406d4 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyDatesTest.java @@ -0,0 +1,78 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.temporal.TemporalAccessor; +import java.util.Date; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyDates; +import com.tvd12.test.base.BaseTest; + +public class EzyDatesTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyDates.format((Date)null), null); + } + + @Test + public void test1() { + EzyDates.format(LocalDateTime.of(2017, 05, 30, 12, 34, 56, 0)); + assertEquals(EzyDates.format(LocalDateTime.of( + 2017, 05, 30, 12, 34, 56, 0), + "yyyy-MM-dd'T'HH:mm:ss"), + "2017-05-30T12:34:56"); + assertEquals(EzyDates.format((TemporalAccessor)null), null); + assertEquals(EzyDates.parseDate("2017-05-30T12:34:56:000"), + LocalDate.of(2017, 05, 30)); + assertEquals(EzyDates.parseDate("2017-05-30", "yyyy-MM-dd"), + LocalDate.of(2017, 05, 30)); + assertEquals(EzyDates.parseDateTime("2017-05-30T12:34:56:000"), + LocalDateTime.of(2017, 05, 30, 12, 34, 56, 0)); + assertEquals(EzyDates.parseDateTime("2017-05-30T12:34:56", "yyyy-MM-dd'T'HH:mm:ss"), + LocalDateTime.of(2017, 05, 30, 12, 34, 56, 0)); + } + + @Test + public void test2() { + assertEquals(EzyDates.format((Date)null), null); + assertEquals(EzyDates.format(new Date()).length() > 0, true); + assertEquals(EzyDates.parse("2017-05-30T12:34:56:000").getTime() > 0, true); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + EzyDates.parse("abcc"); + } + + @Test + public void test4() { + Date now = new Date(); + long nowTime = now.getTime(); + Date before = new Date(nowTime - 10000); + Date after = new Date(nowTime + 10000); + assert EzyDates.between(now, before, after); + + now = new Date(nowTime - 20000); + assert !EzyDates.between(now, before, after); + + now = new Date(nowTime + 20000); + assert !EzyDates.between(now, before, after); + } + + @Test + public void test5() { + int value = EzyDates.formatAsInteger(new Date()); + System.out.println(value); + } + + @Override + public Class getTestClass() { + return EzyDates.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIntsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIntsTest.java new file mode 100644 index 00000000..7f649aeb --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIntsTest.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.ezyfoxserver.io.EzyInts; +import com.tvd12.test.base.BaseTest; + +public class EzyIntsTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyInts.bin2int(31), Integer.MAX_VALUE); + assertEquals(EzyInts.bin2int( + EzyBytes.getBytes(ByteBuffer.allocate(4).putInt(-100))), -100); + assertEquals(EzyInts.bin2uint( + EzyBytes.getBytes(ByteBuffer.allocate(4).putInt(100))), 100); + ByteBuffer buffer1 = ByteBuffer.allocate(4).putInt(-1000); + buffer1.flip(); + assertEquals(EzyInts.bin2int(buffer1), -1000); + + ByteBuffer buffer2 = ByteBuffer.allocate(4).putInt(1000); + buffer2.flip(); + assertEquals(EzyInts.bin2uint(buffer2), 1000); + } + + @Override + public Class getTestClass() { + return EzyInts.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIterablesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIterablesTest.java new file mode 100644 index 00000000..76eb47da --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyIterablesTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzyIterables; +import com.tvd12.test.base.BaseTest; + +public class EzyIterablesTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyIterables.class; + } + + @Test + public void test() { + assert EzyIterables.isEmpty(null); + assert EzyIterables.isEmpty(Lists.newArrayList()); + assert !EzyIterables.isEmpty(Lists.newArrayList(1)); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyListsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyListsTest.java new file mode 100644 index 00000000..69577080 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyListsTest.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.io.EzyLists; +import com.tvd12.test.base.BaseTest; + +public class EzyListsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyLists.class; + } + + @SuppressWarnings("unchecked") + @Test + public void test() { + List set = EzyLists.combine(Sets.newHashSet("1", "2", "3"), + Sets.newHashSet("4", "5", "6")); + assertEquals(set, Lists.newArrayList("1", "2", "3", "4", "5", "6")); + + Collection coll1 = Lists.newArrayList("ab", "cde"); + List set1 = EzyLists.newHashSetByAddAll(coll1, this::stringtoChars); + assertEquals(set1, Lists.newArrayList('a', 'b', 'c', 'd', 'e')); + + List set2 = EzyLists.filter(set, + (str) -> (!str.startsWith("1") && !str.startsWith("5"))); + assertEquals(set2, Lists.newArrayList("2", "3", "4", "6")); + + List set3 = EzyLists.newArrayList(set, "3" ,"4"); + assertEquals(set3, Lists.newArrayList("1", "2", "5", "6")); + + List set4 = EzyLists.newArrayList(new Long[] {1L, 2L, 3L}, v -> v.toString()); + assertEquals(set4, Lists.newArrayList("1", "2", "3")); + + List set5 = EzyLists.newArrayList(Lists.newArrayList(1L, 2L, 3L), v -> v.toString()); + assertEquals(set5, Lists.newArrayList("1", "2", "3")); + + Map map = new HashMap<>(); + map.put("a", 1L); + map.put("b", 2L); + List set6 = EzyLists.newArrayList(map, (k, v) -> v + k); + assertEquals(set6, Lists.newArrayList("1a", "2b")); + + List set7 = EzyLists.addElementsToNewList(new ArrayList<>(), "1", "2", "3"); + assertEquals(set7, Lists.newArrayList("1", "2", "3")); + } + + private Collection stringtoChars(String str) { + List answer = new ArrayList<>(); + for(int i = 0 ; i < str.length() ; i++) + answer.add(str.charAt(i)); + return answer; + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLongsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLongsTest.java new file mode 100644 index 00000000..39e51798 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyLongsTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.ezyfoxserver.io.EzyLongs; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +import java.nio.ByteBuffer; + +public class EzyLongsTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyLongs.bin2long(63), Long.MAX_VALUE); + assertEquals(EzyLongs.bin2long( + EzyBytes.getBytes(ByteBuffer.allocate(8).putLong(-100L))), -100L); + assertEquals(EzyLongs.bin2ulong( + EzyBytes.getBytes(ByteBuffer.allocate(8).putLong(100L))), 100L); + ByteBuffer buffer1 = ByteBuffer.allocate(8).putLong(-1000L); + buffer1.flip(); + assertEquals(EzyLongs.bin2long(buffer1), -1000L); + + ByteBuffer buffer2 = ByteBuffer.allocate(8).putLong(1000L); + buffer2.flip(); + assertEquals(EzyLongs.bin2ulong(buffer2), 1000L); + } + + @Override + public Class getTestClass() { + return EzyLongs.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMapsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMapsTest.java new file mode 100644 index 00000000..5cb552b8 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMapsTest.java @@ -0,0 +1,203 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.io.EzyMaps; +import com.tvd12.ezyfoxserver.util.EzyMapBuilder; +import com.tvd12.test.base.BaseTest; + +public class EzyMapsTest extends BaseTest { + + @Test + public void test() { + Map map = new HashMap<>(); + ClassA classA = new ClassA(); + ClassD classD = new ClassD(); + ClassJ classJ = new ClassJ(); + map.put(InterfaceA.class, classA); + map.put(ClassD.class, classD); + map.put(ClassF.class, classJ); + assert EzyMaps.getValue(map, ClassA.class) == classA; + assert EzyMaps.getValue(map, ClassE.class) == classD; + assert EzyMaps.getValue(map, ClassJ.class) == classJ; + } + + @Test + public void test2() { + Map map = new HashMap<>(); + map.put("1", "a"); + map.put("2", "b"); + assertEquals(EzyMaps.getValueList(map), new ArrayList<>(map.values())); + assertEquals(EzyMaps.getValueSet(map), new HashSet<>(map.values())); + } + + @Test + public void test3() { + Map map = new HashMap<>(); + map.put("1", "a"); + map.put("2", "b"); + map.put("3", "c"); + Map map1 = + EzyMaps.newHashMapNewKeys(map, (k) -> Long.valueOf(k)); + assertEquals(map1.keySet(), Sets.newHashSet(1L, 2L, 3L)); + assertEquals(map1.values(), Sets.newHashSet("a", "b", "c")); + } + + @Test + public void test4() { + Collection coll = Sets.newHashSet("1", "2", "3"); + Map map = EzyMaps.newHashMap(coll, (v)->Long.valueOf(v)); + assertEquals(map.keySet(), Sets.newHashSet(1L, 2L, 3L)); + assertEquals(map.values(), Sets.newHashSet("1", "2", "3")); + } + + @Test + public void test5() { + Map map = new HashMap<>(); + map.put("1", "a"); + map.put("2", "b"); + map.put("3", "c"); + Map map1 = + EzyMaps.newHashMapNewValues(map, (v) -> v.charAt(0)); + assertEquals(map1.keySet(), Sets.newHashSet("1", "2", "3")); + assertEquals(map1.values(), Sets.newHashSet('a', 'b', 'c')); + } + + @Test + public void test6() { + Map map = new HashMap<>(); + map.put("1", "a"); + map.put("2", "b"); + map.put("3", "c"); + Map map1 = + EzyMaps.getValues(map, Lists.newArrayList("1", "2", "5")); + assertEquals(map1.values(), Sets.newHashSet("a", "b")); + } + + @Test + public void test7() { + Map map = new HashMap<>(); + map.put("1", "a"); + map.put("2", "b"); + map.put("3", "c"); + List list = + EzyMaps.getValues(map, (v) -> !v.startsWith("b")); + assertEquals(list, Lists.newArrayList("a", "c")); + } + + @Test + public void test8() { + Map> map = new HashMap<>(); + EzyMaps.addItemsToList(map, "1", "a", "b", "c", "d", "e"); + assertEquals(map.get("1"), Lists.newArrayList("a", "b", "c", "d", "e")); + EzyMaps.removeItems(map, "2", "d", "e"); + EzyMaps.removeItems(map, "1", "d", "e"); + assertEquals(map.get("1"), Lists.newArrayList("a", "b", "c")); + } + + @Test + public void test9() { + Map> map = new HashMap<>(); + EzyMaps.addItemsToSet(map, "1", "a", "b", "c", "d", "e"); + assertEquals(map.get("1"), Sets.newHashSet("a", "b", "c", "d", "e")); + } + + @Test + public void test1() { + assert EzyMaps.getValue(new HashMap<>(), Object.class) == null; + } + + @Test + public void test10() { + Map map = EzyMaps.newHashMap("a", "b"); + assert map.get("a").equals("b"); + } + + @SuppressWarnings("unchecked") + @Test + public void test11() { + Map map1 = EzyMapBuilder.mapBuilder() + .put("1", "a") + .put("2", "b") + .put("3", "c") + .build(); + Map map2 = EzyMapBuilder.mapBuilder() + .put("1", "a") + .put("3", "c") + .build(); + assert EzyMaps.containsAll(map1, map2); + + Map map1a = EzyMapBuilder.mapBuilder() + .put("1", "a") + .put("2", "b") + .put("3", "c") + .build(); + Map map2a = EzyMapBuilder.mapBuilder() + .put("1", "a") + .put("2", "f") + .build(); + assert !EzyMaps.containsAll(map1a, map2a); + + Map map1b = EzyMapBuilder.mapBuilder() + .put("1", "a") + .put("2", "b") + .put("3", "c") + .build(); + Map map2b = EzyMapBuilder.mapBuilder() + .put("x", "a") + .put("y", "f") + .build(); + assert !EzyMaps.containsAll(map1b, map2b); + } + + @Override + public Class getTestClass() { + return EzyMaps.class; + } + + public static interface InterfaceA { + + } + + public static interface InterfaceB { + + } + + public static class ClassA implements InterfaceA { + + } + + public static class ClassB extends ClassA { + + } + + public static class ClassD { + + } + + public static class ClassE extends ClassD { + + } + + + public static class ClassF { + + } + + public static class ClassJ extends ClassF implements InterfaceB { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMathTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMathTest.java new file mode 100644 index 00000000..8690307c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyMathTest.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyBytes; +import com.tvd12.ezyfoxserver.io.EzyMath; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +import java.nio.ByteBuffer; + +public class EzyMathTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyMath.bin2uint( + new byte[] {1, 2, 3, 4}), + ByteBuffer.wrap(new byte[] {1, 2, 3, 4}).getInt()); + assertEquals(EzyMath.bin2int(8), 255); + + assertEquals(EzyMath.bin2ulong( + new byte[] {1, 2, 3, 4, 5, 6, 7, 8}), + ByteBuffer.wrap(new byte[] {1, 2, 3, 4, 5, 6, 7, 8}).getLong()); + assertEquals(EzyMath.bin2long(40), 1099511627775L); + + assertEquals(EzyMath.bin2int( + getBytes(ByteBuffer.allocate(4).putInt(-100))), + -100); + + assertEquals(EzyMath.bin2long( + getBytes(ByteBuffer.allocate(8).putLong(-100000))), + -100000L); + byte[] xor = new byte[] {(byte) 255, (byte) 255, (byte) 255}; + EzyMath.xor(xor); + assertEquals(xor, new byte[] {0, 0, 0}); + } + + protected byte[] getBytes(ByteBuffer buffer) { + return EzyBytes.getBytes(buffer); + } + + @Override + public Class getTestClass() { + return EzyMath.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyNumbersConverterTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyNumbersConverterTest.java new file mode 100644 index 00000000..536590fd --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyNumbersConverterTest.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzyNumbersConverter; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; +import static com.tvd12.ezyfoxserver.io.EzyNumbersConverter.*; + +public class EzyNumbersConverterTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyNumbersConverter.class; + } + + @Test + public void test() { + assertEquals(numbersToPrimitiveBytes(Lists.newArrayList(1,2,3)), + new byte[] {1, 2, 3}); + assertEquals(numbersToPrimitiveChars(Lists.newArrayList(1,2,3)), + new char[] {1, 2, 3}); + assertEquals(numbersToPrimitiveDoubles(Lists.newArrayList(1,2,3)), + new double[] {1, 2, 3}); + assertEquals(numbersToPrimitiveFloats(Lists.newArrayList(1,2,3)), + new float[] {1, 2, 3}); + assertEquals(numbersToPrimitiveInts(Lists.newArrayList(1,2,3)), + new int[] {1, 2, 3}); + assertEquals(numbersToPrimitiveLongs(Lists.newArrayList(1,2,3)), + new long[] {1, 2, 3}); + assertEquals(numbersToPrimitiveShorts(Lists.newArrayList(1,2,3)), + new short[] {1, 2, 3}); + + assertEquals(objectsToWrapperNumbers(Lists.newArrayList("1", "2", "3"), + (size) -> new Long[size], (str) -> Long.valueOf(str)), + new Long[] {1L, 2L, 3L}); + + assertEquals(numbersToWrapperNumbers(Lists.newArrayList(1,2,3), + (size) -> new Long[size], (number) -> number.longValue()), + new Long[] {1L, 2L, 3L}); + + assertEquals(numbersToWrapperBytes(Lists.newArrayList(1,2,3)), + new Byte[] {1, 2, 3}); + assertEquals(numbersToWrapperChars(Lists.newArrayList(1,2,3)), + new Character[] {1, 2, 3}); + assertEquals(numbersToWrapperDoubles(Lists.newArrayList(1,2,3)), + new Double[] {1D, 2D, 3D}); + assertEquals(numbersToWrapperFloats(Lists.newArrayList(1,2,3)), + new Float[] {1F, 2F, 3F}); + assertEquals(numbersToWrapperInts(Lists.newArrayList(1,2,3)), + new Integer[] {1, 2, 3}); + assertEquals(numbersToWrapperLongs(Lists.newArrayList(1,2,3)), + new Long[] {1L, 2L, 3L}); + assertEquals(numbersToWrapperShorts(Lists.newArrayList(1,2,3)), + new Short[] {1, 2, 3}); + assertEquals(objectToChar('a'), new Character('a')); + } + + @Test + public void convertNumberTest() { + Byte value = EzyNumbersConverter.convertNumber((Object)new Long(100), n -> n.byteValue()); + System.err.println("value = " + value); + assert value == 100; + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyPrintsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyPrintsTest.java new file mode 100644 index 00000000..8df93c30 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyPrintsTest.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzyPrints; +import com.tvd12.test.base.BaseTest; + +public class EzyPrintsTest extends BaseTest { + + @Test + public void test() { + System.err.println(EzyPrints.printBits((byte)5)); + System.err.println(EzyPrints.printBits(new byte[] {1, 2, 3})); + + System.err.println(EzyPrints.print(null)); + System.err.println(EzyPrints.print(new boolean[] {true, false, true})); + System.err.println(EzyPrints.print(new byte[] {1, 2, 3})); + System.err.println(EzyPrints.print(new char[] {'a', 'b', 'c'})); + System.err.println(EzyPrints.print(new double[] {1, 2, 3})); + System.err.println(EzyPrints.print(new float[] {1, 2, 3})); + System.err.println(EzyPrints.print(new int[] {1, 2, 3})); + System.err.println(EzyPrints.print(new long[] {1, 2, 3})); + System.err.println(EzyPrints.print(new short[] {1, 2, 3})); + System.err.println(EzyPrints.print(new String[] {"x", "y", "z"})); + System.err.println(EzyPrints.print(Lists.newArrayList("x", "y", "z"))); + } + + @Override + public Class getTestClass() { + return EzyPrints.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySetsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySetsTest.java new file mode 100644 index 00000000..ce290b93 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySetsTest.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.io.EzySets; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzySetsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzySets.class; + } + + @SuppressWarnings("unchecked") + @Test + public void test() { + Set set = EzySets.combine(Sets.newHashSet("1", "2", "3"), + Sets.newHashSet("4", "5", "6")); + assertEquals(set, Sets.newHashSet("1", "2", "3", "4", "5", "6")); + + Collection coll1 = Lists.newArrayList("ab", "cde"); + Set set1 = EzySets.newHashSetByAddAll(coll1, this::stringtoChars); + assertEquals(set1, Sets.newHashSet('a', 'b', 'c', 'd', 'e')); + + Set set2 = EzySets.filter(set, + (str) -> (!str.startsWith("1") && !str.startsWith("5"))); + assertEquals(set2, Sets.newHashSet("2", "3", "4", "6")); + + Set set3 = EzySets.newHashSet(set, "3" ,"4"); + assertEquals(set3, Sets.newHashSet("1", "2", "5", "6")); + + Set set4 = EzySets.newHashSet(new Long[] {1L, 2L, 3L}, v -> v.toString()); + assertEquals(set4, Sets.newHashSet("1", "2", "3")); + + Set set5 = EzySets.newHashSet(Lists.newArrayList(1L, 2L, 3L), v -> v.toString()); + assertEquals(set5, Sets.newHashSet("1", "2", "3")); + + Map map = new HashMap<>(); + map.put("a", 1L); + map.put("b", 2L); + Set set6 = EzySets.newHashSet(map, (k, v) -> v + k); + assertEquals(set6, Sets.newHashSet("1a", "2b")); + + Set set7 = EzySets.addElementsToNewSet(new HashSet<>(), "1", "2", "3"); + assertEquals(set7, Sets.newHashSet("1", "2", "3")); + } + + private Collection stringtoChars(String str) { + List answer = new ArrayList<>(); + for(int i = 0 ; i < str.length() ; i++) + answer.add(str.charAt(i)); + return answer; + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerOtherTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerOtherTest.java new file mode 100644 index 00000000..22762ca9 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerOtherTest.java @@ -0,0 +1,33 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.Date; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyDates; +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerOtherTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assert transformer.convert("abc", Date.class) == null; + assert transformer.convert("2017-10-10T10:10:10:10", Date.class) != null; + + assert transformer.convert("abc", LocalDate.class) == null; + assert transformer.convert("2017-10-10", LocalDate.class) != null; + + assert transformer.convert("abc", LocalDateTime.class) == null; + assert transformer.convert(EzyDates.format(LocalDateTime.now()), LocalDateTime.class) != null; + + assert transformer.convert("", Class.class) == null; + assert transformer.convert(getClass().getName(), Class.class) != null; + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArrayTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArrayTest.java new file mode 100644 index 00000000..871f6888 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArrayTest.java @@ -0,0 +1,106 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerPrimitiveArrayTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assertEquals(transformer.convert("true,false,true", boolean[].class), new boolean[] {true, false, true}); + assertEquals(transformer.convert(new boolean[] {true, false, true}, boolean[].class), new boolean[] {true, false, true}); + assertEquals(transformer.convert(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, boolean[].class), new boolean[] {true, false, true}); + assertEquals(transformer.convert(Lists.newArrayList(true, false, true), boolean[].class), new boolean[] {true, false, true}); + + assertEquals(transformer.convert("1,2,3", byte[].class), new byte[] {1, 2, 3}); + assertEquals(transformer.convert(new byte[] {1, 2, 3}, byte[].class), new byte[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, byte[].class), new byte[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), byte[].class), new byte[] {1, 2, 3}); + + assertEquals(transformer.convert("123", char[].class), new char[] {'1', '2', '3'}); + assertEquals(transformer.convert(new char[] {1, 2, 3}, char[].class), new char[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, char[].class), new char[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), char[].class), new char[] {1, 2, 3}); + + assertEquals(transformer.convert("1.1,2.2,3.3", double[].class), new double[] {1.1D, 2.2D, 3.3D}); + assertEquals(transformer.convert(new double[] {1D, 2D, 3D}, double[].class), new double[] {1.0D, 2.0D, 3.0D}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, double[].class), new double[] {1.0D, 2.0D, 3.0D}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), double[].class), new double[] {1, 2, 3}); + + assertEquals(transformer.convert("1.1,2.2,3.3", float[].class), new float[] {1.1F, 2.2F, 3.3F}); + assertEquals(transformer.convert(new float[] {1F, 2F, 3F}, float[].class), new float[] {1.0F, 2.0F, 3.0F}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, float[].class), new float[] {1.0F, 2.0F, 3.0F}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), float[].class), new float[] {1, 2, 3}); + + assertEquals(transformer.convert("1,2,3", int[].class), new int[] {1, 2, 3}); + assertEquals(transformer.convert(new int[] {1, 2, 3}, int[].class), new int[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, int[].class), new int[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), int[].class), new int[] {1, 2, 3}); + + assertEquals(transformer.convert("1,2,3", long[].class), new long[] {1, 2, 3}); + assertEquals(transformer.convert(new long[] {1L, 2L, 3L}, long[].class), new long[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, long[].class), new long[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), long[].class), new long[] {1, 2, 3}); + + assertEquals(transformer.convert("1,2,3", short[].class), new short[] {1, 2, 3}); + assertEquals(transformer.convert(new short[] {1, 2, 3}, short[].class), new short[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, short[].class), new short[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), short[].class), new short[] {1, 2, 3}); + + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), boolean[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), byte[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), char[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), double[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), float[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), int[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), long[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), short[].class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArraysTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArraysTest.java new file mode 100644 index 00000000..48273ee7 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveArraysTest.java @@ -0,0 +1,97 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerPrimitiveArraysTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assertEquals(transformer.convert("true,false,true;true,false,true", boolean[][].class), new boolean[][] {{true, false, true},{true, false, true}}); + assertEquals(transformer.convert(new boolean[][] {{true, false, true},{true, false, true}}, boolean[][].class), new boolean[][] {{true, false, true},{true, false, true}}); + assertEquals(transformer.convert(new Boolean[][] {{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE},{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}}, boolean[][].class), new boolean[][] {{true, false, true},{true, false, true}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", byte[][].class), new byte[][] {{1, 2, 3}, {1, 2, 3}}); + assertEquals(transformer.convert(new byte[][] {{1, 2, 3}, {1, 2, 3}}, byte[][].class), new byte[][] {{1, 2, 3}, {1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3}, {1, 2, 3}}, byte[][].class), new byte[][] {{1, 2, 3}, {1, 2, 3}}); + + assertEquals(transformer.convert("123;123", char[][].class), new char[][] {{'1', '2', '3'},{'1', '2', '3'}}); + assertEquals(transformer.convert(new char[][] {{1, 2, 3},{1, 2, 3}}, char[][].class), new char[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, char[][].class), new char[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1.1,2.2,3.3;1.1,2.2,3.3", double[][].class), new double[][] {{1.1D, 2.2D, 3.3D},{1.1D, 2.2D, 3.3D}}); + assertEquals(transformer.convert(new double[][] {{1D, 2D, 3D},{1D, 2D, 3D}}, double[][].class), new double[][] {{1.0D, 2.0D, 3.0D}, {1.0D, 2.0D, 3.0D}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, double[][].class), new double[][] {{1.0D, 2.0D, 3.0D},{1.0D, 2.0D, 3.0D}}); + + assertEquals(transformer.convert("1.1,2.2,3.3;1.1,2.2,3.3", float[][].class), new float[][] {{1.1F, 2.2F, 3.3F},{1.1F, 2.2F, 3.3F}}); + assertEquals(transformer.convert(new float[][] {{1F,2F,3F},{1F, 2F, 3F}}, float[][].class), new float[][] {{1.0F, 2.0F, 3.0F}, {1.0F, 2.0F, 3.0F}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, float[][].class), new float[][] {{1.0F, 2.0F, 3.0F},{1.0F, 2.0F, 3.0F}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", int[][].class), new int[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new int[][] {{1, 2, 3},{1, 2, 3}}, int[][].class), new int[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, int[][].class), new int[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", long[][].class), new long[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new long[][] {{1L,2L,3L},{1L, 2L, 3L}}, long[][].class), new long[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, long[][].class), new long[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", short[][].class), new short[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new short[][] {{1, 2, 3},{1, 2, 3}}, short[][].class), new short[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, short[][].class), new short[][] {{1, 2, 3},{1, 2, 3}}); + + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), boolean[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), byte[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), char[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), double[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), float[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), int[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), long[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), short[][].class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveTest.java new file mode 100644 index 00000000..4e825df3 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerPrimitiveTest.java @@ -0,0 +1,98 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerPrimitiveTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assert transformer.convert("true", boolean.class); + assert !transformer.convert("false", boolean.class); + assert transformer.convert("TRUE", boolean.class); + assert !transformer.convert("FALSE", boolean.class); + assert transformer.convert(Boolean.TRUE, boolean.class); + + assert transformer.convert("1", byte.class) == (byte)1; + assert transformer.convert(1.0D, byte.class) == (byte)1; + + assert transformer.convert(new Character('a'), char.class) == 'a'; + assert transformer.convert(1.0D, char.class) == (char)1; + assert transformer.convert("a", char.class) == 'a'; + + assert transformer.convert("1.0", double.class) == 1.0D; + assert transformer.convert(1L, double.class) == 1.0D; + + assert transformer.convert("1.0", float.class) == 1.0F; + assert transformer.convert(1L, float.class) == 1.0F; + + assert transformer.convert("1", int.class) == 1; + assert transformer.convert(1.0D, int.class) == 1; + + assert transformer.convert("1", long.class) == 1L; + assert transformer.convert(1.0D, long.class) == 1L; + + assert transformer.convert("1", short.class) == (short)1; + assert transformer.convert(1.0D, short.class) == (short)1; + + assert transformer.convert(1, String.class).equals("1"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), boolean.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), byte.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), char.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test31() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert("abc", char.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), double.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), float.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), int.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), long.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), short.class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerTest.java new file mode 100644 index 00000000..b6120db1 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerTest.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import java.util.List; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assert transformer.convert(null, null) == null; + } + + @SuppressWarnings({ "unused", "unchecked" }) + @Test + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + List v = transformer.convert(Lists.newArrayList(1, 2, 3), List.class); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArrayTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArrayTest.java new file mode 100644 index 00000000..7f238867 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArrayTest.java @@ -0,0 +1,116 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerWrapperArrayTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assertEquals(transformer.convert("true,false,true", Boolean[].class), new Boolean[] {true, false, true}); + assertEquals(transformer.convert(new boolean[] {true, false, true}, Boolean[].class), new Boolean[] {true, false, true}); + assertEquals(transformer.convert(new Boolean[] {Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}, Boolean[].class), new Boolean[] {true, false, true}); + assertEquals(transformer.convert(Lists.newArrayList(true, false, true), Boolean[].class), new Boolean[] {true, false, true}); + + assertEquals(transformer.convert("1,2,3", Byte[].class), new Byte[] {1, 2, 3}); + assertEquals(transformer.convert(new byte[] {1, 2, 3}, Byte[].class), new Byte[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Byte[].class), new Byte[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Byte[].class), new Byte[] {1, 2, 3}); + + assertEquals(transformer.convert("123", Character[].class), new Character[] {'1', '2', '3'}); + assertEquals(transformer.convert(new char[] {1, 2, 3}, Character[].class), new Character[] {1, 2, 3}); + assertEquals(transformer.convert(new Character[] {1, 2, 3}, Character[].class), new Character[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Character[].class), new Character[] {1, 2, 3}); + + assertEquals(transformer.convert("1.1,2.2,3.3", Double[].class), new Double[] {1.1D, 2.2D, 3.3D}); + assertEquals(transformer.convert(new double[] {1D, 2D, 3D}, Double[].class), new Double[] {1.0D, 2.0D, 3.0D}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Double[].class), new Double[] {1.0D, 2.0D, 3.0D}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Double[].class), new Double[] {1D, 2D, 3D}); + + assertEquals(transformer.convert("1.1,2.2,3.3", Float[].class), new Float[] {1.1F, 2.2F, 3.3F}); + assertEquals(transformer.convert(new float[] {1F, 2F, 3F}, Float[].class), new Float[] {1.0F, 2.0F, 3.0F}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Float[].class), new Float[] {1.0F, 2.0F, 3.0F}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Float[].class), new Float[] {1F, 2F, 3F}); + + assertEquals(transformer.convert("1,2,3", Integer[].class), new Integer[] {1, 2, 3}); + assertEquals(transformer.convert(new int[] {1, 2, 3}, Integer[].class), new Integer[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Integer[].class), new Integer[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Integer[].class), new Integer[] {1, 2, 3}); + + assertEquals(transformer.convert("1,2,3", Long[].class), new Long[] {1L, 2L, 3L}); + assertEquals(transformer.convert(new long[] {1L, 2L, 3L}, Long[].class), new Long[] {1L, 2L, 3L}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Long[].class), new Long[] {1L, 2L, 3L}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Long[].class), new Long[] {1L, 2L, 3L}); + + assertEquals(transformer.convert("1,2,3", Short[].class), new Short[] {1, 2, 3}); + assertEquals(transformer.convert(new short[] {1, 2, 3}, Short[].class), new Short[] {1, 2, 3}); + assertEquals(transformer.convert(new Integer[] {1, 2, 3}, Short[].class), new Short[] {1, 2, 3}); + assertEquals(transformer.convert(Lists.newArrayList(1, 2, 3), Short[].class), new Short[] {1, 2, 3}); + + assertEquals(transformer.convert("1,2,3", String[].class), new String[] {"1", "2", "3"}); + assertEquals(transformer.convert(new String[] {"1", "2", "3"}, String[].class), new String[] {"1", "2", "3"}); + assertEquals(transformer.convert(Lists.newArrayList("1", "2", "3"), String[].class), new String[] {"1", "2", "3"}); + + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Boolean[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Byte[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Character[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Double[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Float[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Integer[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Long[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Short[].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test9() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), String[].class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArraysTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArraysTest.java new file mode 100644 index 00000000..4414a0e4 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperArraysTest.java @@ -0,0 +1,106 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerWrapperArraysTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assertEquals(transformer.convert("true,false,true;true,false,true", Boolean[][].class), new Boolean[][] {{true, false, true},{true, false, true}}); + assertEquals(transformer.convert(new boolean[][] {{true, false, true},{true, false, true}}, Boolean[][].class), new Boolean[][] {{true, false, true},{true, false, true}}); + assertEquals(transformer.convert(new Boolean[][] {{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE},{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}}, Boolean[][].class), new Boolean[][] {{true, false, true},{true, false, true}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", Byte[][].class), new Byte[][] {{1, 2, 3}, {1, 2, 3}}); + assertEquals(transformer.convert(new byte[][] {{1, 2, 3}, {1, 2, 3}}, Byte[][].class), new Byte[][] {{1, 2, 3}, {1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3}, {1, 2, 3}}, Byte[][].class), new Byte[][] {{1, 2, 3}, {1, 2, 3}}); + + assertEquals(transformer.convert("123;123", Character[][].class), new Character[][] {{'1', '2', '3'},{'1', '2', '3'}}); + assertEquals(transformer.convert(new char[][] {{1, 2, 3},{1, 2, 3}}, Character[][].class), new Character[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Character[][].class), new Character[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1.1,2.2,3.3;1.1,2.2,3.3", Double[][].class), new Double[][] {{1.1D, 2.2D, 3.3D},{1.1D, 2.2D, 3.3D}}); + assertEquals(transformer.convert(new double[][] {{1D, 2D, 3D},{1D, 2D, 3D}}, Double[][].class), new Double[][] {{1.0D, 2.0D, 3.0D}, {1.0D, 2.0D, 3.0D}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Double[][].class), new Double[][] {{1.0D, 2.0D, 3.0D},{1.0D, 2.0D, 3.0D}}); + + assertEquals(transformer.convert("1.1,2.2,3.3;1.1,2.2,3.3", Float[][].class), new Float[][] {{1.1F, 2.2F, 3.3F},{1.1F, 2.2F, 3.3F}}); + assertEquals(transformer.convert(new float[][] {{1F,2F,3F},{1F, 2F, 3F}}, Float[][].class), new Float[][] {{1.0F, 2.0F, 3.0F}, {1.0F, 2.0F, 3.0F}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Float[][].class), new Float[][] {{1.0F, 2.0F, 3.0F},{1.0F, 2.0F, 3.0F}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", Integer[][].class), new Integer[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new int[][] {{1, 2, 3},{1, 2, 3}}, Integer[][].class), new Integer[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Integer[][].class), new Integer[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", Long[][].class), new Long[][] {{1L, 2L, 3L},{1L, 2L, 3L}}); + assertEquals(transformer.convert(new long[][] {{1L,2L,3L},{1L, 2L, 3L}}, Long[][].class), new Long[][] {{1L, 2L, 3L},{1L, 2L, 3L}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Long[][].class), new Long[][] {{1L, 2L, 3L},{1L, 2L, 3L}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", Short[][].class), new Short[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new short[][] {{1, 2, 3},{1, 2, 3}}, Short[][].class), new Short[][] {{1, 2, 3},{1, 2, 3}}); + assertEquals(transformer.convert(new Integer[][] {{1, 2, 3},{1, 2, 3}}, Short[][].class), new Short[][] {{1, 2, 3},{1, 2, 3}}); + + assertEquals(transformer.convert("1,2,3;1,2,3", String[][].class), new String[][] {{"1", "2", "3"},{"1", "2", "3"}}); + assertEquals(transformer.convert(new String[][] {{"1", "2", "3"},{"1", "2", "3"}}, String[][].class), new String[][] {{"1", "2", "3"},{"1", "2", "3"}}); + + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Boolean[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Byte[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Character[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Double[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Float[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Integer[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Long[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Short[][].class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test9() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), String[][].class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperTest.java new file mode 100644 index 00000000..851b20f0 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzySimpleValueTransformerWrapperTest.java @@ -0,0 +1,96 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzySimpleValueConverter; +import com.tvd12.ezyfoxserver.io.EzyValueConverter; +import com.tvd12.test.base.BaseTest; + +public class EzySimpleValueTransformerWrapperTest extends BaseTest { + + @Test + public void test() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + assert transformer.convert("true", Boolean.class); + assert !transformer.convert("false", Boolean.class); + assert transformer.convert("TRUE", Boolean.class); + assert !transformer.convert("FALSE", Boolean.class); + assert transformer.convert(Boolean.TRUE, Boolean.class); + + assert transformer.convert("1", Byte.class) == (byte)1; + assert transformer.convert(1.0D, Byte.class) == (byte)1; + + assert transformer.convert(new Character('a'), Character.class) == 'a'; + assert transformer.convert(1.0D, Character.class) == (char)1; + assert transformer.convert("a", Character.class) == 'a'; + + assert transformer.convert("1.0", Double.class) == 1.0D; + assert transformer.convert(1L, Double.class) == 1.0D; + + assert transformer.convert("1.0", Float.class) == 1.0F; + assert transformer.convert(1L, Float.class) == 1.0F; + + assert transformer.convert("1", Integer.class) == 1; + assert transformer.convert(1.0D, Integer.class) == 1; + + assert transformer.convert("1", Long.class) == 1L; + assert transformer.convert(1.0D, Long.class) == 1L; + + assert transformer.convert("1", Short.class) == (short)1; + assert transformer.convert(1.0D, Short.class) == (short)1; + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test1() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Boolean.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test2() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Byte.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test3() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Character.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test31() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert("abc", Character.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test4() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Double.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test5() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Float.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test6() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Integer.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test7() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Long.class); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void test8() { + EzyValueConverter transformer = new EzySimpleValueConverter(); + transformer.convert(new Object(), Short.class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringConveterTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringConveterTest.java new file mode 100644 index 00000000..3c3d6633 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringConveterTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import com.tvd12.ezyfoxserver.io.EzyStringConveter; +import com.tvd12.test.base.BaseTest; + +public class EzyStringConveterTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyStringConveter.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringsTest.java new file mode 100644 index 00000000..8cfe7157 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/io/EzyStringsTest.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.testing.io; + +import static org.testng.Assert.assertEquals; + +import java.nio.ByteBuffer; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.io.EzyStrings; +import com.tvd12.test.base.BaseTest; + +public class EzyStringsTest extends BaseTest { + + @Test + public void test() throws Exception { + assertEquals("abc", EzyStrings.newUtf("abc".getBytes("UTF-8"))); + assertEquals("abc", EzyStrings.newUtf(ByteBuffer.wrap("abc".getBytes("UTF-8")), 3)); + assertEquals(EzyStrings.getUtfBytes("abc"), "abc".getBytes("UTF-8")); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyStrings.newString(new byte[] {1, 2, 3}, "kkk"); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyStrings.getBytes("abc", "hhh"); + } + + @Test + public void test3() { + String[] array = new String[] {"1", "2", "3"}; + assert EzyStrings.getString(array, 1, "x").equals("2"); + assert EzyStrings.getString(array, 100, "x").equals("x"); + } + + @Override + public Class getTestClass() { + return EzyStrings.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/properties/EzySimplePropertiesReaderTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/properties/EzySimplePropertiesReaderTest.java new file mode 100644 index 00000000..dc77d8e8 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/properties/EzySimplePropertiesReaderTest.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.testing.properties; + +import java.util.HashMap; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.properties.EzyPropertiesReader; +import com.tvd12.ezyfoxserver.properties.EzySimplePropertiesReader; +import com.tvd12.test.base.BaseTest; + +public class EzySimplePropertiesReaderTest extends BaseTest { + + @Test + public void test() { + EzyPropertiesReader reader = new EzySimplePropertiesReader(); + Map map = new HashMap<>(); + assert !reader.containsKey(map, "hello"); + map.put("hello", "world"); + assert reader.get(map, "hello").equals("world"); + assert reader.get(map, "hello", String.class).equals("world"); + assert reader.get(map, "foo", "bar").equals("bar"); + assert reader.get(map, "foo", String.class, "bar").equals("bar"); + map.put("foo", "bar"); + assert reader.get(map, "foo", "bar").equals("bar"); + assert reader.get(map, "foo", String.class, "bar").equals("bar"); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/AImpl.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/AImpl.java new file mode 100644 index 00000000..3419131c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/AImpl.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +public class AImpl { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ClassTypeTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ClassTypeTest.java new file mode 100644 index 00000000..f87b1af7 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ClassTypeTest.java @@ -0,0 +1,19 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Map; + +public class ClassTypeTest { + + @SuppressWarnings("rawtypes") + public static void main(String[] args) { + System.out.println(ClassTypeTest.class instanceof Type); + + Map map = new HashMap<>(); + Class clazz = map.getClass(); + System.out.println((Type)clazz instanceof ParameterizedType); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ExampleAnnotation.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ExampleAnnotation.java new file mode 100644 index 00000000..d9075685 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/ExampleAnnotation.java @@ -0,0 +1,32 @@ +/** + * + */ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.LOCAL_VARIABLE; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PACKAGE; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.ElementType.TYPE_PARAMETER; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Documented +@Retention(RUNTIME) +@Target({ TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, + TYPE_USE }) +/** + * @author tavandung12 + * + */ +public @interface ExampleAnnotation { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassTest.java new file mode 100644 index 00000000..7b689867 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassTest.java @@ -0,0 +1,105 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; +import lombok.Setter; + +public class EzyClassTest extends BaseTest { + + @Test + public void test() { + EzyClass clazz = new EzyClass(A.class); + assertEquals(clazz.getName(), A.class.getName()); + assertTrue(clazz.isAnnotated(ExampleAnnotation.class)); + ExampleAnnotation ann = clazz.getAnnotation(ExampleAnnotation.class); + assertNotNull(ann); + assertTrue(clazz.getPublicMethods().size() == 10); + assertTrue(clazz.getSetterMethods().size() == 5); + assertTrue(clazz.getGetterMethods().size() == 5); + assertTrue(clazz.getPublicMethods(m -> !m.getName().contains("D")).size() == 8); + assertTrue(clazz.getSetterMethods(m -> !m.getName().contains("D")).size() == 4); + assertTrue(clazz.getGetterMethods(m -> !m.getName().contains("D")).size() == 4); + assertTrue(clazz.getGetterMethods(m -> !m.getName().contains("D")).size() == 4); + System.err.println("size = " + clazz.getMethods(m -> !m.getName().contains("D")).size()); + assertEquals(clazz.getMethods(m -> !m.getName().contains("D")).size(), 9 + 2); + assertEquals(clazz.getFields().size(), 10 + 2); + assertEquals(clazz.getWritableFields().size(), 9 + 2); + assertEquals(clazz.getPublicFields().size(), 4); + assertEquals(clazz.getPublicFields(f -> !f.getName().equals("a")).size(), 3); + assertEquals(clazz.getFields(f -> !f.getName().equals("a")).size(), 9 + 2); + clazz.getMethods(m -> !m.getName().contains("D"), m -> new EzyMethod(m.getMethod())); + assertTrue(clazz.toString().equals(A.class.toString())); + assertEquals(clazz.getClazz(), A.class); + assertEquals(clazz.getMethods().size(), 11 + 2); + + assertEquals(clazz.getDeclaredFields().size(), 6 + 1); + assertEquals(clazz.getDeclaredMethods().size(), 6 + 1); + System.err.println("fields = " + clazz.getDeclaredFields()); + System.err.println("methods = " + clazz.getDeclaredMethods()); + assert clazz.getField("x") != null; + clazz.getDeclaredMethods(m -> true); + clazz.getDeclaredSetterMethods(); + clazz.getDeclaredGetterMethods(); + clazz.getFieldsByName(); + clazz.getMethodsByName(); + clazz.getMethod("setY"); + clazz.newInstance(); + clazz.getDeclaredConstructors(); + clazz.getDeclaredConstructor(); + + assert clazz.getModifiers() == clazz.getClazz().getModifiers(); + } + + public static class B { + public String x = "x"; + + @Setter + @Getter + protected String y = "y"; + + @Getter + @Setter + private String z = "z"; + + protected static final String FINAL_FIELD = "final field"; + + protected String protectedMethod() { + return "a"; + } + } + + @ExampleAnnotation + public static class A extends B { + + public String a = "a"; + public String b = "b"; + @ExampleAnnotation + public String c = "c"; + + @Setter + @Getter + @ExampleAnnotation + private String d = "d"; + + @Setter + @Getter + @ExampleAnnotation + private String e = "e"; + + @Setter + @Getter + @ExampleAnnotation + private String f = "f"; + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClasses1Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClasses1Test.java new file mode 100644 index 00000000..18a14802 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClasses1Test.java @@ -0,0 +1,82 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Field; +import java.util.Set; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.test.base.BaseTest; + +public class EzyClasses1Test extends BaseTest { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void test1() { + Class clazzD = E.class; + Set classes = EzyClasses.flatSuperAndInterfaceClasses(clazzD); + for(Class cl : classes) { + System.err.println(cl.getSimpleName() + ", "); + } + assertEquals(classes, Sets.newHashSet(A.class, B.class, C.class, D.class)); + classes = EzyClasses.flatSuperClasses(B.class); + assertEquals(classes.size(), 0); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void test2() { + Class clazzD = E.class; + System.err.println("\n======\n"); + Set classes = EzyClasses.flatSuperAndInterfaceClasses(clazzD, true); + for(Class cl : classes) { + System.err.println(cl.getSimpleName() + ", "); + } + assertEquals(classes, Sets.newHashSet(A.class, B.class, C.class, D.class, Object.class)); + classes = EzyClasses.flatSuperClasses(B.class); + assertEquals(classes.size(), 0); + } + + public A a = new A() { + + }; + + @Test + public void test3() throws Exception { + Class clazz = Class.forName("DefaultClassX"); + Object object = clazz.newInstance(); + Field objf = clazz.getDeclaredField("obj"); + objf.setAccessible(true); + Object obj = objf.get(object); + assert EzyClasses.getVariableName(clazz).equals("defaultClassX"); + System.out.println(EzyClasses.getVariableName(a.getClass())); + System.out.println(EzyClasses.getVariableName(obj.getClass())); + + assert EzyClasses.getVariableName(Impl.class, "Impl").equals("impl"); + assert EzyClasses.getVariableName(AImpl.class, "Impl").equals("a"); + assert EzyClasses.getVariableName(abc.class, "abc").equals("abc"); + } + + public static interface A { + + } + + public static interface B extends A { + + } + + public static class C { + + } + + public static class D extends C { + + } + + public static class E extends D implements B { + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassesTest.java new file mode 100644 index 00000000..e118002d --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyClassesTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Constructor; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyClasses; +import com.tvd12.test.base.BaseTest; + +public class EzyClassesTest extends BaseTest { + + @Test + public void test() { + EzyClasses.newInstance(String.class.getName()); + EzyClasses.newInstance(String.class.getName(), getClass().getClassLoader()); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyClasses.newInstance("aaa"); + EzyClasses.newInstance("aaa", getClass().getClassLoader()); + } + + @Test + public void test2() throws Exception { + Constructor constructor = EzyClasses.getConstructor(ClassA.class); + EzyClasses.newInstance(constructor); + EzyClasses.newInstance(ClassA.class); + } + + @Override + public Class getTestClass() { + return EzyClasses.class; + } + + public static class ClassA { + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyField2Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyField2Test.java new file mode 100644 index 00000000..d8ee01cb --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyField2Test.java @@ -0,0 +1,36 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.test.base.BaseTest; + +public class EzyField2Test extends BaseTest { + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() throws Exception { + EzyField field = new EzyField(ClassA.class.getDeclaredField("a")); + field.set(new ClassA(), "10"); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() throws Exception { + EzyField field = new EzyField(ClassA.class.getDeclaredField("a")); + field.get(this); + } + + @Test + public void test3() throws Exception { + EzyField field = new EzyField(ClassA.class.getDeclaredField("b")); + ClassA obj = new ClassA(); + assert field.get(obj).equals("b"); + field.set(obj, "10"); + assert field.get(obj).equals("10"); + } + + public static class ClassA { + protected final String a = "a"; + public String b = "b"; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldFinderTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldFinderTest.java new file mode 100644 index 00000000..d8007713 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldFinderTest.java @@ -0,0 +1,58 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.lang.reflect.Field; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyFieldFinder; +import com.tvd12.test.base.BaseTest; + +public class EzyFieldFinderTest extends BaseTest { + + @Test + public void test() { + Field a = EzyFieldFinder.builder() + .clazz(B.class) + .fieldName("a") + .build() + .find(); + assertNotNull(a); + + Field b = EzyFieldFinder.builder() + .clazz(B.class) + .fieldName("b") + .build() + .find(); + assertNotNull(b); + + Field c = EzyFieldFinder.builder() + .clazz(B.class) + .fieldName("c") + .build() + .find(); + assertNotNull(c); + + Field d = EzyFieldFinder.builder() + .clazz(B.class) + .fieldName("d") + .build() + .find(); + assertNull(d); + } + + public static interface I { + String a = ""; + } + + public abstract class A implements I { + String b; + } + + public abstract class B extends A { + String c; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldTest.java new file mode 100644 index 00000000..bf339659 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldTest.java @@ -0,0 +1,54 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyFields; +import com.tvd12.test.base.BaseTest; + +public class EzyFieldTest extends BaseTest { + + @Test + public void test() throws Exception { + EzyField a = EzyField.builder() + .clazz(ClassA.class) + .fieldName("a") + .build(); + assertNotNull(EzyFields.getField(ClassA.class, "a")); + assertFalse(a.isMapType()); + assertFalse(a.isCollection()); + assertEquals(a.getType(), String.class); + assertEquals(a.getGenericType(), String.class); + assertEquals(a.getGetterMethod(), "getA"); + assertEquals(a.getSetterMethod(), "setA"); + assertFalse(a.isAnnotated(ExampleAnnotation.class)); + assertNull(a.getAnnotation(ExampleAnnotation.class)); + a.toString(); + + EzyField ab = new EzyField(ClassA.class.getDeclaredField("ab")); + assertEquals(ab.getGetterMethod(), "getAb"); + assertEquals(ab.getSetterMethod(), "setAb"); + assertTrue(ab.isMapType()); + + assert !a.equals(null); + assert a.equals(a); + assert a.equals(new EzyField(a.getField())); + assert a.hashCode() == a.hashCode(); + } + + public static class ClassA { + protected String a; + protected Map ab; + protected List abc; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldsTest.java new file mode 100644 index 00000000..b4a29bdf --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyFieldsTest.java @@ -0,0 +1,32 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyFields; +import com.tvd12.test.base.BaseTest; + +public class EzyFieldsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyFields.class; + } + + @Test + public void test() { + assertEquals(EzyFields.getAnnotatedFields(ClassB.class, ExampleAnnotation.class).size(), 2); + } + + public static class ClassA { + @ExampleAnnotation + String value; + } + + public static class ClassB extends ClassA { + @ExampleAnnotation + String name; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericSetterValidatorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericSetterValidatorTest.java new file mode 100644 index 00000000..14ad8bfd --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericSetterValidatorTest.java @@ -0,0 +1,21 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Type; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyGenericSetterValidator; +import com.tvd12.test.base.BaseTest; + +public class EzyGenericSetterValidatorTest extends BaseTest { + + @Test + public void test() { + new EzyGenericSetterValidator().validate(new MyType()); + } + + public static class MyType implements Type { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics1Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics1Test.java new file mode 100644 index 00000000..c04c6e5d --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics1Test.java @@ -0,0 +1,96 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyFields; + +import lombok.Data; + +public class EzyGenerics1Test { + + @Test + public void test() { + System.out.println("\n======= begin check getGenericType ========\n"); + List fields = EzyFields.getFields(ClassC.class); + for(Field field : fields) { + System.out.println("field " + field.getName() + ", genericType = " + field.getGenericType().getTypeName()); + } + System.out.println("\n======= end check getGenericType ========\n"); + + List validFields = new ArrayList<>(); + + System.out.println("\n======= begin check is ParameterizedType ========\n"); + for(Field field : fields) { + Type type = field.getGenericType(); + System.out.println("field " + field.getName() + ", is ParameterizedType = " + + (type instanceof ParameterizedType)); + if(type instanceof ParameterizedType) + validFields.add(field); + } + System.out.println("\n======= end check getGenericType ========\n"); + + System.out.println("\n======= begin check generic argument type ========\n"); + for(Field field : validFields) { + Type type = field.getGenericType(); + Type[] types = ((ParameterizedType)type).getActualTypeArguments(); + System.out.println("field " + field.getName() + ", genericType = " + + Arrays.toString(types)); + System.out.println(types[0].getClass()); + } + System.out.println("\n======= end check getGenericType ========\n"); + } + + @Data + public static class ClassA { + private String name; + private List abc = new ArrayList<>(); + } + + @Data + public static class ClassB { + private String name; + + private int a; + private int b; + private int c; + private int d; + private int e; + private int f; + private int g; + private int h; + private int i; + private int j; + } + + @Data + @SuppressWarnings("rawtypes") + public static class ClassC { + public ClassB classB; + public ClassD classD; + public boolean visible; + + public ClassD classD1; + + public Map map1; + public List> list1; + public Map map2; + public Map map3; + public Map map4; + public List list2; + } + + public static class ClassD { + public ClassD(T value) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics2Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics2Test.java new file mode 100644 index 00000000..d4d1c9d6 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics2Test.java @@ -0,0 +1,65 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import lombok.Data; + +public class EzyGenerics2Test { + + @Test + public void test() throws Exception { + Field field = ClassC.class.getDeclaredField("map1"); + System.out.println(Map.class.isAssignableFrom(field.getType())); + } + + @Data + public static class ClassA { + private String name; + private List abc = new ArrayList<>(); + } + + @Data + public static class ClassB { + private String name; + + private int a; + private int b; + private int c; + private int d; + private int e; + private int f; + private int g; + private int h; + private int i; + private int j; + } + + @Data + @SuppressWarnings("rawtypes") + public static class ClassC { + public ClassB classB; + public ClassD classD; + public boolean visible; + + public ClassD classD1; + + public Map map1; + public List> list1; + public Map map2; + public Map map3; + public Map map4; + public List list2; + } + + public static class ClassD { + public ClassD(T value) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics3Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics3Test.java new file mode 100644 index 00000000..cf93db8f --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics3Test.java @@ -0,0 +1,70 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import lombok.Data; + +public class EzyGenerics3Test { + + @SuppressWarnings("rawtypes") + @Test + public void test() throws Exception { + Field field = ClassC.class.getDeclaredField("map1"); + ParameterizedType type = (ParameterizedType)field.getGenericType(); + System.out.println(type.getRawType().getTypeName()); + System.out.println(field.getType().equals(type.getRawType())); + System.out.println(Map.class.isAssignableFrom((Class)type.getRawType())); + } + + @Data + public static class ClassA { + private String name; + private List abc = new ArrayList<>(); + } + + @Data + public static class ClassB { + private String name; + + private int a; + private int b; + private int c; + private int d; + private int e; + private int f; + private int g; + private int h; + private int i; + private int j; + } + + @Data + @SuppressWarnings("rawtypes") + public static class ClassC { + public ClassB classB; + public ClassD classD; + public boolean visible; + + public ClassD classD1; + + public Map map1; + public List> list1; + public Map map2; + public Map map3; + public Map map4; + public List list2; + } + + public static class ClassD { + public ClassD(T value) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics4Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics4Test.java new file mode 100644 index 00000000..96caf140 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics4Test.java @@ -0,0 +1,91 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; + +import lombok.Data; + +public class EzyGenerics4Test { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void test() throws Exception { + Field field = ClassC.class.getDeclaredField("map1"); + ParameterizedType type = (ParameterizedType)field.getGenericType(); + System.out.println(type.getRawType().getTypeName()); + System.out.println(field.getType().equals(type.getRawType())); + System.out.println(Map.class.isAssignableFrom((Class)type.getRawType())); + + Map map = new HashMap<>(); + Class> mapClass = (Class>)map.getClass(); + System.out.println("mapClass = " + mapClass); + System.out.println(Arrays.toString(mapClass.getGenericInterfaces())); + System.out.println(mapClass.getGenericSuperclass()); + Type mapType = mapClass.getGenericInterfaces()[0]; + Type mapType0 = ((ParameterizedType)mapType).getActualTypeArguments()[0]; + System.out.println("mapType0 is String.class = " + mapType0.equals(String.class)); + System.out.println(mapType0.getClass()); + + Field list1 = ClassC.class.getDeclaredField("list1"); + Type list1Type = list1.getGenericType(); + Class list1ElementType = EzyGenerics.getOneGenericClassArgument(list1Type); + System.out.println("list1Type: " + list1Type); + System.out.println("list1ElementType: " + list1ElementType); + } + + @Data + public static class ClassA { + private String name; + private List abc = new ArrayList<>(); + } + + @Data + public static class ClassB { + private String name; + + private int a; + private int b; + private int c; + private int d; + private int e; + private int f; + private int g; + private int h; + private int i; + private int j; + } + + @Data + @SuppressWarnings("rawtypes") + public static class ClassC { + public ClassB classB; + public ClassD classD; + public boolean visible; + + public ClassD classD1; + + public Map map1; + public List> list1; + public Map map2; + public Map map3; + public Map map4; + public List list2; + } + + public static class ClassD { + public ClassD(T value) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics5Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics5Test.java new file mode 100644 index 00000000..e7056f5c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics5Test.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.HashMap; + +public class EzyGenerics5Test { + + public static void main(String[] args) throws Exception { + Field field = ClassA.class.getDeclaredField("doc"); + System.out.println(field.getGenericType()); + System.out.println(field.getGenericType() instanceof ParameterizedType); + } + + public static class ClassA { + public Doc doc; + } + + public static class Doc extends HashMap { + private static final long serialVersionUID = 7094427792585792941L; + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics6Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics6Test.java new file mode 100644 index 00000000..f69c4779 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenerics6Test.java @@ -0,0 +1,98 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; +import com.tvd12.test.base.BaseTest; + +public class EzyGenerics6Test extends BaseTest { + + @SuppressWarnings("rawtypes") + @Test + public void test1() { + Class[] args = EzyGenerics.getGenericInterfacesArguments( + InterfaceB.class, InterfaceA.class, 2); + assertEquals(args, new Class[] {String.class, String.class}); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceA.class, InterfaceA.class, 2); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceB.class, InterfaceC.class, 2); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test4() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceB.class, InterfaceD.class, 2); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test5() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceB.class, InterfaceE.class, 2); + } + + @Test + public void test6() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceB.class, InterfaceF.class, 2); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test7() { + EzyGenerics.getGenericInterfacesArguments( + InterfaceB1.class, InterfaceG.class, 2); + } + + public static interface InterfaceA { + } + + public static interface InterfaceC { + } + + public static interface InterfaceD { + + } + + public static interface InterfaceE { + + } + + public static interface InterfaceF extends Map { + + } + + public static interface InterfaceG { + + } + + public static interface MyMap extends Map { + + } + + @SuppressWarnings("rawtypes") + public static interface InterfaceB extends + InterfaceA, + InterfaceC, + InterfaceD, + InterfaceE, + InterfaceF, Map> { + + } + + public static interface InterfaceB1 extends InterfaceG { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericsTest.java new file mode 100644 index 00000000..92cb40e2 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGenericsTest.java @@ -0,0 +1,60 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyGenerics; +import com.tvd12.test.base.BaseTest; + +public class EzyGenericsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyGenerics.class; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyGenerics.getGenericClassArguments(getGenericType("a"), 1); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + EzyGenerics.getGenericClassArguments(getGenericType("b"), 2); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test3() { + EzyGenerics.getGenericClassArguments(getGenericType("e"), 2); + } + + @Test + public void test4() { + EzyGenerics.getTwoGenericClassArguments(getGenericType("c")); + } + + private Type getGenericType(String fieldName) { + return field(fieldName).getGenericType(); + } + + private Field field(String field) { + try { + return ClassA.class.getDeclaredField(field); + } catch (Exception e) { + return null; + } + } + + public static class ClassA { + String a; + Collection b; + Map c; + Map, Map> d; + Map e; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGetterMethodTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGetterMethodTest.java new file mode 100644 index 00000000..d2eb2932 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyGetterMethodTest.java @@ -0,0 +1,66 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyGetterMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyGetterMethodTest extends BaseTest { + + @Test + public void test() throws Exception { + EzyGetterMethod getter = new EzyGetterMethod( + ClassA.class.getDeclaredMethod("getValue")); + assertEquals(getter.getType(), String.class); + assertEquals(getter.getGenericType(), String.class); + assertEquals(getter.isMapType(), false); + assertEquals(getter.isCollection(), false); + assertEquals(getter.getFieldName(), "value"); + assertEquals(getter.getTypeName(), String.class.getTypeName()); + + } + + @Test + public void test2() throws Exception { + EzyGetterMethod getter = new EzyGetterMethod( + ClassA.class.getDeclaredMethod("getA")); + assertEquals(getter.getFieldName(), "a"); + } + + @Test + public void test3() throws Exception { + EzyGetterMethod getter = new EzyGetterMethod( + ClassA.class.getDeclaredMethod("duplicateValue")); + assertEquals(getter.getFieldName(), "duplicateValue"); + } + + @Test + public void test4() throws Exception { + EzyGetterMethod get = new EzyGetterMethod( + ClassA.class.getDeclaredMethod("get")); + assert get.getFieldName().equals("get"); + } + + public static class ClassA { + + public String getA() { + return ""; + } + + public String getValue() { + return "value"; + } + + public String duplicateValue() { + return ""; + } + + public String get() { + return "get"; + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethod2Test.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethod2Test.java new file mode 100644 index 00000000..334cca91 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethod2Test.java @@ -0,0 +1,56 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyMethod2Test extends BaseTest { + + @Test + public void test() throws Exception { + + EzyMethod m1 = new EzyMethod(ClassA.class.getDeclaredMethod("get")); + EzyMethod m2 = new EzyMethod(ClassA.class.getDeclaredMethod("set")); + EzyMethod m3 = new EzyMethod(ClassA.class.getDeclaredMethod("hello")); + EzyMethod m4 = new EzyMethod(ClassA.class.getDeclaredMethod("getJava")); + + assert m1.getFieldName().equals("get"); + assert m2.getFieldName().equals("set"); + assert m3.getFieldName().equals("hello"); + assert m4.getFieldName().equals("java"); + + m4.invoke(new ClassA()); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() throws Exception { + EzyMethod m1 = new EzyMethod(ClassA.class.getDeclaredMethod("pMethod")); + m1.invoke(new ClassA()); + } + + public static class ClassA { + + protected void pMethod() { + throw new RuntimeException(); + } + + public String get() { + return ""; + } + + public void set() { + + } + + public void hello() { + + } + + public String getJava() { + return "java"; + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodFinderTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodFinderTest.java new file mode 100644 index 00000000..7055976a --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodFinderTest.java @@ -0,0 +1,62 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.lang.reflect.Method; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyMethodFinder; +import com.tvd12.test.base.BaseTest; + +public class EzyMethodFinderTest extends BaseTest { + + @Test + public void test1() { + Method m1 = EzyMethodFinder.builder() + .clazz(B.class) + .methodName("getName") + .parameterTypes() + .build() + .find(); + assertNotNull(m1); + + Method m2 = EzyMethodFinder.builder() + .clazz(B.class) + .methodName("getName1") + .parameterTypes() + .build() + .find(); + assertNotNull(m2); + + Method m3 = EzyMethodFinder.builder() + .clazz(B.class) + .methodName("getName2") + .parameterTypes() + .build() + .find(); + assertNotNull(m3); + + Method m4 = EzyMethodFinder.builder() + .clazz(B.class) + .methodName("getName3") + .parameterTypes() + .build() + .find(); + assertNull(m4); + } + + public static interface I { + String getName(); + } + + public static abstract class A implements I { + public abstract String getName1(); + } + + public static abstract class B extends A { + public abstract String getName2(); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodTest.java new file mode 100644 index 00000000..aa1b1f88 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodTest.java @@ -0,0 +1,93 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.test.base.BaseTest; + +public class EzyMethodTest extends BaseTest { + + @Test + public void test() throws Exception { + EzyMethod method1 = EzyMethod.builder() + .clazz(ClassA.class) + .methodName("getValue") + .parameterTypes(String.class, String.class) + .build(); + method1.setDisplayName("getValue$impl"); + assertEquals(method1.getDisplayName(), "getValue$impl"); + assertEquals(method1.getReturnType(), String.class); + assertEquals(method1.getGenericReturnType(), String.class); + assertEquals(method1.getGenericParameterTypes().length, 2); + assertEquals(method1.getParameterTypes().length, 2); + assertFalse(method1.isAnnotated(ExampleAnnotation.class)); + assertNull(method1.getAnnotation(ExampleAnnotation.class)); + method1.getDeclaration(); + method1.getPublicDeclaration(); + method1.toString(); + + EzyMethod method2 = new EzyMethod(ClassA.class.getDeclaredMethod("notSetter1", String.class)); + assertFalse(method2.isSetter()); + assertFalse(method2.isGetter()); + EzyMethod method3 = new EzyMethod(ClassA.class.getDeclaredMethod("notSetter2")); + assertFalse(method3.isSetter()); + assertFalse(method3.isGetter()); + EzyMethod method4 = new EzyMethod(ClassA.class.getDeclaredMethod("notSetter3", String.class, String.class)); + assertFalse(method4.isSetter()); + assertFalse(method4.isGetter()); + EzyMethod method5 = new EzyMethod(ClassA.class.getDeclaredMethod("setNotSetter", String.class, String.class)); + assertFalse(method5.isSetter()); + assertFalse(method5.isGetter()); + + EzyMethod method6 = new EzyMethod(ClassA.class.getDeclaredMethod("getNotGetter3", String.class)); + assertFalse(method6.isSetter()); + assertFalse(method6.isGetter()); + + EzyMethod method7 = new EzyMethod(ClassA.class.getDeclaredMethod("getNotGetter4")); + assertFalse(method7.isSetter()); + assertFalse(method7.isGetter()); + + assert !method7.equals(method6); + method7.hashCode(); + + EzyMethod method8 = new EzyMethod(ClassA.class.getDeclaredMethod("newHello")); + assert method8.getFieldName().equals("hello"); + } + + public static class ClassA { + + public String getValue(String a, String b) { + return "value"; + } + + public String newHello() { + return "hello"; + } + + public void notSetter1(String a) { + } + + protected void notSetter2() { + } + + protected void notSetter3(String a, String b) { + } + + public void setNotSetter(String a, String b) { + + } + + public String getNotGetter3(String a) { + return null; + } + + public void getNotGetter4() { + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodsTest.java new file mode 100644 index 00000000..2da3d9aa --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyMethodsTest.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyMethods; +import com.tvd12.test.base.BaseTest; + +public class EzyMethodsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyMethods.class; + } + + @Test + public void test() { + assertNotNull(EzyMethods.getPublicMethod(ClassB.class, "setValue", String.class)); + assertEquals(EzyMethods.getAnnotatedMethods(ClassB.class, ExampleAnnotation.class).size(), 1); + } + + public static class ClassA { + + public void setValue(String value) { + } + + } + + public static class ClassB extends ClassA { + + @ExampleAnnotation + public void setName(String name) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyPackagesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyPackagesTest.java new file mode 100644 index 00000000..db75d5ac --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyPackagesTest.java @@ -0,0 +1,52 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertTrue; + +import java.util.Set; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyPackages; +import com.tvd12.test.base.BaseTest; + +public class EzyPackagesTest extends BaseTest { + + public java.lang.Class getTestClass() { + return EzyPackages.class; + }; + + @Test + public void test() { + assertTrue(EzyPackages.getAnnotatedClasses( + "com.tvd12.ezyfoxserver.testing.reflect", ExampleAnnotation.class) + .contains(ClassA.class)); + } + + @Test + public void test1() { + Set> set = EzyPackages.getExtendsClasses( + "com.tvd12.ezyfoxserver.testing.reflect", InterfaceA.class); + System.out.println(set); + + set = EzyPackages.getExtendsClasses( + "com.tvd12.ezyfoxserver.testing.reflect", ClassA.class); + System.out.println(set); + + } + + @ExampleAnnotation + public static class ClassA { + + } + + public static class ClassB extends ClassA { + + } + + public static interface InterfaceA { + } + + public static interface InterfaceB extends InterfaceA { + + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterMethodTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterMethodTest.java new file mode 100644 index 00000000..fb9cf00a --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterMethodTest.java @@ -0,0 +1,64 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzySetterMethod; +import com.tvd12.test.base.BaseTest; + +public class EzySetterMethodTest extends BaseTest { + + @Test + public void test() throws Exception { + EzySetterMethod setter = new EzySetterMethod( + ClassA.class.getDeclaredMethod("setValue", String.class)); + assertEquals(setter.getType(), String.class); + assertEquals(setter.getGenericType(), String.class); + assertEquals(setter.isMapType(), false); + assertEquals(setter.isCollection(), false); + assertEquals(setter.getFieldName(), "value"); + assert setter.getParameterCount() >= 0; + } + + @Test + public void test2() throws Exception { + EzySetterMethod setter = new EzySetterMethod( + ClassA.class.getDeclaredMethod("setA", String.class)); + assertEquals(setter.getFieldName(), "a"); + } + + @Test + public void test3() throws Exception { + EzySetterMethod setter = new EzySetterMethod( + ClassA.class.getDeclaredMethod("duplicateValue", String.class)); + assertEquals(setter.getFieldName(), "duplicateValue"); + } + + @Test + public void test4() throws Exception { + EzySetterMethod set = new EzySetterMethod( + ClassA.class.getDeclaredMethod("set", String.class)); + assert set.getFieldName().equals("set"); + } + + public static class ClassA { + + public void setA(String a) { + + } + + public void setValue(String value) { + } + + public void duplicateValue(String value) { + + } + + public void set(String a) { + + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterValidatorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterValidatorTest.java new file mode 100644 index 00000000..638ef951 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzySetterValidatorTest.java @@ -0,0 +1,77 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.reflect.EzyFields; +import com.tvd12.ezyfoxserver.reflect.EzyGenericSetterValidator; + +import lombok.Data; + +public class EzySetterValidatorTest { + + @Test + public void test() throws Exception { + System.out.println("\n======= begin validator ========\n"); + List fields = EzyFields.getFields(ClassC.class); + for(Field field : fields) { + System.out.println("field " + field.getName() + + ", valid = " + new EzyGenericSetterValidator().validate(field.getGenericType()) + + ", instance of class = " + (field.getGenericType() instanceof Class) + + ", instance of ParameterizedType " + (field.getGenericType() instanceof ParameterizedType) + + ", genericType = " + field.getGenericType().getTypeName()); + } + System.out.println("\n======= end validator ========\n"); + } + + @Data + public static class ClassA { + private String name; + private List abc = new ArrayList<>(); + } + + @Data + public static class ClassB { + private String name; + + private int a; + private int b; + private int c; + private int d; + private int e; + private int f; + private int g; + private int h; + private int i; + private int j; + } + + @Data + @SuppressWarnings("rawtypes") + public static class ClassC { + public ClassB classB; + public ClassD classD; + public boolean visible; + + public ClassD classD1; + + public Map map1; + public List> list1; + public Map map2; + public Map map3; + public Map map4; + public List list2; + } + + public static class ClassD { + public ClassD(T value) { + + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyTypesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyTypesTest.java new file mode 100644 index 00000000..d8e9543c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/EzyTypesTest.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import com.tvd12.ezyfoxserver.reflect.EzyTypes; +import com.tvd12.test.base.BaseTest; + +public class EzyTypesTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyTypes.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/FetchMethodTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/FetchMethodTest.java new file mode 100644 index 00000000..176bcf57 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/FetchMethodTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +import com.tvd12.ezyfoxserver.reflect.EzyMethods; + +public class FetchMethodTest { + + public static void main(String[] args) throws Exception { + System.out.println(EzyMethods.getMethods(B.class)); + } + + public static class B extends A { + @Override + public void setValue() { + super.setValue(); + } + } + + public static class A { + public void setValue() { + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/Impl.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/Impl.java new file mode 100644 index 00000000..c18b8a2a --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/Impl.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +public class Impl { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/abc.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/abc.java new file mode 100644 index 00000000..2265d2e1 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/reflect/abc.java @@ -0,0 +1,5 @@ +package com.tvd12.ezyfoxserver.testing.reflect; + +public class abc { + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyArrayIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyArrayIteratorTest.java new file mode 100644 index 00000000..ff63b444 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyArrayIteratorTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import static org.testng.Assert.*; + +import java.lang.reflect.Array; +import java.util.concurrent.atomic.AtomicInteger; + +public abstract class EzyArrayIteratorTest { + + @Test + public void test() { + Object array = newArray(); + EzyArrayIterator it = newIterator(); + AtomicInteger i = new AtomicInteger(0); + while(it.hasNext()) + assertEquals(it.next(), Array.get(array, i.getAndIncrement())); + } + + protected abstract Object newArray(); + protected abstract EzyArrayIterator newIterator(); +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyAutoImplAnnotationsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyAutoImplAnnotationsTest.java new file mode 100644 index 00000000..1668bbaf --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyAutoImplAnnotationsTest.java @@ -0,0 +1,57 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.util.EzyAutoImplAnnotations; +import com.tvd12.test.base.BaseTest; + +public class EzyAutoImplAnnotationsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyAutoImplAnnotations.class; + } + + @Test + public void test() { + assert EzyAutoImplAnnotations.getBeanName(ClassA.class).equals("classA"); + assert EzyAutoImplAnnotations.getBeanName(ClassB.class).equals("b"); + assert EzyAutoImplAnnotations.getBeanName(ClassC.class).equals("c"); + assert EzyAutoImplAnnotations.getBeanName(ClassD.class).equals("classD"); + assert EzyAutoImplAnnotations.getBeanName(ClassE.class).equals("classE"); + } + + @EzyAutoImpl + public interface ClassA { + + } + + @EzyAutoImpl("b") + public interface ClassB { + + } + + @EzyAutoImpl(properties = { + @EzyKeyValue(key = "name", value = "c") + }) + public interface ClassC { + + } + + @EzyAutoImpl(properties = { + @EzyKeyValue(key = "name", value = "") + }) + public interface ClassD { + + } + + @EzyAutoImpl(properties = { + @EzyKeyValue(key = "no no no", value = "e") + }) + public interface ClassE { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBoolsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBoolsIteratorTest.java new file mode 100644 index 00000000..650d19bb --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBoolsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyBoolsIterator; + +public class EzyBoolsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new boolean[] {true, false, true}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyBoolsIterator.wrap(new boolean[] {true, false, true}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBytesIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBytesIteratorTest.java new file mode 100644 index 00000000..69dfbb08 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyBytesIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyShortsIterator; + +public class EzyBytesIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new short[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyShortsIterator.wrap(new short[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCharsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCharsIteratorTest.java new file mode 100644 index 00000000..78146316 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCharsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyCharsIterator; + +public class EzyCharsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new char[] {'a', 'b', 'c'}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyCharsIterator.wrap(new char[] {'a', 'b', 'c'}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCollectionFactoryTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCollectionFactoryTest.java new file mode 100644 index 00000000..f96202db --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyCollectionFactoryTest.java @@ -0,0 +1,47 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Set; +import java.util.Stack; +import java.util.Vector; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyCollectionFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyCollectionFactoryTest extends BaseTest { + + @SuppressWarnings({ "unused", "rawtypes" }) + @Test + public void test() { + EzyCollectionFactory factory = new EzyCollectionFactory(); + Collection coll = factory.newCollection(Collection.class); + List list = factory.newCollection(List.class); + ArrayList arrayList = factory.newCollection(ArrayList.class); + LinkedList linkedList = factory.newCollection(LinkedList.class); + CopyOnWriteArrayList copyOnWriteArrayList = factory.newCollection(CopyOnWriteArrayList.class); + Set set = factory.newCollection(Set.class); + HashSet hashSet = factory.newCollection(HashSet.class); + LinkedHashSet linkedHashSet = factory.newCollection(LinkedHashSet.class); + CopyOnWriteArraySet copyOnWriteArraySet = factory.newCollection(CopyOnWriteArraySet.class); + Vector vector = factory.newCollection(Vector.class); + Queue queue = factory.newCollection(Queue.class); + Stack stack = factory.newCollection(Stack.class); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyCollectionFactory factory = new EzyCollectionFactory(); + factory.newCollection(Integer.class); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDirectoriesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDirectoriesTest.java new file mode 100644 index 00000000..fe96c885 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDirectoriesTest.java @@ -0,0 +1,70 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.Collection; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyDirectories; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzyDirectoriesTest extends BaseTest { + + private EzyDirectories directories; + + public EzyDirectoriesTest() throws IOException { + super(); + this.directories = new EzyDirectories().directory(createDirectory()); + } + + private File createDirectory() throws IOException { + File file = new File("util-directories-test"); + file.mkdirs(); + File a = new File(file.getAbsolutePath() + File.separator + "A"); + File b = new File(file.getAbsolutePath() + File.separator + "B"); + File c = new File(file.getAbsolutePath() + File.separator + "C"); + a.mkdirs(); + b.mkdirs(); + c.mkdirs(); + File f1 = new File(a.getAbsolutePath() + File.separator + "F1"); + File f2 = new File(a.getAbsolutePath() + File.separator + "F2"); + f1.createNewFile(); + f2.createNewFile(); + + File f3 = new File(b.getAbsolutePath() + File.separator + "F3.txt"); + File f4 = new File(b.getAbsolutePath() + File.separator + "F4.txt"); + f3.createNewFile(); + f4.createNewFile(); + + File f5 = new File(c.getAbsolutePath() + File.separator + "F5.md"); + File f6 = new File(c.getAbsolutePath() + File.separator + "F6.md"); + f5.createNewFile(); + f6.createNewFile(); + + return file; + } + + @Test + public void test1() throws IOException { + URL[] urls = directories.getURLs(); + assertEquals(urls.length, 6); + + urls = directories.getURLs(null, false); + assertEquals(urls.length, 0); + + urls = directories.getURLs(new String[] {"txt"}); + assertEquals(urls.length, 2); + + urls = directories.getURLs(new String[] {"md"}); + assertEquals(urls.length, 2); + + Collection files = directories.getFiles(); + assertEquals(files.size(), 6); + + assert directories.toString() != null; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDoublesIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDoublesIteratorTest.java new file mode 100644 index 00000000..f2456a07 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyDoublesIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyDoublesIterator; + +public class EzyDoublesIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new double[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyDoublesIterator.wrap(new double[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntryTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntryTest.java new file mode 100644 index 00000000..64c8e61e --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEntryTest.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyEntry; +import com.tvd12.test.base.BaseTest; + +public class EzyEntryTest extends BaseTest { + + @Test + public void test() { + EzyEntry ab = EzyEntry.of("a", "b"); + + assert ab.getKey().equals("a"); + assert ab.getValue().equals("b"); + + EzyEntry bc = new EzyEntry<>(); + bc.setKey("b"); + assert bc.setValue("c") == null; + assert !ab.equals(bc); + assert ab.hashCode() != bc.hashCode(); + + EzyEntry abe = EzyEntry.of("a", "b"); + assert ab.equals(abe); + assert ab.hashCode() == abe.hashCode(); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEnumsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEnumsTest.java new file mode 100644 index 00000000..6d7a7999 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEnumsTest.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.constant.EzyConstant; +import com.tvd12.ezyfoxserver.util.EzyEnums; +import com.tvd12.test.base.BaseTest; + +import lombok.Getter; + +public class EzyEnumsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyEnums.class; + } + + @Test + public void test1() { + assert EzyEnums.valueOf(ABC.values(), 1) == ABC.A; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test2() { + assert EzyEnums.valueOf(ABC.values(), 10) == ABC.A; + } + + public static enum ABC implements EzyConstant { + + A(1), + B(2), + C(3); + + @Getter + private int id; + + private ABC(int id) { + this.id = id; + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEqualsAndHashCodeTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEqualsAndHashCodeTest.java new file mode 100644 index 00000000..03ce4e74 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyEqualsAndHashCodeTest.java @@ -0,0 +1,117 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.math.BigInteger; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyEquals; +import com.tvd12.ezyfoxserver.util.EzyHashCodes; +import com.tvd12.test.base.BaseTest; +import com.tvd12.test.performance.Performance; + +import lombok.Getter; +import lombok.Setter; + +public class EzyEqualsAndHashCodeTest extends BaseTest { + + @Test + public void test() { + ClassA classA = new ClassA(); + classA.setId(10); + classA.setName("name"); + assert new ClassA().equals(null) == false; + assert classA.equals(classA); + assert classA.equals(new Object()) == false; + assert new ClassA().equals(new ClassA()); + assert new ClassA().hashCode() == new ClassA().hashCode(); + assert classA.equals(new ClassA()) == false; + + ClassA classA1 = new ClassA(); + classA1.setName("name"); + assert classA1.equals(new ClassA()) == false; + assert new ClassA().equals(classA1) == false; + + ClassA classA2 = new ClassA(); + classA2.setName("name"); + classA2.setValue("value"); + classA2.setObject(new BigInteger("123")); + + ClassA classA3 = new ClassA(); + classA3.setName("name"); + classA3.setValue("value"); + classA3.setObject(new BigInteger("123")); + + assert classA3.equals(classA2); + + assert classA2.hashCode() == classA2.hashCode(); + assert classA3.hashCode() == classA2.hashCode(); + } + + @Test + public void testEqualPerformance() { + ClassA classA2 = new ClassA(); + classA2.setName("name"); + classA2.setValue("value"); + classA2.setObject(new BigInteger("123")); + + ClassA classA3 = new ClassA(); + classA3.setName("name"); + classA3.setValue("value"); + classA3.setObject(new BigInteger("123")); + + long time = Performance.create() + .loop(1000000) + .test(() -> { + classA2.equals(classA3); + }) + .getTime(); + System.out.println("equals.time = " + time); + } + + @Test + public void testHashCodePerformance() { + ClassA classA2 = new ClassA(); + classA2.setName("name"); + classA2.setValue("value"); + classA2.setObject(new BigInteger("123")); + + long time = Performance.create() + .loop(1000000) + .test(() -> { + classA2.hashCode(); + }) + .getTime(); + System.out.println("hashcode.time = " + time); + } + + @Setter + @Getter + public static class ClassA { + private int id; + private String name; + private String value; + private Object object; + + @Override + public boolean equals(Object obj) { + return new EzyEquals() + .function(c -> c.id) + .function(c -> c.name) + .function(c -> c.value) + .function(c -> c.object) + .isEquals(this, obj); + } + + @Override + public int hashCode() { + return new EzyHashCodes() + .initial(17) + .prime(37) + .append(id, name) + .append(value) + .append(object) + .toHashCode(); + } + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyFloatsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyFloatsIteratorTest.java new file mode 100644 index 00000000..0bf96e12 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyFloatsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyFloatsIterator; + +public class EzyFloatsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new float[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyFloatsIterator.wrap(new float[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapListTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapListTest.java new file mode 100644 index 00000000..f52c5dad --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapListTest.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.util.EzyHashMapList; +import com.tvd12.ezyfoxserver.util.EzyMapList; +import com.tvd12.test.base.BaseTest; + +public class EzyHashMapListTest extends BaseTest { + + @Test + public void test() { + EzyMapList map = new EzyHashMapList<>(); + map.addItems("1", "a", "b", "c"); + assertEquals(map.get("1"), Lists.newArrayList("a", "b", "c")); + map.removeItems("1", "b", "c"); + assertEquals(map.get("1"), Lists.newArrayList("a")); + map.removeItems("zzz"); + assert map.getItems("abc").size() == 0; + map.addItems("a", Lists.newArrayList("a", "b", "c")); + assert map.getItems("a").size() == 3; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapSetTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapSetTest.java new file mode 100644 index 00000000..be65b402 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyHashMapSetTest.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.google.common.collect.Sets; +import com.tvd12.ezyfoxserver.util.EzyHashMapSet; +import com.tvd12.ezyfoxserver.util.EzyMapSet; +import com.tvd12.test.base.BaseTest; + +public class EzyHashMapSetTest extends BaseTest { + + @Test + public void test() { + EzyMapSet map = new EzyHashMapSet<>(); + map.addItems("1", "a", "b", "c"); + assertEquals(map.get("1"), Sets.newHashSet("a", "b", "c")); + map.removeItems("1", "b", "c"); + assertEquals(map.get("1"),Sets.newHashSet("a")); + map.removeItems("zzz"); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIfElseTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIfElseTest.java new file mode 100644 index 00000000..d9115eb6 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIfElseTest.java @@ -0,0 +1,35 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyIfElse; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +import java.util.concurrent.atomic.AtomicInteger; + +public class EzyIfElseTest extends BaseTest { + + @Test + public void test() { + AtomicInteger num = new AtomicInteger(0); + EzyIfElse.withIf(true, () -> num.incrementAndGet()); + assertEquals(num.get(), 1); + EzyIfElse.withIf(false, () -> num.incrementAndGet()); + assertEquals(num.get(), 1); + EzyIfElse.withElse(false, () -> num.incrementAndGet()); + assertEquals(num.get(), 2); + EzyIfElse.withElse(true, () -> num.incrementAndGet()); + assertEquals(num.get(), 2); + EzyIfElse.withIfElse(true, () -> num.incrementAndGet(), () -> num.incrementAndGet()); + assertEquals(num.get(), 3); + EzyIfElse.withIfElse(false, () -> num.incrementAndGet(), () -> num.incrementAndGet()); + assertEquals(num.get(), 4); + } + + @Override + public Class getTestClass() { + return EzyIfElse.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyInterfacesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyInterfacesTest.java new file mode 100644 index 00000000..2a1db227 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyInterfacesTest.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.function.EzyApply; +import com.tvd12.ezyfoxserver.reflect.EzyInterfaces; +import com.tvd12.test.base.BaseTest; + +public class EzyInterfacesTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyInterfaces.class; + } + + @Test + public void test() { + assert EzyInterfaces.getInterface(InterfaceB.class, InterfaceC.class) != null; + assert EzyInterfaces.getInterface(InterfaceB.class, EzyApply.class) == null; + } + + public static class ClassA { + } + + public static interface InterfaceA { + } + + public static interface InterfaceB extends InterfaceA, InterfaceC { + + } + + public static interface InterfaceC { + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIntsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIntsIteratorTest.java new file mode 100644 index 00000000..7f946b13 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyIntsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyIntsIterator; + +public class EzyIntsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new int[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyIntsIterator.wrap(new int[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyKeyValueAnnotationsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyKeyValueAnnotationsTest.java new file mode 100644 index 00000000..f5d196fe --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyKeyValueAnnotationsTest.java @@ -0,0 +1,34 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.Map; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.ezyfoxserver.annotation.EzyKeyValue; +import com.tvd12.ezyfoxserver.util.EzyKeyValueAnnotations; +import com.tvd12.test.base.BaseTest; + +public class EzyKeyValueAnnotationsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyKeyValueAnnotations.class; + } + + @Test + public void test() { + Map map = EzyKeyValueAnnotations + .getProperties(ClassE.class.getAnnotation(EzyAutoImpl.class) + .properties()); + assert map.get("foo").equals("bar"); + } + + @EzyAutoImpl(properties = { + @EzyKeyValue(key = "foo", value = "bar") + }) + public interface ClassE { + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLoggableTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLoggableTest.java new file mode 100644 index 00000000..6769c030 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLoggableTest.java @@ -0,0 +1,14 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +public class EzyLoggableTest extends EzyLoggable { + + @Test + public void test() { + getLogger().debug("abc"); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLongsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLongsIteratorTest.java new file mode 100644 index 00000000..848a668c --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyLongsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyLongsIterator; + +public class EzyLongsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new long[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyLongsIterator.wrap(new long[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapBuilderTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapBuilderTest.java new file mode 100644 index 00000000..672332de --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapBuilderTest.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.HashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyMapBuilder; +import com.tvd12.test.base.BaseTest; + +public class EzyMapBuilderTest extends BaseTest { + + @Test + public void test() { + EzyMapBuilder.mapBuilder() + .map(new HashMap<>()) + .put("a", "b") + .putAll(new HashMap<>()) + .build(); + new EzyMapBuilder() + .build(); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapFactoryTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapFactoryTest.java new file mode 100644 index 00000000..2e84f069 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyMapFactoryTest.java @@ -0,0 +1,30 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyMapFactory; +import com.tvd12.test.base.BaseTest; + +public class EzyMapFactoryTest extends BaseTest { + + @SuppressWarnings({ "unused", "rawtypes" }) + @Test + public void test() { + EzyMapFactory factory = new EzyMapFactory(); + Map map = factory.newMap(Map.class); + HashMap hashMap = factory.newMap(HashMap.class); + TreeMap treeMap = factory.newMap(TreeMap.class); + ConcurrentHashMap concurrentHashMap = factory.newMap(ConcurrentHashMap.class); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test1() { + EzyMapFactory factory = new EzyMapFactory(); + factory.newMap(Integer.class); + } +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyObjectsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyObjectsTest.java new file mode 100644 index 00000000..ce640339 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyObjectsTest.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyObjects; +import com.tvd12.test.base.BaseTest; + +import lombok.EqualsAndHashCode; + +public class EzyObjectsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyObjects.class; + } + + @Test + public void test() { + assert EzyObjects.equals(null, null); + assert !EzyObjects.equals(null, this); + assert !EzyObjects.equals(this, null); + assert EzyObjects.equals(new ClassA(), new ClassA()); + } + + @EqualsAndHashCode + public static class ClassA { + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyProcessorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyProcessorTest.java new file mode 100644 index 00000000..307ced67 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyProcessorTest.java @@ -0,0 +1,159 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyProcessor; +import com.tvd12.test.base.BaseTest; + +public class EzyProcessorTest extends BaseTest { + + @Test + public void test() { + EzyProcessor.processWithException(() -> { + }); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test1() { + EzyProcessor.processWithException(() -> { + throw new Exception(); + }); + } + + @Test + public void test2() { + EzyProcessor.processWithIllegalArgumentException(() -> { + }); + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test4() { + EzyProcessor.processWithIllegalArgumentException(() -> { + throw new Exception(); + }); + } + + + @Test + public void test5() { + Lock lock = new ReentrantLock(); + EzyProcessor.processWithLock(() -> {}, lock); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test6() { + Lock lock = new ReentrantLock(); + EzyProcessor.processWithLock(() -> {throw new IllegalStateException();}, lock); + } + + @Test + public void test7() { + Lock lock = new ReentrantLock(); + try { + EzyProcessor.processWithTryLock(() -> {}, lock, 10); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test8() { + Lock lock = new ReentrantLock(); + try { + EzyProcessor.processWithTryLock(() -> {throw new IllegalStateException();}, lock, 10); + } catch (InterruptedException e) { + } + } + + @Test + public void test9() { + Lock lock = new ReentrantLock() { + private static final long serialVersionUID = 616957346213118575L; + + public boolean tryLock(long time, TimeUnit timeUnit) throws InterruptedException { + throw new InterruptedException(); + }; + }; + try { + EzyProcessor.processWithTryLock(() -> { + }, lock, 1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test + public void test10() { + Lock lock = new ReentrantLock() { + private static final long serialVersionUID = 616957346213118575L; + + public boolean tryLock(long time, TimeUnit timeUnit) throws InterruptedException { + return false; + }; + }; + try { + EzyProcessor.processWithTryLock(() -> { + }, lock, 1); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Test + public void test11() { + Lock lock = new ReentrantLock() { + private static final long serialVersionUID = 616957346213118575L; + + public boolean tryLock() { + return false; + }; + }; + EzyProcessor.processWithTryLock(() -> { + }, lock); + } + + @Test + public void test12() { + Lock lock = new ReentrantLock(); + EzyProcessor.processWithTryLock(() -> { + }, lock); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test13() { + Lock lock = new ReentrantLock(); + EzyProcessor.processWithTryLock(() -> { + throw new IllegalStateException(); + }, lock); + } + + @Test + public void test14() { + EzyProcessor.processWithLogException(() -> {}); + } + + @Test + public void test15() { + EzyProcessor.processWithLogException(() -> {throw new Exception();}); + } + + @Test + public void test16() { + EzyProcessor.processWithSync(() -> {}, this); + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test17() { + EzyProcessor.processWithSync(() -> {throw new IllegalStateException();}, this); + } + + @Override + public Class getTestClass() { + return EzyProcessor.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyPropertyAnnotationsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyPropertyAnnotationsTest.java new file mode 100644 index 00000000..23345e35 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyPropertyAnnotationsTest.java @@ -0,0 +1,75 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyProperty; +import com.tvd12.ezyfoxserver.reflect.EzyClass; +import com.tvd12.ezyfoxserver.reflect.EzyField; +import com.tvd12.ezyfoxserver.reflect.EzyMethod; +import com.tvd12.ezyfoxserver.reflect.EzyReflectElement; +import com.tvd12.ezyfoxserver.util.EzyPropertyAnnotations; +import com.tvd12.test.base.BaseTest; + +public class EzyPropertyAnnotationsTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzyPropertyAnnotations.class; + } + + @Test + public void test() { + EzyClass clazz = new EzyClass(ClassA.class); + EzyField a = clazz.getField("a"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)a).equals("a"); + EzyField b = clazz.getField("b"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)b).equals("1"); + + EzyMethod c = clazz.getMethod("setC"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)c).equals("c"); + + EzyMethod d = clazz.getMethod("setD"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)d).equals("2"); + + EzyMethod e = clazz.getMethod("setE"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)e).equals("3"); + + EzyMethod f = clazz.getMethod("setF"); + assert EzyPropertyAnnotations.getPropertyName(clazz, (EzyReflectElement)f).equals("f"); + } + + public static class ClassA { + + @EzyProperty + public String a; + + @EzyProperty("1") + public String b; + + @EzyProperty + private String c; + + @EzyProperty("2") + private String d; + + public void setC(String c) { + this.c = c; + } + + public void setD(String d) { + this.d = d; + } + + @EzyProperty("3") + public void setE(String e) { + + } + + @EzyProperty + public void setF(String f) { + + } + + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReferenceTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReferenceTest.java new file mode 100644 index 00000000..155554cc --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReferenceTest.java @@ -0,0 +1,45 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyReference; +import com.tvd12.test.base.BaseTest; + +public class EzyReferenceTest extends BaseTest { + + @Test + public void test() { + assert (new EzyReference() { + + @Override + public void retain() { + } + + @Override + public void release() { + } + + @Override + public int getReferenceCount() { + return 0; + } + }.releasable()); + + assert (new EzyReference() { + + @Override + public void retain() { + } + + @Override + public void release() { + } + + @Override + public int getReferenceCount() { + return 1; + } + }.releasable()) == false; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReturnerTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReturnerTest.java new file mode 100644 index 00000000..15f00add --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyReturnerTest.java @@ -0,0 +1,77 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyReturner; +import com.tvd12.test.base.BaseTest; + +public class EzyReturnerTest extends BaseTest { + + @Test + public void test() { + assert EzyReturner.returnNotNull(10, 100) == 10; + assert EzyReturner.returnNotNull(null, 100) == 100; + } + + @Test + public void test2() { + assert EzyReturner.returnWithException(() -> 100) == 100; + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test3() { + EzyReturner.returnWithException(() -> { + throw new Exception(); + }); + } + + @Test + public void test4() { + assert EzyReturner.returnWithIllegalArgumentException(() -> 100) == 100; + } + + @Test(expectedExceptions = {IllegalArgumentException.class}) + public void test5() { + EzyReturner.returnWithIllegalArgumentException(() -> { + throw new Exception(); + }); + } + + @Test + public void test6() { + Lock lock = new ReentrantLock(); + assert EzyReturner.returnWithLock(() -> 10, lock) == 10; + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test7() { + Lock lock = new ReentrantLock(); + EzyReturner.returnWithLock(() -> { + throw new IllegalStateException(); + }, lock); + } + + @Test + public void test8() { + assert EzyReturner.returnAndApply(10L, () -> {}) == 10L; + } + + @Test + public void test9() { + assert EzyReturner.returnWithSync(() -> 10L, this) == 10L; + } + + @Test(expectedExceptions = {IllegalStateException.class}) + public void test10() { + EzyReturner.returnWithSync(() -> {throw new IllegalStateException();}, this); + } + + @Override + public Class getTestClass() { + return EzyReturner.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyRoPropertiesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyRoPropertiesTest.java new file mode 100644 index 00000000..ab589189 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyRoPropertiesTest.java @@ -0,0 +1,41 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import java.util.Properties; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyRoProperties; +import com.tvd12.test.base.BaseTest; + +public class EzyRoPropertiesTest extends BaseTest { + + @Test + public void test() { + EzyRoProperties properties = new EzyRoProperties() { + + @Override + public T getProperty(Object key, Class clazz) { + return null; + } + + @SuppressWarnings("unchecked") + @Override + public String getProperty(Object key) { + return "hello"; + } + + @Override + public Properties getProperties() { + return null; + } + + @Override + public boolean containsKey(Object key) { + return false; + } + }; + + assert properties.getProperty(String.class).equals("hello"); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyShortsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyShortsIteratorTest.java new file mode 100644 index 00000000..a8780d8d --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyShortsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyBytesIterator; + +public class EzyShortsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new byte[] {1, 2, 3}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyBytesIterator.wrap(new byte[] {1, 2, 3}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyStringsIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyStringsIteratorTest.java new file mode 100644 index 00000000..dcbad608 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyStringsIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyStringsIterator; + +public class EzyStringsIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new String[] {"a", "b", "c"}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyStringsIterator.wrap(new String[] {"a", "b", "c"}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzySumTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzySumTest.java new file mode 100644 index 00000000..62d19bca --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzySumTest.java @@ -0,0 +1,43 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.tvd12.ezyfoxserver.util.EzySum; +import com.tvd12.test.base.BaseTest; + +public class EzySumTest extends BaseTest { + + @Override + public Class getTestClass() { + return EzySum.class; + } + + @Test + public void test() { + assert EzySum.sumBytes(new byte[] {1, 2, 3}) == 6; + assert EzySum.sumBytes(Lists.newArrayList((byte)1, (byte)2, (byte)3)) == 6; + + assert EzySum.sumDoubles(new double[] {1D, 2D, 3D}) == 6D; + assert EzySum.sumDoubles(Lists.newArrayList(1D, 2D, 3D)) == 6D; + + assert EzySum.sumFloats(new float[]{1F, 2F, 3F}) == 6D; + assert EzySum.sumFloats(Lists.newArrayList(1F, 2F, 3F)) == 6F; + + assert EzySum.sumInts(new int[]{1, 2, 3}) == 6D; + assert EzySum.sumInts(Lists.newArrayList(1, 2, 3)) == 6; + + assert EzySum.sumLongs(new long[]{1, 2, 3}) == 6D; + assert EzySum.sumLongs(Lists.newArrayList(1L, 2L, 3L)) == 6L; + + assert EzySum.sumShorts(new short[]{1, 2, 3}) == 6D; + assert EzySum.sumShorts(Lists.newArrayList((short)1, (short)2, (short)3)) == 6; + + assert EzySum.sumToInt(new String[] {"1", "2", "3"}, s -> Integer.valueOf(s)) == 6; + assert EzySum.sumToInt(Lists.newArrayList("1", "2", "3"), s -> Integer.valueOf(s)) == 6; + + assert EzySum.sumToLong(new String[] {"1", "2", "3"}, s -> Long.valueOf(s)) == 6; + assert EzySum.sumToLong(Lists.newArrayList("1", "2", "3"), s -> Long.valueOf(s)) == 6; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyTimesTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyTimesTest.java new file mode 100644 index 00000000..3403ff4f --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyTimesTest.java @@ -0,0 +1,25 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.util.EzyTimes; +import com.tvd12.test.base.BaseTest; +import static org.testng.Assert.*; + +public class EzyTimesTest extends BaseTest { + + @Test + public void test() { + assertEquals(EzyTimes.getRemainTime(0, 0), 0); + assertTrue(EzyTimes.getRemainTime(100, System.currentTimeMillis()) <= 100); + + assertEquals(EzyTimes.getPositiveRemainTime(0, 0), 0); + assertTrue(EzyTimes.getPositiveRemainTime(100, System.currentTimeMillis()) <= 100); + } + + @Override + public Class getTestClass() { + return EzyTimes.class; + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyWrapperIteratorTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyWrapperIteratorTest.java new file mode 100644 index 00000000..09ed3200 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/EzyWrapperIteratorTest.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import com.tvd12.ezyfoxserver.util.EzyArrayIterator; +import com.tvd12.ezyfoxserver.util.EzyWrapperIterator; + +public class EzyWrapperIteratorTest extends EzyArrayIteratorTest { + + @Override + protected Object newArray() { + return new String[] {"a", "b", "c"}; + } + + @Override + protected EzyArrayIterator newIterator() { + return EzyWrapperIterator.wrap(new String[] {"a", "b", "c"}); + } + +} diff --git a/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/ReflectionsTest.java b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/ReflectionsTest.java new file mode 100644 index 00000000..190fad41 --- /dev/null +++ b/ezyfox-server-util/src/test/java/com/tvd12/ezyfoxserver/testing/util/ReflectionsTest.java @@ -0,0 +1,16 @@ +package com.tvd12.ezyfoxserver.testing.util; + +import org.reflections.Reflections; +import org.testng.annotations.Test; + +import com.tvd12.ezyfoxserver.annotation.EzyAutoImpl; +import com.tvd12.test.base.BaseTest; + +public class ReflectionsTest extends BaseTest { + + @Test + public void test() { + new Reflections("non-exists").getTypesAnnotatedWith(EzyAutoImpl.class); + } + +} diff --git a/ezyfox-server-util/src/test/resources/AllTests.tng.xml b/ezyfox-server-util/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..6b82355c --- /dev/null +++ b/ezyfox-server-util/src/test/resources/AllTests.tng.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-webapi/assembly.xml b/ezyfox-server-webapi/assembly.xml new file mode 100644 index 00000000..9ccc91ef --- /dev/null +++ b/ezyfox-server-webapi/assembly.xml @@ -0,0 +1,16 @@ + + + bin + false + + zip + + + + + true + lib + + + + \ No newline at end of file diff --git a/ezyfox-server-webapi/pom.xml b/ezyfox-server-webapi/pom.xml new file mode 100644 index 00000000..881ac896 --- /dev/null +++ b/ezyfox-server-webapi/pom.xml @@ -0,0 +1,57 @@ + + 4.0.0 + + com.tvd12 + ezyfox-server + 0.0.2 + + + ezyfox-server-webapi + 1.0.0 + + ezyfox-server-webapi + http://www.tvd12.com/java/projects/ezyfox-server + + + 1.0.0 + 1.0.0 + 1.5.4.RELEASE + + + + + + org.springframework.boot + spring-boot-dependencies + ${springboot.version} + pom + import + + + + + + + com.tvd12 + ezyfox-server-core + ${ezy.core.version} + + + com.tvd12 + ezyfox-server-databridge + ${ezy.databridge.version} + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + \ No newline at end of file diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyAbstractHandlerInterceptor.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyAbstractHandlerInterceptor.java new file mode 100644 index 00000000..e735323d --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyAbstractHandlerInterceptor.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.webapi; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +public class EzyAbstractHandlerInterceptor implements HandlerInterceptor { + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + return true; + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyEmbeddedServletContainerCustomizer.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyEmbeddedServletContainerCustomizer.java new file mode 100644 index 00000000..7c9b0329 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyEmbeddedServletContainerCustomizer.java @@ -0,0 +1,27 @@ +package com.tvd12.ezyfoxserver.webapi; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; +import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; +import org.springframework.stereotype.Component; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.setting.EzyHttpSetting; +import com.tvd12.ezyfoxserver.setting.EzySettings; + +@Component +public class EzyEmbeddedServletContainerCustomizer + implements EmbeddedServletContainerCustomizer { + + @Autowired + protected EzyServerContext serverContext; + + @Override + public void customize(ConfigurableEmbeddedServletContainer container) { + EzyServer server = serverContext.getServer(); + EzySettings settings = server.getSettings(); + EzyHttpSetting http = settings.getHttp(); + container.setPort(http.getPort()); + } +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyHandlerInterceptor.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyHandlerInterceptor.java new file mode 100644 index 00000000..35626e38 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyHandlerInterceptor.java @@ -0,0 +1,24 @@ +package com.tvd12.ezyfoxserver.webapi; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class EzyHandlerInterceptor extends EzyAbstractHandlerInterceptor { + + protected Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + getLogger().debug("intercept request from {}, with url {}", request.getRemoteAddr(), request.getRequestURI()); + return true; + } + + protected Logger getLogger() { + return logger; + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyServerContextUnpacker.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyServerContextUnpacker.java new file mode 100644 index 00000000..20d332c3 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyServerContextUnpacker.java @@ -0,0 +1,55 @@ +package com.tvd12.ezyfoxserver.webapi; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.tvd12.ezyfoxserver.EzyServer; +import com.tvd12.ezyfoxserver.config.EzyConfig; +import com.tvd12.ezyfoxserver.context.EzyAppContext; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.setting.EzySettings; +import com.tvd12.ezyfoxserver.util.EzyLoggable; +import com.tvd12.ezyfoxserver.wrapper.EzyManagers; +import com.tvd12.ezyfoxserver.wrapper.EzySessionManager; +import com.tvd12.ezyfoxserver.wrapper.EzyServerUserManager; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzyServerContextUnpacker extends EzyLoggable { + + @Autowired + protected EzyServerContext serverContext; + + protected EzyServer getServer() { + return serverContext.getServer(); + } + + protected EzyConfig getConfig() { + return getServer().getConfig(); + } + + protected EzySettings getSettings() { + return getServer().getSettings(); + } + + protected EzyManagers getServerManagers() { + return getServer().getManagers(); + } + + protected EzyAppContext getAppContext(String appName) { + return serverContext.getAppContext(appName); + } + + protected EzyServerUserManager getServerUserManager() { + return getServerManagers().getManager(EzyServerUserManager.class); + } + + @SuppressWarnings("unchecked") + protected EzySessionManager getServerSessionManger() { + return getServerManagers().getManager(EzySessionManager.class); + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringApplication.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringApplication.java new file mode 100644 index 00000000..ac9cb5d8 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringApplication.java @@ -0,0 +1,28 @@ +package com.tvd12.ezyfoxserver.webapi; + +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; + +import com.tvd12.ezyfoxserver.context.EzyServerContext; + +import lombok.Setter; + +@Setter +public class EzySpringApplication extends SpringApplication { + + protected EzyServerContext serverContext; + + public EzySpringApplication(Object... sources) { + super(sources); + } + + @Override + protected ConfigurableApplicationContext createApplicationContext() { + ConfigurableApplicationContext ctx = super.createApplicationContext(); + ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); + beanFactory.registerSingleton("serverContext", serverContext); + return ctx; + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringHttpBootstrap.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringHttpBootstrap.java new file mode 100644 index 00000000..0da701e2 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzySpringHttpBootstrap.java @@ -0,0 +1,39 @@ +package com.tvd12.ezyfoxserver.webapi; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; + +import com.tvd12.ezyfoxserver.EzyHttpBootstrap; +import com.tvd12.ezyfoxserver.context.EzyServerContext; +import com.tvd12.ezyfoxserver.util.EzyLoggable; + +import lombok.Setter; + +@SpringBootApplication +public class EzySpringHttpBootstrap + extends EzyLoggable implements EzyHttpBootstrap { + + @Setter + protected EzyServerContext serverContext; + + protected ConfigurableApplicationContext applicationContext; + + @Override + public void start() throws Exception { + SpringApplication app = newApplication(); + applicationContext = app.run(); + } + + @Override + public void destroy() { + SpringApplication.exit(applicationContext, () -> 0); + } + + protected SpringApplication newApplication() { + EzySpringApplication app = new EzySpringApplication(getClass()); + app.setServerContext(serverContext); + return app; + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyWebMvcConfigurerAdapter.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyWebMvcConfigurerAdapter.java new file mode 100644 index 00000000..2dd83c95 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/EzyWebMvcConfigurerAdapter.java @@ -0,0 +1,15 @@ +package com.tvd12.ezyfoxserver.webapi; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +public class EzyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(new EzyHandlerInterceptor()); + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyAppUserManagerController.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyAppUserManagerController.java new file mode 100644 index 00000000..b1f51ac8 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyAppUserManagerController.java @@ -0,0 +1,29 @@ +package com.tvd12.ezyfoxserver.webapi.controller; + +import java.util.Collection; +import java.util.List; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.tvd12.ezyfoxserver.entity.EzyUser; +import com.tvd12.ezyfoxserver.proxydata.EzyProxyUser; +import com.tvd12.ezyfoxserver.wrapper.EzyAppUserManager; + +@RestController +@RequestMapping("admin/users") +public class EzyAppUserManagerController extends EzyController { + + @GetMapping + protected Collection getUsers(@RequestParam String appName) { + List users = getAppUserManager(appName).getUserList(); + return EzyProxyUser.newCollection(users); + } + + protected EzyAppUserManager getAppUserManager(String appName) { + return getAppContext(appName).getApp().getUserManager(); + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyController.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyController.java new file mode 100644 index 00000000..70bc61fe --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyController.java @@ -0,0 +1,11 @@ +package com.tvd12.ezyfoxserver.webapi.controller; + +import com.tvd12.ezyfoxserver.webapi.EzyServerContextUnpacker; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class EzyController extends EzyServerContextUnpacker { +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyServerSettingController.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyServerSettingController.java new file mode 100644 index 00000000..5ba9ce4b --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzyServerSettingController.java @@ -0,0 +1,18 @@ +package com.tvd12.ezyfoxserver.webapi.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.tvd12.ezyfoxserver.EzyServer; + +@RestController +@RequestMapping("admin/server-setting") +public class EzyServerSettingController extends EzyController { + + @GetMapping + public EzyServer getSetverSetting() { + return getServerContext().getServer(); + } + +} diff --git a/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzySessionManagerController.java b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzySessionManagerController.java new file mode 100644 index 00000000..485e2e84 --- /dev/null +++ b/ezyfox-server-webapi/src/main/java/com/tvd12/ezyfoxserver/webapi/controller/EzySessionManagerController.java @@ -0,0 +1,22 @@ +package com.tvd12.ezyfoxserver.webapi.controller; + +import java.util.Collection; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.tvd12.ezyfoxserver.entity.EzySession; +import com.tvd12.ezyfoxserver.proxydata.EzyProxySession; + +@RestController +@RequestMapping("admin/sessions") +public class EzySessionManagerController extends EzyController { + + @GetMapping("/all") + public Collection getSessions() { + Collection sessions = getServerSessionManger().getAllSessions(); + return EzyProxySession.newCollection(sessions); + } + +} diff --git a/ezyfox-server-webapi/src/main/resources/application.properties b/ezyfox-server-webapi/src/main/resources/application.properties new file mode 100755 index 00000000..b6b497cf --- /dev/null +++ b/ezyfox-server-webapi/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.main.banner-mode=off \ No newline at end of file diff --git a/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestApplication.java b/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestApplication.java new file mode 100644 index 00000000..c2bd702b --- /dev/null +++ b/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestApplication.java @@ -0,0 +1,23 @@ +package com.tvd12.ezyfoxserver.springboot.testing; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.context.EzyServerContext; + +@SpringBootApplication +public class MyTestApplication { + + @Bean + public EzyServerContext newServerContext() { + EzySimpleServer server = new MyTestServer(); + EzyServerContext context = mock(EzyServerContext.class); + when(context.getServer()).thenReturn(server); + return context; + } + +} diff --git a/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestServer.java b/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestServer.java new file mode 100644 index 00000000..c49f77b6 --- /dev/null +++ b/ezyfox-server-webapi/src/test/java/com/tvd12/ezyfoxserver/springboot/testing/MyTestServer.java @@ -0,0 +1,13 @@ +package com.tvd12.ezyfoxserver.springboot.testing; + +import com.tvd12.ezyfoxserver.EzySimpleServer; +import com.tvd12.ezyfoxserver.setting.EzySimpleSettings; + +public class MyTestServer extends EzySimpleServer { + + public MyTestServer() { + EzySimpleSettings settings = new EzySimpleSettings(); + setSettings(settings); + } + +} diff --git a/ezyfox-server-webapi/src/test/resources/AllTests.tng.xml b/ezyfox-server-webapi/src/test/resources/AllTests.tng.xml new file mode 100644 index 00000000..3f571ed5 --- /dev/null +++ b/ezyfox-server-webapi/src/test/resources/AllTests.tng.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/ezyfox-server-webapi/src/test/resources/testupload.txt b/ezyfox-server-webapi/src/test/resources/testupload.txt new file mode 100755 index 00000000..5b97ca74 --- /dev/null +++ b/ezyfox-server-webapi/src/test/resources/testupload.txt @@ -0,0 +1 @@ +Spring Framework \ No newline at end of file diff --git a/pom.xml b/pom.xml index dad796f3..0b4ce39c 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ ezyfox-server http://www.tvd12.com/java/projects/ezyfox-server - Socket server + Common maven project configuration @@ -63,8 +63,9 @@ 1.8 1.8 + 2.9.9 21.0 - 0.9.10 + 0.9.11 1.10 1.0.3 @@ -104,6 +105,11 @@ guava ${google.guava.version} + + joda-time + joda-time + ${joda.time.version} + org.reflections reflections @@ -154,13 +160,31 @@ ${maven.compiler.target} + + org.jacoco + jacoco-maven-plugin + 0.7.9 + + + prepare-agent + + prepare-agent + + + + default-report + prepare-package + report + + + org.apache.maven.plugins maven-surefire-plugin - 2.19.1 + 2.20 src/test/resources/AllTests.tng.xml @@ -179,7 +203,7 @@ - deploy + ezyfox-deploy @@ -250,6 +274,7 @@ maven-deploy-plugin + 2.8.2 true @@ -259,10 +284,6 @@ maven-release-plugin 2.5.3 - - maven-deploy-plugin - 2.8.2 - maven-install-plugin 2.5.2