From dc638c3fe8d38fb81901235b8060d1308724e9ca Mon Sep 17 00:00:00 2001 From: RedKale <22250530@qq.com> Date: Thu, 31 Mar 2016 17:49:16 +0800 Subject: [PATCH] --- test/META-INF/persistence.xml | 14 + test/org/redkale/source/FilterNodeTest.java | 303 ++++++++++++++++++ .../org/redkale/test/convert/BasedEntity.java | 21 ++ .../redkale/test/convert/BsonTestMain.java | 89 +++++ .../redkale/test/convert/ComplextEntity.java | 71 ++++ .../test/convert/ConstructorArgsEntity.java | 67 ++++ .../redkale/test/convert/ConvertRecord.java | 192 +++++++++++ .../redkale/test/convert/GenericEntity.java | 110 +++++++ .../test/convert/InnerCoderEntity.java | 119 +++++++ .../redkale/test/convert/JsonTestMain.java | 73 +++++ .../test/convert/SimpleChildEntity.java | 60 ++++ .../redkale/test/convert/SimpleEntity.java | 137 ++++++++ .../org/redkale/test/convert/media/Image.java | 117 +++++++ .../org/redkale/test/convert/media/Media.java | 203 ++++++++++++ .../test/convert/media/MediaContent.java | 109 +++++++ .../redkale/test/http/HttpRequestDesc.java | 189 +++++++++++ .../redkale/test/http/HttpResponseDesc.java | 105 ++++++ test/org/redkale/test/http/WebSocketDesc.java | 154 +++++++++ .../redkale/test/net/UploadTestServlet.java | 50 +++ test/org/redkale/test/service/Person.java | 32 ++ test/org/redkale/test/service/TestBean.java | 14 + test/org/redkale/test/sncp/SncpTest.java | 210 ++++++++++++ test/org/redkale/test/sncp/SncpTestBean.java | 54 ++++ .../redkale/test/sncp/SncpTestIService.java | 20 ++ .../redkale/test/sncp/SncpTestService.java | 101 ++++++ .../redkale/test/source/CacheTestBean.java | 81 +++++ test/org/redkale/test/source/JDBCTest.java | 42 +++ .../redkale/test/source/LoginTestBean.java | 26 ++ .../redkale/test/source/LoginTestRecord.java | 95 ++++++ .../redkale/test/source/TestSourceCache.java | 134 ++++++++ test/org/redkale/test/util/CreatorRecord.java | 97 ++++++ test/org/redkale/test/util/ResourceTest.java | 153 +++++++++ test/org/redkale/test/util/TestABean.java | 14 + test/org/redkale/test/util/TestBean.java | 46 +++ test/org/redkale/test/util/TestXBean.java | 15 + test/org/redkale/test/util/UntilTestMain.java | 103 ++++++ .../test/websocket/ChatWebSocketServlet.java | 77 +++++ test/org/redkale/test/websocket/Flash843.java | 29 ++ .../test/websocket/VideoWebSocketServlet.java | 134 ++++++++ 39 files changed, 3660 insertions(+) create mode 100644 test/META-INF/persistence.xml create mode 100644 test/org/redkale/source/FilterNodeTest.java create mode 100644 test/org/redkale/test/convert/BasedEntity.java create mode 100644 test/org/redkale/test/convert/BsonTestMain.java create mode 100644 test/org/redkale/test/convert/ComplextEntity.java create mode 100644 test/org/redkale/test/convert/ConstructorArgsEntity.java create mode 100644 test/org/redkale/test/convert/ConvertRecord.java create mode 100644 test/org/redkale/test/convert/GenericEntity.java create mode 100644 test/org/redkale/test/convert/InnerCoderEntity.java create mode 100644 test/org/redkale/test/convert/JsonTestMain.java create mode 100644 test/org/redkale/test/convert/SimpleChildEntity.java create mode 100644 test/org/redkale/test/convert/SimpleEntity.java create mode 100644 test/org/redkale/test/convert/media/Image.java create mode 100644 test/org/redkale/test/convert/media/Media.java create mode 100644 test/org/redkale/test/convert/media/MediaContent.java create mode 100644 test/org/redkale/test/http/HttpRequestDesc.java create mode 100644 test/org/redkale/test/http/HttpResponseDesc.java create mode 100644 test/org/redkale/test/http/WebSocketDesc.java create mode 100644 test/org/redkale/test/net/UploadTestServlet.java create mode 100644 test/org/redkale/test/service/Person.java create mode 100644 test/org/redkale/test/service/TestBean.java create mode 100644 test/org/redkale/test/sncp/SncpTest.java create mode 100644 test/org/redkale/test/sncp/SncpTestBean.java create mode 100644 test/org/redkale/test/sncp/SncpTestIService.java create mode 100644 test/org/redkale/test/sncp/SncpTestService.java create mode 100644 test/org/redkale/test/source/CacheTestBean.java create mode 100644 test/org/redkale/test/source/JDBCTest.java create mode 100644 test/org/redkale/test/source/LoginTestBean.java create mode 100644 test/org/redkale/test/source/LoginTestRecord.java create mode 100644 test/org/redkale/test/source/TestSourceCache.java create mode 100644 test/org/redkale/test/util/CreatorRecord.java create mode 100644 test/org/redkale/test/util/ResourceTest.java create mode 100644 test/org/redkale/test/util/TestABean.java create mode 100644 test/org/redkale/test/util/TestBean.java create mode 100644 test/org/redkale/test/util/TestXBean.java create mode 100644 test/org/redkale/test/util/UntilTestMain.java create mode 100644 test/org/redkale/test/websocket/ChatWebSocketServlet.java create mode 100644 test/org/redkale/test/websocket/Flash843.java create mode 100644 test/org/redkale/test/websocket/VideoWebSocketServlet.java diff --git a/test/META-INF/persistence.xml b/test/META-INF/persistence.xml new file mode 100644 index 000000000..eba70637b --- /dev/null +++ b/test/META-INF/persistence.xml @@ -0,0 +1,14 @@ + + + + false + ALL + NONE + + + + + + + + diff --git a/test/org/redkale/source/FilterNodeTest.java b/test/org/redkale/source/FilterNodeTest.java new file mode 100644 index 000000000..02b524aef --- /dev/null +++ b/test/org/redkale/source/FilterNodeTest.java @@ -0,0 +1,303 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.source; + +import org.redkale.util.AutoLoad; +import static org.redkale.source.FilterExpress.*; +import java.util.*; +import java.util.function.*; +import javax.persistence.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class FilterNodeTest { + + public static void main(String[] args) throws Exception { + final Properties props = new Properties(); + final Function fullloader = (Class t) -> new ArrayList(); + final Function func = (Class t) -> EntityInfo.load(t, 0, false, props, fullloader); + final EntityInfo carEntity = EntityInfo.load(CarTestTable.class, 0, false, props, (t) -> CarTestTable.createList()); + final EntityInfo userEntity = EntityInfo.load(UserTestTable.class, 0, false, props, (t) -> UserTestTable.createList()); + final EntityInfo typeEntity = EntityInfo.load(CarTypeTestTable.class, 0, false, props, (t) -> CarTypeTestTable.createList()); + + final CarTestBean bean = new CarTestBean(); + bean.carid = 70002; + bean.username = "用户1"; + bean.createtime = 500; + bean.typename = "法拉利"; + FilterNode joinNode1 = FilterJoinNode.create(UserTestTable.class, new String[]{"userid", "username"}, "username", LIKE, bean.username) + .or(FilterJoinNode.create(UserTestTable.class, new String[]{"userid", "username"}, "createtime", GREATERTHAN, bean.createtime)); + FilterNode joinNode2 = FilterJoinNode.create(CarTypeTestTable.class, "cartype", "typename", LIKE, bean.typename); + FilterNode node = CarTestBean.caridTransient() ? (joinNode2.or(joinNode1)) : FilterNode.create("carid", GREATERTHAN, bean.carid).and(joinNode1).or(joinNode2); + FilterNode beanNode = FilterNodeBean.createFilterNode(bean); + System.out.println("node.string = " + node); + System.out.println("bean.string = " + beanNode); + Map nodeJoinTabalis = node.getJoinTabalis(); + Map beanJoinTabalis = beanNode.getJoinTabalis(); + CharSequence nodeJoinsql = node.createSQLJoin(func, nodeJoinTabalis, carEntity); + CharSequence beanJoinsql = beanNode.createSQLJoin(func, beanJoinTabalis, carEntity); + CharSequence nodeWhere = node.createSQLExpress(carEntity, nodeJoinTabalis); + CharSequence beanWhere = beanNode.createSQLExpress(carEntity, beanJoinTabalis); + System.out.println("node.sql = SELECT a.* FROM " + CarTestTable.class.getSimpleName().toLowerCase() + " a" + (nodeJoinsql == null ? "" : nodeJoinsql) + " WHERE " + nodeWhere); + System.out.println("bean.sql = SELECT a.* FROM " + CarTestTable.class.getSimpleName().toLowerCase() + " a" + (beanJoinsql == null ? "" : beanJoinsql) + " WHERE " + beanWhere); + assert node.isCacheUseable(func) : "isCacheUseable 应该是true"; + assert beanNode.isCacheUseable(func) : "isCacheUseable 应该是true"; + System.out.println("node.Predicate = " + node.createPredicate(carEntity.getCache())); + System.out.println("bean.Predicate = " + beanNode.createPredicate(carEntity.getCache())); + System.out.println("node.sheet = " + carEntity.getCache().querySheet(null, new Flipper(), node)); + System.out.println("bean.sheet = " + carEntity.getCache().querySheet(null, new Flipper(), beanNode)); + } + + public static class CarTestBean implements FilterBean { + + @FilterGroup("[OR].[AND]a") + @FilterColumn(express = GREATERTHAN) + @Transient + public long carid; + + @FilterGroup("[OR].[AND]a.[OR]c") + @FilterColumn(express = LIKE) + @FilterJoinColumn(table = UserTestTable.class, columns = {"userid", "username"}) + public String username; + + @FilterGroup("[OR].[AND]a.[OR]c") + @FilterColumn(express = GREATERTHAN) + @FilterJoinColumn(table = UserTestTable.class, columns = {"userid", "username"}) + public long createtime; + + @FilterGroup("[OR]") + @FilterColumn(express = LIKE) + @FilterJoinColumn(table = CarTypeTestTable.class, columns = {"cartype"}) + public String typename; + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public static boolean caridTransient() { + try { + return CarTestBean.class.getDeclaredField("carid").getAnnotation(Transient.class) != null; + } catch (Exception e) { + e.printStackTrace(); + return true; + } + } + } + + @AutoLoad + @Cacheable + public static class CarTestTable { + + public static List createList() { + List list = new ArrayList<>(); + + list.add(new CarTestTable(70001, 101, 1000011, "我的车")); + list.add(new CarTestTable(70002, 102, 1000012, "我的车")); + list.add(new CarTestTable(70003, 103, 1000013, "我的车")); + list.add(new CarTestTable(70004, 104, 1000014, "我的车")); + list.add(new CarTestTable(70005, 105, 1000015, "我的车")); + + list.add(new CarTestTable(70201, 201, 1000031, "我的车")); + list.add(new CarTestTable(70202, 202, 1000032, "我的车")); + list.add(new CarTestTable(70203, 203, 1000033, "我的车")); + list.add(new CarTestTable(70204, 204, 1000034, "我的车")); + list.add(new CarTestTable(70205, 205, 1000035, "我的车")); + list.add(new CarTestTable(70505, 301, 1008000, "我的车")); + + return list; + } + + @Id + private long carid; + + private int cartype; + + private int userid; + + private String username; + + private String cartitle; + + public CarTestTable() { + + } + + public CarTestTable(long carid, int cartype, int userid, String cartitle) { + this.carid = carid; + this.cartype = cartype; + this.userid = userid; + this.username = "用户" + userid % 1000; + this.cartitle = cartitle; + } + + public long getCarid() { + return carid; + } + + public void setCarid(long carid) { + this.carid = carid; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getCartitle() { + return cartitle; + } + + public void setCartitle(String cartitle) { + this.cartitle = cartitle; + } + + public int getCartype() { + return cartype; + } + + public void setCartype(int cartype) { + this.cartype = cartype; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + } + + @AutoLoad + @Cacheable + public static class CarTypeTestTable { + + public static List createList() { + List list = new ArrayList<>(); + list.add(new CarTypeTestTable(101, "奥迪A1")); + list.add(new CarTypeTestTable(102, "奥迪A2")); + list.add(new CarTypeTestTable(103, "奥迪A3")); + list.add(new CarTypeTestTable(104, "奥迪A4")); + list.add(new CarTypeTestTable(105, "奥迪A5")); + list.add(new CarTypeTestTable(201, "奔驰S1")); + list.add(new CarTypeTestTable(202, "奔驰S2")); + list.add(new CarTypeTestTable(203, "奔驰S3")); + list.add(new CarTypeTestTable(204, "奔驰S4")); + list.add(new CarTypeTestTable(205, "奔驰S5")); + list.add(new CarTypeTestTable(301, "法拉利")); + return list; + } + + @Id + private int cartype; + + private String typename; + + public CarTypeTestTable() { + + } + + public CarTypeTestTable(int cartype, String typename) { + this.cartype = cartype; + this.typename = typename; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public int getCartype() { + return cartype; + } + + public void setCartype(int cartype) { + this.cartype = cartype; + } + + public String getTypename() { + return typename; + } + + public void setTypename(String typename) { + this.typename = typename; + } + + } + + @AutoLoad + @Cacheable + public static class UserTestTable { + + public static List createList() { + List list = new ArrayList<>(); + for (int i = 11; i <= 50; i++) { + list.add(new UserTestTable(1000000 + i, "用户" + i, i * 20)); + } + list.add(new UserTestTable(1008000, "车主A", 20)); + return list; + } + + @Id + private int userid; + + private String username; + + private long createtime; + + public UserTestTable() { + } + + public UserTestTable(int userid, String username, long createtime) { + this.userid = userid; + this.username = username; + this.createtime = createtime; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public long getCreatetime() { + return createtime; + } + + public void setCreatetime(long createtime) { + this.createtime = createtime; + } + + } +} diff --git a/test/org/redkale/test/convert/BasedEntity.java b/test/org/redkale/test/convert/BasedEntity.java new file mode 100644 index 000000000..d1dc3867c --- /dev/null +++ b/test/org/redkale/test/convert/BasedEntity.java @@ -0,0 +1,21 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.io.Serializable; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public abstract class BasedEntity implements Serializable { + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } +} diff --git a/test/org/redkale/test/convert/BsonTestMain.java b/test/org/redkale/test/convert/BsonTestMain.java new file mode 100644 index 000000000..c94834392 --- /dev/null +++ b/test/org/redkale/test/convert/BsonTestMain.java @@ -0,0 +1,89 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.io.*; +import org.redkale.convert.bson.BsonByteBufferWriter; +import org.redkale.convert.bson.BsonFactory; +import org.redkale.util.Utility; +import org.redkale.convert.bson.BsonConvert; +import java.nio.*; +import java.util.Arrays; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class BsonTestMain { + + public static void main(String[] args) throws Exception { + Serializable[] sers = new Serializable[]{"aaa", 4}; + final BsonConvert convert = BsonFactory.root().getConvert(); + byte[] bytes = convert.convertTo(sers); + Utility.println("---", bytes); + Serializable[] a = convert.convertFrom(Serializable[].class, bytes); + System.out.println(Arrays.toString(a)); + main2(args); + main3(args); + main4(args); + } + + public static void main2(String[] args) throws Exception { + final BsonConvert convert = BsonFactory.root().getConvert(); + SimpleChildEntity entry = SimpleChildEntity.create(); + byte[] bytes = convert.convertTo(SimpleEntity.class, entry); + System.out.println("长度: " + bytes.length); + BsonByteBufferWriter writer = convert.pollBsonWriter(() -> ByteBuffer.allocate(1)); + convert.convertTo(writer, SimpleEntity.class, entry); + ByteBuffer[] buffers = writer.toBuffers(); + int len = 0; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (ByteBuffer b : buffers) { + len += b.remaining(); + byte[] ts = new byte[b.remaining()]; + b.get(ts); + out.write(ts); + b.flip(); + } + System.out.println("长度: " + len); + SimpleChildEntity entry2 = convert.convertFrom(SimpleChildEntity.class, buffers); + System.out.println(entry); + System.out.println(entry2); + } + + public static void main3(String[] args) throws Exception { + final BsonConvert convert = BsonFactory.root().getConvert(); + SimpleChildEntity entry = SimpleChildEntity.create(); + byte[] bytes = convert.convertTo(SimpleEntity.class, entry); + Utility.println(null, bytes); + System.out.println(JsonConvert.root().convertTo(entry)); + SimpleEntity rs = convert.convertFrom(SimpleEntity.class, bytes); + System.out.println(rs.toString()); + System.out.println(JsonConvert.root().convertTo(rs)); + + ComplextEntity bean = new ComplextEntity(); + byte[] bytes2 = convert.convertTo(Object.class, bean); + final int len = bytes2.length; + BsonByteBufferWriter writer = convert.pollBsonWriter(() -> ByteBuffer.allocate(len / 2)); + convert.convertTo(writer, bean); + bytes2 = writer.toArray(); + System.out.println(convert.convertFrom(ComplextEntity.class, bytes2).toString()); + } + + public static void main4(String[] args) throws Exception { + final BsonConvert convert = BsonFactory.root().getConvert(); + SimpleChildEntity entry = SimpleChildEntity.create(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + convert.convertTo(out, SimpleEntity.class, entry); + byte[] bytes = out.toByteArray(); + Utility.println(null, bytes); + System.out.println(JsonConvert.root().convertTo(entry)); + SimpleEntity rs = convert.convertFrom(SimpleEntity.class, new ByteArrayInputStream(bytes)); + System.out.println(rs.toString()); + + } +} diff --git a/test/org/redkale/test/convert/ComplextEntity.java b/test/org/redkale/test/convert/ComplextEntity.java new file mode 100644 index 000000000..14f4fe11f --- /dev/null +++ b/test/org/redkale/test/convert/ComplextEntity.java @@ -0,0 +1,71 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.util.List; +import javax.persistence.*; + +/** + * + * @author zhangjx + */ +public class ComplextEntity extends BasedEntity { + + @Id + private int userid; + + private String chname = ""; + + @Transient + private boolean flag = true; + + @Transient + private List children; + + @Transient + private SimpleEntity user; + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getChname() { + return chname; + } + + public void setChname(String chname) { + this.chname = chname; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + public SimpleEntity getUser() { + return user; + } + + public void setUser(SimpleEntity user) { + this.user = user; + } + +} diff --git a/test/org/redkale/test/convert/ConstructorArgsEntity.java b/test/org/redkale/test/convert/ConstructorArgsEntity.java new file mode 100644 index 000000000..871b3a63a --- /dev/null +++ b/test/org/redkale/test/convert/ConstructorArgsEntity.java @@ -0,0 +1,67 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.beans.*; +import org.redkale.convert.bson.*; +import org.redkale.convert.json.*; + +/** + * 测试不存在无参数的构造函数的bean类解析 + * + * @author zhangjx + */ +public class ConstructorArgsEntity { + + private final int userid; + + private String name; + + private long createtime; + + @ConstructorProperties({"userid", "name"}) + public ConstructorArgsEntity(int userid, String name) { + this.userid = userid; + this.name = name; + } + + public static void main(String[] args) throws Exception { + final JsonConvert jsonConvert = JsonConvert.root(); + final BsonConvert bsonConvert = BsonFactory.root().getConvert(); + ConstructorArgsEntity bean = new ConstructorArgsEntity(12345678, "哈哈"); + bean.setCreatetime(System.currentTimeMillis()); + String json = jsonConvert.convertTo(bean); + System.out.println(json); + System.out.println(jsonConvert.convertFrom(ConstructorArgsEntity.class, json).toString()); + byte[] bytes = bsonConvert.convertTo(bean); + System.out.println(bsonConvert.convertFrom(ConstructorArgsEntity.class, bytes).toString()); + } + + public int getUserid() { + return userid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getCreatetime() { + return createtime; + } + + public void setCreatetime(long createtime) { + this.createtime = createtime; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } +} diff --git a/test/org/redkale/test/convert/ConvertRecord.java b/test/org/redkale/test/convert/ConvertRecord.java new file mode 100644 index 000000000..55ac8fe35 --- /dev/null +++ b/test/org/redkale/test/convert/ConvertRecord.java @@ -0,0 +1,192 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + + +import java.util.*; + +/** + * + * @author redkale + */ +public class ConvertRecord { + + private String aname; + + private String desc = ""; + + private int id = (int) System.currentTimeMillis(); + + private int[] integers; + + private long[] longs; + + private List strings; + + private Map map; + + public static ConvertRecord createDefault() { + ConvertRecord v = new ConvertRecord(); + v.setAname("this is name\n \"test"); + v.setId(1000000001); + v.setIntegers(new int[]{12, 34, 56, 78, 90, 123, 456, 789}); + v.setLongs(new long[]{10000012L, 10000034L, 10000056L, 10000078L, -10000090L, -100000123L, -100000456L, -100000789L}); + List list = new ArrayList<>(); + list.add("str_a"); + list.add("str_b"); + list.add("str_c"); + v.setStrings(list); + Map map = new HashMap<>(); + map.put("key_a", 111); + map.put("key_b", 222); + map.put("key_c", 333); + v.setMap(map); + return v; + } + + public static void main(String[] args) throws Exception { + final ConvertRecord entry = ConvertRecord.createDefault(); + run(ConvertRecord.class, entry); + } + + public static void run(final Class type, final T entry) throws Exception { + /** + final org.redkale.convert.json.JsonConvert convert = org.redkale.convert.json.JsonFactory.root().getConvert(); + final String entryString = convert.convertTo(entry); + convert.convertFrom(type, entryString); + System.out.println("redkale-convert: " + convert.convertTo(entry)); + + com.alibaba.fastjson.JSON.parseObject(entryString, type); + System.out.println("fastjson 1.2.7: " + com.alibaba.fastjson.JSON.toJSONString(entry)); + + final com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper(); + mapper.readValue(entryString, type); + System.out.println("jackson 2.7.2: " + mapper.writeValueAsString(entry)); + + final com.google.gson.Gson gson = new com.google.gson.Gson(); + gson.fromJson(entryString, type); + System.out.println("google-gson 2.4: " + gson.toJson(entry)); + + System.out.println("------------------------------------------------"); + System.out.println("组件 序列化耗时(ms) 反序列化耗时(ms)"); + final int count = 10_0000; + long s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + convert.convertTo(entry); + } + long e = System.currentTimeMillis() - s; + System.out.print("redkale-convert " + e); + + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + convert.convertFrom(type, entryString); + } + e = System.currentTimeMillis() - s; + System.out.println("\t " + e); + + //---------------------------------------------------------------------------- + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + com.alibaba.fastjson.JSON.toJSONString(entry); + } + e = System.currentTimeMillis() - s; + System.out.print("fastjson 1.2.7 " + e); + + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + com.alibaba.fastjson.JSON.parseObject(entryString, type); + } + e = System.currentTimeMillis() - s; + System.out.println("\t " + e); + //---------------------------------------------------------------------------- + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + mapper.writeValueAsString(entry); + } + e = System.currentTimeMillis() - s; + System.out.print("jackson 2.7.2 " + e); + + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + mapper.readValue(entryString, type); + } + e = System.currentTimeMillis() - s; + System.out.println("\t " + e); + //---------------------------------------------------------------------------- + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + gson.toJson(entry); + } + e = System.currentTimeMillis() - s; + System.out.print("google-gson 2.4 " + e); + + s = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + gson.fromJson(entryString, type); + } + e = System.currentTimeMillis() - s; + System.out.println("\t " + e); + //---------------------------------------------------------------------------- + */ + } + + public String getAname() { + return aname; + } + + public void setAname(String aname) { + this.aname = aname; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int[] getIntegers() { + return integers; + } + + public void setIntegers(int[] integers) { + this.integers = integers; + } + + public long[] getLongs() { + return longs; + } + + public void setLongs(long[] longs) { + this.longs = longs; + } + + public List getStrings() { + return strings; + } + + public void setStrings(List strings) { + this.strings = strings; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + +} diff --git a/test/org/redkale/test/convert/GenericEntity.java b/test/org/redkale/test/convert/GenericEntity.java new file mode 100644 index 000000000..04e86fa9f --- /dev/null +++ b/test/org/redkale/test/convert/GenericEntity.java @@ -0,0 +1,110 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import org.redkale.util.TypeToken; +import org.redkale.convert.json.JsonFactory; +import java.lang.reflect.*; +import java.util.*; +import org.redkale.convert.json.*; + +/** + * 支持泛型的 + * + * @author zhangjx + * @param + * @param + * @param + */ +public class GenericEntity { + + private K name; + + private List list; + + private Entry entry; + + public static void main(String[] args) throws Throwable { + GenericEntity bean = new GenericEntity<>(); + bean.setName("你好"); + List list = new ArrayList<>(); + list.add(1234567890L); + bean.setList(list); + bean.setEntry(new Entry<>("aaaa", SimpleEntity.create())); + final Type type = new TypeToken>() { + }.getType(); + JsonFactory.root().tiny(true); + String json = JsonConvert.root().convertTo(bean); + System.out.println(json); + System.out.println(JsonConvert.root().convertFrom(type, json).toString()); + } + + @Override + public String toString() { + return "{\"entry\":" + entry + ",\"list\":" + list + ",\"name\":\"" + name + "\"}"; + } + + public K getName() { + return name; + } + + public void setName(K name) { + this.name = name; + } + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + + public Entry getEntry() { + return entry; + } + + public void setEntry(Entry entry) { + this.entry = entry; + } + + public static class Entry { + + private K key; + + private V value; + + public Entry() { + } + + public Entry(K key, V value) { + this.key = key; + this.value = value; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public K getKey() { + return key; + } + + public void setKey(K key) { + this.key = key; + } + + public V getValue() { + return value; + } + + public void setValue(V value) { + this.value = value; + } + + } +} diff --git a/test/org/redkale/test/convert/InnerCoderEntity.java b/test/org/redkale/test/convert/InnerCoderEntity.java new file mode 100644 index 000000000..ba761182a --- /dev/null +++ b/test/org/redkale/test/convert/InnerCoderEntity.java @@ -0,0 +1,119 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import org.redkale.convert.*; +import org.redkale.convert.bson.*; +import org.redkale.convert.json.*; +import org.redkale.util.*; + +/** + * + * @author zhangjx + */ +public class InnerCoderEntity { + + private final String val; + + private final int id; + + private InnerCoderEntity(int id, String value) { + this.id = id; + this.val = value; + } + + public static InnerCoderEntity create(int id, String value) { + return new InnerCoderEntity(id, value); + } + + /** + * 该方法提供给Convert组件自动加载。 + * 1) 方法名可以随意。 + 2) 方法必须是static + 3)方法的参数有且只能有一个, 且必须是org.redkale.convert.ConvertFactory或子类。 + —3.1) 参数类型为org.redkale.convert.ConvertFactory 表示适合JSON和BSON。 + —3.2) 参数类型为org.redkale.convert.json.JsonFactory 表示仅适合JSON。 + —3.3) 参数类型为org.redkale.convert.bson.BsonFactory 表示仅适合BSON。 + 4)方法的返回类型必须是org.redkale.convert.Decodeable/org.redkale.convert.Encodeable/org.redkale.convert.SimpledCoder + 若返回类型不是org.redkale.convert.SimpledCoder, 就必须提供两个方法: 一个返回Decodeable 一个返回 Encodeable。 + * + * @param factory + * @return + */ + private static SimpledCoder createConvertCoder(final org.redkale.convert.ConvertFactory factory) { + return new SimpledCoder() { + + //必须与EnMember[] 顺序一致 + private final DeMember[] deMembers = new DeMember[]{ + DeMember.create(factory, InnerCoderEntity.class, "id"), + DeMember.create(factory, InnerCoderEntity.class, "val")}; + + //必须与DeMember[] 顺序一致 + private final EnMember[] enMembers = new EnMember[]{ + EnMember.create(factory, InnerCoderEntity.class, "id"), + EnMember.create(factory, InnerCoderEntity.class, "val")}; + + @Override + public void convertTo(Writer out, InnerCoderEntity value) { + if (value == null) { + out.writeObjectNull(InnerCoderEntity.class); + return; + } + out.writeObjectB(value); + for (EnMember member : enMembers) { + out.writeObjectField(member, value); + } + out.writeObjectE(value); + } + + @Override + public InnerCoderEntity convertFrom(Reader in) { + if (in.readObjectB(InnerCoderEntity.class) == null) return null; + int index = 0; + final Object[] params = new Object[deMembers.length]; + while (in.hasNext()) { + DeMember member = in.readFieldName(deMembers); //读取字段名 + in.readBlank(); //读取字段名与字段值之间的间隔符,JSON则是跳过冒号: + if (member == null) { + in.skipValue(); //跳过不存在的字段的值, 一般不会发生 + } else { + params[index++] = member.read(in); + } + } + in.readObjectE(InnerCoderEntity.class); + return InnerCoderEntity.create(params[0] == null ? 0 : (Integer) params[0], (String) params[1]); + } + }; + } + + public int getId() { + return id; + } + + public String getVal() { + return val; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public static void main(String[] args) throws Exception { + InnerCoderEntity record = InnerCoderEntity.create(200, "haha"); + final JsonConvert convert = JsonConvert.root(); + String json = convert.convertTo(record); + System.out.println(json); + System.out.println(convert.convertFrom(InnerCoderEntity.class, json).toString()); + + final BsonConvert convert2 = BsonFactory.root().getConvert(); + byte[] bs = convert2.convertTo(InnerCoderEntity.class, null); + Utility.println("--", bs); + InnerCoderEntity r = convert2.convertFrom(InnerCoderEntity.class, bs); + System.out.println(r); + } + +} diff --git a/test/org/redkale/test/convert/JsonTestMain.java b/test/org/redkale/test/convert/JsonTestMain.java new file mode 100644 index 000000000..960abce92 --- /dev/null +++ b/test/org/redkale/test/convert/JsonTestMain.java @@ -0,0 +1,73 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.io.*; +import org.redkale.convert.json.JsonConvert; +import org.redkale.convert.json.JsonFactory; +import java.nio.*; +import java.util.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class JsonTestMain { + + public static void main(String[] args) throws Exception { + JsonFactory factory = JsonFactory.root().tiny(true); + final JsonConvert convert = JsonConvert.root(); + String json = "{\"access_token\":\"vVX2bIjN5P9TMOphDkStM96eNWapAehTuWAlVDO74aFaYxLwj2b-9-T9p_W2mfr9\",\"expires_in\":7200, \"aa\":\"\"}"; + Map map = convert.convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, json); + System.out.println(map); + System.out.println(convert.convertTo(map)); + ByteBuffer[] buffers = convert.convertTo(() -> ByteBuffer.allocate(1024), map); + byte[] bs = new byte[buffers[0].remaining()]; + buffers[0].get(bs); + System.out.println(new String(bs)); + main2(args); + main3(args); + } + + public static void main2(String[] args) throws Exception { + final JsonConvert convert = JsonConvert.root(); + SimpleChildEntity entry = SimpleChildEntity.create(); + String json = convert.convertTo(SimpleEntity.class, entry); + System.out.println("长度: " + json.length()); + JsonByteBufferWriter writer = convert.pollJsonWriter(() -> ByteBuffer.allocate(1)); + convert.convertTo(writer, SimpleEntity.class, entry); + ByteBuffer[] buffers = writer.toBuffers(); + int len = 0; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (ByteBuffer b : buffers) { + len += b.remaining(); + byte[] ts = new byte[b.remaining()]; + b.get(ts); + out.write(ts); + b.flip(); + } + System.out.println("长度: " + len); + System.out.println(json); + SimpleChildEntity entry2 = convert.convertFrom(SimpleChildEntity.class, buffers); + System.out.println(entry); + System.out.println(entry2); + } + + public static void main3(String[] args) throws Exception { + final JsonConvert convert = JsonConvert.root(); + SimpleChildEntity entry = SimpleChildEntity.create(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + convert.convertTo(out, SimpleEntity.class, entry); + String json = out.toString("UTF-8"); + System.out.println("长度: " + json.length()); + System.out.println(json); + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + SimpleChildEntity entry2 = convert.convertFrom(SimpleChildEntity.class, in); + System.out.println(entry); + System.out.println(entry2); + } +} diff --git a/test/org/redkale/test/convert/SimpleChildEntity.java b/test/org/redkale/test/convert/SimpleChildEntity.java new file mode 100644 index 000000000..e96010038 --- /dev/null +++ b/test/org/redkale/test/convert/SimpleChildEntity.java @@ -0,0 +1,60 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.net.*; +import org.redkale.convert.ConvertEntity; +import java.util.*; + +/** + * + * @author zhangjx + */ +@ConvertEntity("myname") +public class SimpleChildEntity extends SimpleEntity { + + private short st = -1234; + + private String extend; + + public static SimpleChildEntity create() { + SimpleChildEntity v = new SimpleChildEntity(); + v.setName("this is name\n \"test"); + v.setId(1000000001); + v.setAddrs(new int[]{22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999}); + v.setStrings(new String[]{"zzz", "yyy", "xxx"}); + List list = new ArrayList<>(); + list.add("aaaa"); + list.add("bbbb"); + list.add("cccc"); + v.setLists(list); + Map map = new HashMap<>(); + map.put("AAA", 111); + map.put("BBB", 222); + map.put("CCC", 333); + v.setMap(map); + v.setExtend("hahaha"); + v.setAddr(new InetSocketAddress("127.0.0.1", 6666)); + return v; + } + + public short getSt() { + return st; + } + + public void setSt(short st) { + this.st = st; + } + + public String getExtend() { + return extend; + } + + public void setExtend(String extend) { + this.extend = extend; + } + +} diff --git a/test/org/redkale/test/convert/SimpleEntity.java b/test/org/redkale/test/convert/SimpleEntity.java new file mode 100644 index 000000000..3af940b6d --- /dev/null +++ b/test/org/redkale/test/convert/SimpleEntity.java @@ -0,0 +1,137 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert; + +import java.net.*; +import org.redkale.util.Creator; +import java.util.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class SimpleEntity { + + private String name; + + private String desc = ""; + + private int id = (int) System.currentTimeMillis(); + + private int[] addrs; + + private List lists; + + private String[] strings; + + private Map map; + + private InetSocketAddress addr; + + public static SimpleEntity create() { + SimpleEntity v = new SimpleEntity(); + v.setName("this is name\n \"test"); + v.setId(1000000001); + v.setAddrs(new int[]{22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999}); + v.setStrings(new String[]{"zzz", "yyy", "xxx"}); + List list = new ArrayList<>(); + list.add("aaaa"); + list.add("bbbb"); + list.add("cccc"); + v.setLists(list); + Map map = new HashMap<>(); + map.put("AAA", 111); + map.put("BBB", 222); + map.put("CCC", 333); + v.setMap(map); + v.setAddr(new InetSocketAddress("127.0.0.1", 6666)); + return v; + } + + public static void main(String[] args) throws Exception { + System.out.println(JsonConvert.root().convertTo(create())); + Creator creator = Creator.create(SimpleEntity.class); //Creator.create(10, SimpleEntity.class); + SimpleEntity entry = creator.create(); + System.out.println(entry); + for (int i = 0; i < 10000000; i++) { + creator.create(); + } + System.gc(); + Thread.sleep(2000); + System.out.println(creator.create()); + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public InetSocketAddress getAddr() { + return addr; + } + + public void setAddr(InetSocketAddress addr) { + this.addr = addr; + } + + public int[] getAddrs() { + return addrs; + } + + public void setAddrs(int[] addrs) { + this.addrs = addrs; + } + + public List getLists() { + return lists; + } + + public void setLists(List lists) { + this.lists = lists; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String[] getStrings() { + return strings; + } + + public void setStrings(String[] strings) { + this.strings = strings; + } + +} diff --git a/test/org/redkale/test/convert/media/Image.java b/test/org/redkale/test/convert/media/Image.java new file mode 100644 index 000000000..14af488d6 --- /dev/null +++ b/test/org/redkale/test/convert/media/Image.java @@ -0,0 +1,117 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert.media; + +/** + * + * @author redkale + */ +public class Image implements java.io.Serializable { + + private static final long serialVersionUID = 1L; + + public enum Size { + SMALL, LARGE + } + + private String uri; + + private String title; // Can be null + + private int width; + + private int height; + + private Size size; + + public Image() { + } + + public Image(String uri, String title, int width, int height, Size size) { + this.height = height; + this.title = title; + this.uri = uri; + this.width = width; + this.size = size; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Image image = (Image) o; + + if (height != image.height) return false; + if (width != image.width) return false; + if (size != image.size) return false; + if (title != null ? !title.equals(image.title) : image.title != null) return false; + return !(uri != null ? !uri.equals(image.uri) : image.uri != null); + } + + @Override + public int hashCode() { + int result = uri != null ? uri.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + result = 31 * result + width; + result = 31 * result + height; + result = 31 * result + (size != null ? size.hashCode() : 0); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("[Image "); + sb.append("uri=").append((uri)); + sb.append(", title=").append((title)); + sb.append(", width=").append(width); + sb.append(", height=").append(height); + sb.append(", size=").append(size); + sb.append("]"); + return sb.toString(); + } + + public void setUri(String uri) { + this.uri = uri; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setWidth(int width) { + this.width = width; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setSize(Size size) { + this.size = size; + } + + public String getUri() { + return uri; + } + + public String getTitle() { + return title; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public Size getSize() { + return size; + } +} diff --git a/test/org/redkale/test/convert/media/Media.java b/test/org/redkale/test/convert/media/Media.java new file mode 100644 index 000000000..699d02ccf --- /dev/null +++ b/test/org/redkale/test/convert/media/Media.java @@ -0,0 +1,203 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert.media; + +import java.util.*; + +/** + * + * @author redkale + */ +public class Media implements java.io.Serializable { + + public enum Player { + JAVA, FLASH; + + } + + private String uri; + + private String title; // Can be unset. + + private int width; + + private int height; + + private String format; + + private long duration; + + private long size; + + private int bitrate; // Can be unset. + + private List persons; + + private Player player; + + private String copyright; // Can be unset. + + public Media() { + } + + public Media(String uri, String title, int width, int height, String format, long duration, long size, + int bitrate, boolean hasBitrate, List persons, Player player, String copyright) { + this.uri = uri; + this.title = title; + this.width = width; + this.height = height; + this.format = format; + this.duration = duration; + this.size = size; + this.bitrate = bitrate; + + this.persons = persons; + this.player = player; + this.copyright = copyright; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Media media = (Media) o; + if (bitrate != media.bitrate) return false; + if (duration != media.duration) return false; + if (height != media.height) return false; + if (size != media.size) return false; + if (width != media.width) return false; + if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false; + if (format != null ? !format.equals(media.format) : media.format != null) return false; + if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false; + if (player != media.player) return false; + if (title != null ? !title.equals(media.title) : media.title != null) return false; + if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false; + return true; + } + + @Override + public int hashCode() { + int result = uri != null ? uri.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + result = 31 * result + width; + result = 31 * result + height; + result = 31 * result + (format != null ? format.hashCode() : 0); + result = 31 * result + (int) (duration ^ (duration >>> 32)); + result = 31 * result + (int) (size ^ (size >>> 32)); + result = 31 * result + bitrate; + result = 31 * result + (persons != null ? persons.hashCode() : 0); + result = 31 * result + (player != null ? player.hashCode() : 0); + result = 31 * result + (copyright != null ? copyright.hashCode() : 0); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("[Media "); + sb.append("uri=").append((uri)); + sb.append(", title=").append((title)); + sb.append(", width=").append(width); + sb.append(", height=").append(height); + sb.append(", format=").append((format)); + sb.append(", duration=").append(duration); + sb.append(", size=").append(size); + sb.append(", bitrate=").append(String.valueOf(bitrate)); + sb.append(", persons=").append((persons)); + sb.append(", player=").append(player); + sb.append(", copyright=").append((copyright)); + sb.append("]"); + return sb.toString(); + } + + public void setUri(String uri) { + this.uri = uri; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setWidth(int width) { + this.width = width; + } + + public void setHeight(int height) { + this.height = height; + } + + public void setFormat(String format) { + this.format = format; + } + + public void setDuration(long duration) { + this.duration = duration; + } + + public void setSize(long size) { + this.size = size; + } + + public void setBitrate(int bitrate) { + this.bitrate = bitrate; + } + + public void setPersons(List persons) { + this.persons = persons; + } + + public void setPlayer(Player player) { + this.player = player; + } + + public void setCopyright(String copyright) { + this.copyright = copyright; + } + + public String getUri() { + return uri; + } + + public String getTitle() { + return title; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public String getFormat() { + return format; + } + + public long getDuration() { + return duration; + } + + public long getSize() { + return size; + } + + public int getBitrate() { + return bitrate; + } + + public List getPersons() { + return persons; + } + + public Player getPlayer() { + return player; + } + + public String getCopyright() { + return copyright; + } +} diff --git a/test/org/redkale/test/convert/media/MediaContent.java b/test/org/redkale/test/convert/media/MediaContent.java new file mode 100644 index 000000000..50efeaddf --- /dev/null +++ b/test/org/redkale/test/convert/media/MediaContent.java @@ -0,0 +1,109 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.convert.media; + +import java.util.*; +import org.redkale.convert.json.*; +import org.redkale.test.convert.*; + +/** + * + * @author redkale + */ +public class MediaContent implements java.io.Serializable { + + private Media media; + + private List images; + + public MediaContent() { + } + + public MediaContent(Media media, List images) { + this.media = media; + this.images = images; + } + + public static void main(String[] args) throws Exception { + final MediaContent entry = MediaContent.createDefault(); + ConvertRecord.run(MediaContent.class, entry); + } + + public static MediaContent createDefault() { + String str = "{" + + " media : {" + + " uri : \"http://javaone.com/keynote.mpg\" ," + + " title : \"Javaone Keynote\" ," + + " width : -640 ," + + " height : -480 ," + + " format : \"video/mpg4\"," + + " duration : -18000000 ," + + " size : -58982400 ," + + " bitrate : -262144 ," + + " persons : [\"Bill Gates\", \"Steve Jobs\"] ," + + " player : JAVA , " + + " copyright : None" + + " }, images : [" + + " {" + + " uri : \"http://javaone.com/keynote_large.jpg\"," + + " title : \"Javaone Keynote\"," + + " width : -1024," + + " height : -768," + + " size : LARGE" + + " }, {" + + " uri : \"http://javaone.com/keynote_small.jpg\", " + + " title : \"Javaone Keynote\" , " + + " width : -320 , " + + " height : -240 , " + + " size : SMALL" + + " }" + + " ]" + + "}"; + return JsonFactory.root().getConvert().convertFrom(MediaContent.class, str); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MediaContent that = (MediaContent) o; + if (images != null ? !images.equals(that.images) : that.images != null) return false; + return !(media != null ? !media.equals(that.media) : that.media != null); + } + + @Override + public int hashCode() { + int result = media != null ? media.hashCode() : 0; + result = 31 * result + (images != null ? images.hashCode() : 0); + return result; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("[MediaContent: "); + sb.append("media=").append(media); + sb.append(", images=").append(images); + sb.append("]"); + return sb.toString(); + } + + public void setMedia(Media media) { + this.media = media; + } + + public void setImages(List images) { + this.images = images; + } + + public Media getMedia() { + return media; + } + + public List getImages() { + return images; + } +} diff --git a/test/org/redkale/test/http/HttpRequestDesc.java b/test/org/redkale/test/http/HttpRequestDesc.java new file mode 100644 index 000000000..dc8597577 --- /dev/null +++ b/test/org/redkale/test/http/HttpRequestDesc.java @@ -0,0 +1,189 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.http; + +import java.io.*; +import java.net.*; +import java.nio.charset.*; +import java.util.*; +import org.redkale.convert.json.*; +import org.redkale.net.http.*; + +/** + * + * @author zhangjx + */ +public interface HttpRequestDesc { + + //获取请求方法 GET、POST等 + public String getMethod(); + + //获取协议名 http、https、ws、wss等 + public String getProtocol(); + + //获取Host的Header值 + public String getHost(); + + //获取请求内容的长度, 为-1表示内容长度不确定 + public long getContentLength(); + + //获取Content-Type的header值 + public String getContentType(); + + //获取Connection的Header值 + public String getConnection(); + + //获取客户端地址IP + public SocketAddress getRemoteAddress(); + + //获取客户端地址IP, 与getRemoteAddres() 的区别在于:本方法优先取header中指定为RemoteAddress名的值,没有则返回getRemoteAddres()的getHostAddress()。 + //本方法适用于服务前端有如nginx的代理服务器进行中转,通过getRemoteAddres()是获取不到客户端的真实IP。 + public String getRemoteAddr(); + + //获取请求内容指定的编码字符串 + public String getBody(Charset charset); + + //获取请求内容的UTF-8编码字符串 + public String getBodyUTF8(); + + //获取文件上传对象 + public MultiContext getMultiContext(); + + //获取文件上传信息列表 等价于 getMultiContext().parts(); + public Iterable multiParts() throws IOException; + + //获取sessionid + public String getSessionid(boolean autoCreate); + + //更新sessionid + public String changeSessionid(); + + //使sessionid失效 + public void invalidateSession(); + + //获取所有Cookie对象 + public java.net.HttpCookie[] getCookies(); + + //获取Cookie值, 没有返回默认值 + public String getCookie(String name, String defaultValue); + + //获取Cookie值 + public String getCookie(String name); + + //获取请求的URL + public String getRequestURI(); + + //截取getRequestURI最后的一个/后面的部分 + public String getRequstURILastPath(); + + //从prefix之后截取getRequestURI再对"/"进行分隔 + public String[] getRequstURIPaths(String prefix); + + //获取请求URL分段中含prefix段的long值 + // 例如请求URL /pipes/record/query/time:1453104341363/id:40 + // 获取time参数: long time = request.getRequstURIPath("time:", 0L); + public long getRequstURIPath(String prefix, long defaultValue); + + //获取请求URL分段中含prefix段的int值 + // 例如请求URL /pipes/record/query/page:2/size:50 + // 获取page参数: int page = request.getRequstURIPath("page:", 1); + // 获取size参数: int size = request.getRequstURIPath("size:", 20); + public int getRequstURIPath(String prefix, int defaultValue); + + //获取请求URL分段中含prefix段的值 + //例如请求URL /pipes/record/query/name:hello + //获取name参数: String name = request.getRequstURIPath("name:", "none"); + public String getRequstURIPath(String prefix, String defaultValue); + + // 获取请求URL分段中含prefix段的short值 + // 例如请求URL /pipes/record/query/type:10 + // 获取type参数: short type = request.getRequstURIPath("type:", (short)0); + public short getRequstURIPath(String prefix, short defaultValue); + + //获取所有的header名 + public String[] getHeaderNames(); + + // 获取指定的header值 + public String getHeader(String name); + + //获取指定的header值, 没有返回默认值 + public String getHeader(String name, String defaultValue); + + //获取指定的header的json值 + public T getJsonHeader(JsonConvert convert, Class clazz, String name); + + //获取指定的header的json值 + public T getJsonHeader(Class clazz, String name); + + //获取指定的header的boolean值, 没有返回默认boolean值 + public boolean getBooleanHeader(String name, boolean defaultValue); + + // 获取指定的header的short值, 没有返回默认short值 + public short getShortHeader(String name, short defaultValue); + + //获取指定的header的int值, 没有返回默认int值 + public int getIntHeader(String name, int defaultValue); + + // 获取指定的header的float值, 没有返回默认float值 + public float getFloatHeader(String name, float defaultValue); + + // 获取指定的header的long值, 没有返回默认long值 + public long getLongHeader(String name, long defaultValue); + + //获取指定的header的double值, 没有返回默认double值 + public double getDoubleHeader(String name, double defaultValue); + + //获取所有参数名 + public String[] getParameterNames(); + + //获取指定的参数值 + public String getParameter(String name); + + //获取指定的参数值, 没有返回默认值 + public String getParameter(String name, String defaultValue); + + //获取指定的参数json值 + public T getJsonParameter(JsonConvert convert, Class clazz, String name); + + //获取指定的参数json值 + public T getJsonParameter(Class clazz, String name); + + //获取指定的参数boolean值, 没有返回默认boolean值 + public boolean getBooleanParameter(String name, boolean defaultValue); + + //获取指定的参数short值, 没有返回默认short值 + public short getShortParameter(String name, short defaultValue); + + //获取指定的参数int值, 没有返回默认int值 + public int getIntParameter(String name, int defaultValue); + + //获取指定的参数float值, 没有返回默认float值 + public float getFloatParameter(String name, float defaultValue); + + //获取指定的参数long值, 没有返回默认long值 + public long getLongParameter(String name, long defaultValue); + + //获取指定的参数double值, 没有返回默认double值 + public double getDoubleParameter(String name, double defaultValue); + + //获取HTTP上下文对象 + public HttpContext getContext(); + + //获取所有属性值, servlet执行完后会被清空 + public Map getAttributes(); + + //获取指定属性值 + public T getAttribute(String name); + + //删除指定属性 + public void removeAttribute(String name); + + //设置属性值 + public void setAttribute(String name, Object value); + + //获取request创建时间 + public long getCreatetime(); +} diff --git a/test/org/redkale/test/http/HttpResponseDesc.java b/test/org/redkale/test/http/HttpResponseDesc.java new file mode 100644 index 000000000..eacaf2122 --- /dev/null +++ b/test/org/redkale/test/http/HttpResponseDesc.java @@ -0,0 +1,105 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.http; + +import java.io.*; +import java.lang.reflect.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public interface HttpResponseDesc { + + //设置状态码 + public void setStatus(int status); + + //获取状态码 + public int getStatus(); + + //获取 ContentType + public String getContentType(); + + //设置 ContentType + public void setContentType(String contentType); + + //获取内容长度 + public long getContentLength(); + + //设置内容长度 + public void setContentLength(long contentLength); + + //设置Header值 + public void setHeader(String name, Object value); + + //添加Header值 + public void addHeader(String name, Object value); + + //跳过header的输出 + //通常应用场景是,调用者的输出内容里已经包含了HTTP的响应头信息,因此需要调用此方法避免重复输出HTTP响应头信息。 + public void skipHeader(); + + //增加Cookie值 + public void addCookie(HttpCookie... cookies); + + //异步输出指定内容 + public void sendBody(ByteBuffer buffer, A attachment, CompletionHandler handler); + + //关闭HTTP连接,如果是keep-alive则不强制关闭 + public void finish(); + + //强制关闭HTTP连接 + public void finish(boolean kill); + + //将对象以JSON格式输出 + public void finishJson(Object obj); + + //将对象以JSON格式输出 + public void finishJson(JsonConvert convert, Object obj); + + //将对象以JSON格式输出 + public void finishJson(Type type, Object obj); + + //将对象以JSON格式输出 + public void finishJson(final JsonConvert convert, final Type type, final Object obj); + + //将对象以JSON格式输出 + public void finishJson(final Object... objs); + + //将指定字符串以响应结果输出 + public void finish(String obj); + + //以指定响应码附带内容输出, message 可以为null + public void finish(int status, String message); + + //以304状态码输出 + public void finish304(); + + //以404状态码输出 + public void finish404(); + + //将指定ByteBuffer按响应结果输出 + public void finish(ByteBuffer buffer); + + //将指定ByteBuffer按响应结果输出 + //kill 输出后是否强制关闭连接 + public void finish(boolean kill, ByteBuffer buffer); + + //将指定ByteBuffer数组按响应结果输出 + public void finish(ByteBuffer... buffers); + + //将指定ByteBuffer数组按响应结果输出 + //kill 输出后是否强制关闭连接 + public void finish(boolean kill, ByteBuffer... buffers); + + //将指定文件按响应结果输出 + public void finish(File file) throws IOException; + +} diff --git a/test/org/redkale/test/http/WebSocketDesc.java b/test/org/redkale/test/http/WebSocketDesc.java new file mode 100644 index 000000000..174cb3868 --- /dev/null +++ b/test/org/redkale/test/http/WebSocketDesc.java @@ -0,0 +1,154 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.http; + +import java.io.*; +import java.net.*; +import java.util.*; +import org.redkale.net.*; +import org.redkale.net.http.*; + +/** + * + * @author zhangjx + */ +public interface WebSocketDesc { + + //发送消息体, 包含二进制/文本 返回结果0表示成功,非0表示错误码 + public int send(WebSocketPacket packet); + + //发送单一的文本消息 返回结果0表示成功,非0表示错误码 + public int send(String text); + + //发送文本消息 返回结果0表示成功,非0表示错误码 + public int send(String text, boolean last); + + //发送单一的二进制消息 返回结果0表示成功,非0表示错误码 + public int send(byte[] data); + + //发送单一的二进制消息 返回结果0表示成功,非0表示错误码 + public int send(byte[] data, boolean last); + + //发送消息, 消息类型是String或byte[] 返回结果0表示成功,非0表示错误码 + public int send(Serializable message, boolean last); + + //给指定groupid的WebSocketGroup下所有WebSocket节点发送文本消息 + public int sendEachMessage(Serializable groupid, String text); + + //给指定groupid的WebSocketGroup下所有WebSocket节点发送文本消息 + public int sendEachMessage(Serializable groupid, String text, boolean last); + + //给指定groupid的WebSocketGroup下所有WebSocket节点发送二进制消息 + public int sendEachMessage(Serializable groupid, byte[] data); + + //给指定groupid的WebSocketGroup下所有WebSocket节点发送二进制消息 + public int sendEachMessage(Serializable groupid, byte[] data, boolean last); + + //给指定groupid的WebSocketGroup下最近接入的WebSocket节点发送文本消息 + public int sendRecentMessage(Serializable groupid, String text); + + //给指定groupid的WebSocketGroup下最近接入的WebSocket节点发送文本消息 + public int sendRecentMessage(Serializable groupid, String text, boolean last); + + //给指定groupid的WebSocketGroup下最近接入的WebSocket节点发送二进制消息 + public int sendRecentMessage(Serializable groupid, byte[] data); + + //给指定groupid的WebSocketGroup下最近接入的WebSocket节点发送二进制消息 + public int sendRecentMessage(Serializable groupid, byte[] data, boolean last); + + //发送PING消息 返回结果0表示成功,非0表示错误码 + public int sendPing(); + + //发送PING消息,附带其他信息 返回结果0表示成功,非0表示错误码 + public int sendPing(byte[] data); + + //发送PONG消息,附带其他信息 返回结果0表示成功,非0表示错误码 + public int sendPong(byte[] data); + + //获取当前WebSocket下的属性 + public T getAttribute(String name); + + //移出当前WebSocket下的属性 + public T removeAttribute(String name); + + //给当前WebSocket下的增加属性 + public void setAttribute(String name, Object value); + + //获取当前WebSocket所属的groupid + public Serializable getGroupid(); + + //获取当前WebSocket的会话ID, 不会为null + public Serializable getSessionid(); + + //获取客户端直接地址, 当WebSocket连接是由代理服务器转发的,则该值固定为代理服务器的IP地址 + public SocketAddress getRemoteAddress(); + + //获取客户端真实地址 同 HttpRequest.getRemoteAddr() + public String getRemoteAddr(); + + //获取WebSocket创建时间 + public long getCreatetime(); + + //显式地关闭WebSocket + public void close(); + + + //获取当前WebSocket所属的WebSocketGroup, 不会为null + /* protected */ WebSocketGroup getWebSocketGroup(); + + + //获取指定groupid的WebSocketGroup, 没有返回null + /* protected */ WebSocketGroup getWebSocketGroup(Serializable groupid); + + + //获取当前进程节点所有在线的WebSocketGroup + /* protected */ Collection getWebSocketGroups(); + + + //获取在线用户的节点地址列表 + /* protected */ Collection getOnlineNodes(Serializable groupid); + + + //获取在线用户的详细连接信息 + /* protected */ Map> getOnlineRemoteAddress(Serializable groupid); + + //返回sessionid, null表示连接不合法或异常,默认实现是request.getSessionid(false),通常需要重写该方法 + public Serializable onOpen(final HttpRequest request); + + + //创建groupid, null表示异常, 必须实现该方法, 通常为用户ID为groupid + /* protected abstract */ Serializable createGroupid(); + + //标记为@WebSocketBinary才需要重写此方法 + default void onRead(AsyncConnection channel) { + } + + default void onConnected() { + } + + //接收文本消息响应事件,可能会接收到文本消息需要重写该方法 + default void onMessage(String text) { + } + + default void onPing(byte[] bytes) { + } + + default void onPong(byte[] bytes) { + } + + //接收二进制消息响应事件,可能会接收到二进制消息需要重写该方法 + default void onMessage(byte[] bytes) { + } + + default void onFragment(String text, boolean last) { + } + + default void onFragment(byte[] bytes, boolean last) { + } + + default void onClose(int code, String reason) { + } +} diff --git a/test/org/redkale/test/net/UploadTestServlet.java b/test/org/redkale/test/net/UploadTestServlet.java new file mode 100644 index 000000000..dfc918877 --- /dev/null +++ b/test/org/redkale/test/net/UploadTestServlet.java @@ -0,0 +1,50 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.net; + +import org.redkale.net.http.HttpServlet; +import org.redkale.net.http.MultiPart; +import org.redkale.net.http.HttpRequest; +import org.redkale.net.http.HttpResponse; +import java.io.*; + +/** + * + * @author zhangjx + */ +//@WebServlet({"/uploadtest/form", "/uploadtest/send"}) +public class UploadTestServlet extends HttpServlet { + + @Override + public void execute(HttpRequest request, HttpResponse response) throws IOException { + if (request.getRequestURI().contains("/uploadtest/send")) { + send(request, response); + } else { + form(request, response); + } + } + + public void form(HttpRequest req, HttpResponse resp) throws IOException { + resp.setContentType("text/html"); + resp.finish( + "" + + "
" + + "描述:         文件1:

" + + "描述:         文件2:

" + + "描述:         文件3:

" + + "描述:         

" + + "              
" + + ""); + } + + public void send(HttpRequest req, HttpResponse resp) throws IOException { + for (MultiPart entry : req.multiParts()) { + entry.skip(); + System.out.println(entry); + } + System.exit(0); + } +} diff --git a/test/org/redkale/test/service/Person.java b/test/org/redkale/test/service/Person.java new file mode 100644 index 000000000..b0ed01586 --- /dev/null +++ b/test/org/redkale/test/service/Person.java @@ -0,0 +1,32 @@ +package org.redkale.test.service; + +import java.io.Serializable; + +public class Person implements Serializable { + + private byte[] b = new byte[1024 * 2]; + + private String name; + + @Override + public String toString() { + return "{name=" + name + ", b =" + (b == null ? "null" : "[length=" + b.length + "]") + "}"; + } + + public byte[] getB() { + return b; + } + + public void setB(byte[] b) { + this.b = b; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/test/org/redkale/test/service/TestBean.java b/test/org/redkale/test/service/TestBean.java new file mode 100644 index 000000000..4f7729d6e --- /dev/null +++ b/test/org/redkale/test/service/TestBean.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.service; + +/** + * + * @author zhangjx + */ +public class TestBean { + +} diff --git a/test/org/redkale/test/sncp/SncpTest.java b/test/org/redkale/test/sncp/SncpTest.java new file mode 100644 index 000000000..b029a2bef --- /dev/null +++ b/test/org/redkale/test/sncp/SncpTest.java @@ -0,0 +1,210 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.sncp; + +import org.redkale.net.sncp.Sncp; +import org.redkale.convert.bson.BsonFactory; +import org.redkale.net.Transport; +import org.redkale.service.Service; +import org.redkale.net.sncp.SncpServer; +import org.redkale.convert.bson.BsonConvert; +import org.redkale.util.Utility; +import org.redkale.net.sncp.ServiceWrapper; +import org.redkale.util.AnyValue; +import org.redkale.watch.WatchFactory; +import org.redkale.util.ResourceFactory; +import java.io.*; +import java.net.*; +import java.nio.*; +import java.nio.channels.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.*; +import java.util.logging.*; +import org.redkale.util.*; + +/** + * + * @author zhangjx + */ +public class SncpTest { + + private static final String serviceName = ""; + + private static final String myhost = Utility.localInetAddress().getHostAddress(); + + private static final int port = 4040; + + private static final int port2 = 4240; + + public static void main(String[] args) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + final PrintStream ps = new PrintStream(out); + ps.println("handlers = java.util.logging.ConsoleHandler"); + ps.println(".handlers = java.util.logging.ConsoleHandler"); + ps.println(".level = FINEST"); + ps.println("java.util.logging.ConsoleHandler.level = FINEST"); + LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray())); + ResourceFactory.root().register("", BsonConvert.class, BsonFactory.root().getConvert()); + if (System.getProperty("client") == null) { + runServer(); + if (port2 > 0) runServer2(); + } + if (System.getProperty("server") == null) { + runClient(); + } + if (System.getProperty("server") != null) { + System.in.read(); + } + } + + public static AsynchronousChannelGroup newChannelGroup() throws IOException { + final AtomicInteger counter = new AtomicInteger(); + ExecutorService transportExec = Executors.newFixedThreadPool(16, (Runnable r) -> { + Thread t = new Thread(r); + t.setDaemon(true); + t.setName("Transport-Thread-" + counter.incrementAndGet()); + return t; + }); + return AsynchronousChannelGroup.withCachedThreadPool(transportExec, 1); + } + + public static ObjectPool newBufferPool() { + return new ObjectPool<>(new AtomicLong(), new AtomicLong(), 16, + (Object... params) -> ByteBuffer.allocateDirect(8192), null, (e) -> { + if (e == null || e.isReadOnly() || e.capacity() != 8192) return false; + e.clear(); + return true; + }); + } + + private static void runClient() throws Exception { + InetSocketAddress addr = new InetSocketAddress(myhost, port); + Set set = new LinkedHashSet<>(); + set.add(addr); + if (port2 > 0) set.add(new InetSocketAddress(myhost, port2)); + //String name, WatchFactory, ObjectPool, AsynchronousChannelGroup, InetSocketAddress clientAddress, Collection + final Transport transport = new Transport("", WatchFactory.root(), newBufferPool(), newChannelGroup(), null, set); + final SncpTestService service = Sncp.createRemoteService(serviceName, null, SncpTestService.class, null, transport); + ResourceFactory.root().inject(service); + +// SncpTestBean bean = new SncpTestBean(); +// StringBuilder sb = new StringBuilder(); +// for (int i = 0; i < 2000; i++) { +// sb.append("_").append(i).append("_0123456789"); +// } +// bean.setContent(sb.toString()); +// bean.setContent("hello sncp"); + SncpTestBean callbean = new SncpTestBean(); + callbean.setId(1); + callbean.setContent("数据X"); + + service.insert(callbean); + System.out.println("bean.id应该会被修改: " + callbean); + System.out.println("---------------------------------------------------"); + final int count = 10; + final CountDownLatch cld = new CountDownLatch(count); + final AtomicInteger ai = new AtomicInteger(); + for (int i = 0; i < count; i++) { + final int k = i + 1; + new Thread() { + @Override + public void run() { + try { + Thread.sleep(k); + SncpTestBean bean = new SncpTestBean(); + bean.setId(k); + bean.setContent("数据: " + (k < 10 ? "0" : "") + k); + StringBuilder sb = new StringBuilder(); + sb.append(k).append("------"); + for (int i = 0; i < 1200; i++) { + sb.append("_").append(i).append("_").append(k).append("_0123456789"); + } + bean.setContent(sb.toString()); + + service.queryResult(bean); + //service.updateBean(bean); + } catch (Exception e) { + e.printStackTrace(); + } finally { + long a = ai.incrementAndGet(); + System.out.println("运行了 " + (a == 100 ? "--------------------------------------------------" : "") + a); + cld.countDown(); + } + } + }.start(); + } + cld.await(); + System.out.println("---全部运行完毕---"); + System.exit(0); + } + + private static void runServer() throws Exception { + InetSocketAddress addr = new InetSocketAddress(myhost, port); + final CountDownLatch cdl = new CountDownLatch(1); + new Thread() { + { + setName("Thread-Server-01"); + } + + @Override + public void run() { + try { + SncpServer server = new SncpServer(); + Set set = new LinkedHashSet<>(); + if (port2 > 0) set.add(new InetSocketAddress(myhost, port2)); + //String name, WatchFactory, ObjectPool, AsynchronousChannelGroup, InetSocketAddress clientAddress, Collection + final Transport transport = new Transport("", WatchFactory.root(), newBufferPool(), newChannelGroup(), null, set); + SncpTestService service = Sncp.createLocalService("", null, ResourceFactory.root(), SncpTestService.class, addr, transport, null); + ResourceFactory.root().inject(service); + server.addService(new ServiceWrapper(SncpTestService.class, service, "", "", new HashSet<>(), null)); + System.out.println(service); + AnyValue.DefaultAnyValue conf = new AnyValue.DefaultAnyValue(); + conf.addValue("host", "0.0.0.0"); + conf.addValue("port", "" + port); + server.init(conf); + server.start(); + cdl.countDown(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + cdl.await(); + } + + private static void runServer2() throws Exception { + InetSocketAddress addr = new InetSocketAddress(myhost, port2); + final CountDownLatch cdl = new CountDownLatch(1); + new Thread() { + { + setName("Thread-Server-02"); + } + + @Override + public void run() { + try { + SncpServer server = new SncpServer(); + Set set = new LinkedHashSet<>(); + set.add(new InetSocketAddress(myhost, port)); + //String name, WatchFactory, ObjectPool, AsynchronousChannelGroup, InetSocketAddress clientAddress, Collection + final Transport transport = new Transport("", WatchFactory.root(), newBufferPool(), newChannelGroup(), null, set); + Service service = Sncp.createLocalService("", null, ResourceFactory.root(), SncpTestService.class, addr, transport, null); + server.addService(new ServiceWrapper(SncpTestService.class, service, "", "", new HashSet<>(), null)); + AnyValue.DefaultAnyValue conf = new AnyValue.DefaultAnyValue(); + conf.addValue("host", "0.0.0.0"); + conf.addValue("port", "" + port2); + server.init(conf); + server.start(); + cdl.countDown(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + cdl.await(); + } +} diff --git a/test/org/redkale/test/sncp/SncpTestBean.java b/test/org/redkale/test/sncp/SncpTestBean.java new file mode 100644 index 000000000..77684df5e --- /dev/null +++ b/test/org/redkale/test/sncp/SncpTestBean.java @@ -0,0 +1,54 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.sncp; + +import org.redkale.convert.bson.BsonFactory; +import org.redkale.util.Utility; +import org.redkale.source.FilterBean; +import javax.persistence.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class SncpTestBean implements FilterBean { + + @Id + private long id; + + private String content; + + public static void main(String[] args) throws Exception { + SncpTestBean bean = JsonConvert.root().convertFrom(SncpTestBean.class, "{\"content\":\"数据: 01\",\"id\":1}"); + System.out.println(bean); + byte[] bs = BsonFactory.root().getConvert().convertTo(bean); + Utility.println("---------", bs); + System.out.println(BsonFactory.root().getConvert().convertFrom(SncpTestBean.class, bs).toString()); + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + +} diff --git a/test/org/redkale/test/sncp/SncpTestIService.java b/test/org/redkale/test/sncp/SncpTestIService.java new file mode 100644 index 000000000..0d9c554e1 --- /dev/null +++ b/test/org/redkale/test/sncp/SncpTestIService.java @@ -0,0 +1,20 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.sncp; + +import org.redkale.service.*; +import org.redkale.source.*; + +/** + * + * @author zhangjx + */ +public interface SncpTestIService extends Service { + + public void insert(@DynCall(DataCallArrayAttribute.class) SncpTestBean... beans); + + public String updateBean(@DynCall(SncpTestService.CallAttribute.class) SncpTestBean bean); +} diff --git a/test/org/redkale/test/sncp/SncpTestService.java b/test/org/redkale/test/sncp/SncpTestService.java new file mode 100644 index 000000000..260118d92 --- /dev/null +++ b/test/org/redkale/test/sncp/SncpTestService.java @@ -0,0 +1,101 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.sncp; + +import java.lang.reflect.*; +import java.net.*; +import org.redkale.net.sncp.*; +import org.redkale.service.*; +import org.redkale.util.Attribute; +import org.redkale.source.DataCallArrayAttribute; +import org.redkale.util.*; + +/** + * + * @author zhangjx + */ +@ResourceType({SncpTestIService.class}) +public class SncpTestService implements SncpTestIService { + + public static class CallAttribute implements Attribute { + + @Override + public Class type() { + return long.class; + } + + @Override + public Class declaringClass() { + return SncpTestBean.class; + } + + @Override + public String field() { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public Long get(SncpTestBean obj) { + System.out.println("返回ID: " + obj.getId()); + return obj.getId(); + } + + @Override + public void set(SncpTestBean obj, Long value) { + System.out.println("设置ID: " + value); + obj.setId(value); + } + + } + + public void insert(@DynCall(DataCallArrayAttribute.class) SncpTestBean... beans) { + for (SncpTestBean bean : beans) { + bean.setId(System.currentTimeMillis()); + } + } + + public String queryResult(SncpTestBean bean) { + System.out.println(Thread.currentThread().getName() + " 运行了queryResult方法"); + return "result: " + bean; + } + + @MultiRun + public String updateBean(@DynCall(CallAttribute.class) SncpTestBean bean) { + bean.setId(System.currentTimeMillis()); + System.out.println(Thread.currentThread().getName() + " 运行了updateBean方法"); + return "result: " + bean; + } + + public static void main(String[] args) throws Exception { + Service service = Sncp.createLocalService("", null, ResourceFactory.root(), SncpTestService.class, new InetSocketAddress("127.0.0.1", 7070), null, null); + for (Method method : service.getClass().getDeclaredMethods()) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + for (Method method : SncpClient.parseMethod(service.getClass())) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + service = Sncp.createRemoteService("", null, SncpTestService.class, new InetSocketAddress("127.0.0.1", 7070), null); + for (Method method : service.getClass().getDeclaredMethods()) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + for (Method method : SncpClient.parseMethod(service.getClass())) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + service = Sncp.createRemoteService("", null, SncpTestIService.class, new InetSocketAddress("127.0.0.1", 7070), null); + for (Method method : service.getClass().getDeclaredMethods()) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + for (Method method : SncpClient.parseMethod(service.getClass())) { + System.out.println(method); + } + System.out.println("-----------------------------------"); + } +} diff --git a/test/org/redkale/test/source/CacheTestBean.java b/test/org/redkale/test/source/CacheTestBean.java new file mode 100644 index 000000000..fa636a7de --- /dev/null +++ b/test/org/redkale/test/source/CacheTestBean.java @@ -0,0 +1,81 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.source; + +import org.redkale.source.EntityInfo; +import org.redkale.source.EntityCache; +import org.redkale.util.Attribute; +import java.util.*; +import javax.persistence.*; +import org.redkale.source.*; + +/** + * + * @author zhangjx + */ +public class CacheTestBean { + + @Id + private long pkgid; + + private String name; + + private long price; + + public static void main(String[] args) throws Exception { + final List list = new ArrayList<>(); + list.add(new CacheTestBean(1, "a", 12)); + list.add(new CacheTestBean(1, "a", 18)); + list.add(new CacheTestBean(2, "b", 20)); + list.add(new CacheTestBean(2, "bb", 60)); + Attribute idattr = Attribute.create(CacheTestBean.class, "pkgid"); + Attribute nameattr = Attribute.create(CacheTestBean.class, "name"); + Attribute priceattr = Attribute.create(CacheTestBean.class, "price"); + EntityCache cache = new EntityCache(EntityInfo.load(CacheTestBean.class, 0, true,new Properties(), null)); + cache.fullLoad(list); + + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.COUNT, "name", null)); + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.DISTINCTCOUNT, "name", null)); + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.AVG, "price", null)); + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.SUM, "price", null)); + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.MAX, "price", null)); + System.out.println(cache.queryColumnMap("pkgid", FilterFunc.MIN, "price", null)); + } + + public CacheTestBean() { + } + + public CacheTestBean(long pkgid, String name, long price) { + this.pkgid = pkgid; + this.name = name; + this.price = price; + } + + public long getPkgid() { + return pkgid; + } + + public void setPkgid(long pkgid) { + this.pkgid = pkgid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getPrice() { + return price; + } + + public void setPrice(long price) { + this.price = price; + } + +} diff --git a/test/org/redkale/test/source/JDBCTest.java b/test/org/redkale/test/source/JDBCTest.java new file mode 100644 index 000000000..a8d782334 --- /dev/null +++ b/test/org/redkale/test/source/JDBCTest.java @@ -0,0 +1,42 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.source; + +import org.redkale.source.DataDefaultSource; +import org.redkale.source.DataSource; + +/** + * + * @author zhangjx + */ +public class JDBCTest { + + public static void main(String[] args) throws Exception { + DataSource source = new DataDefaultSource(); //耗时:37415 + int count = 1000; + LoginTestRecord last = null; + long s = System.currentTimeMillis(); + int c = 0; + try { + for (int i = 0; i < count; i++) { + LoginTestRecord record = new LoginTestRecord(); + record.setSessionid(Long.toHexString(System.nanoTime())); + record.setLoginagent("win7"); + record.setLogintime(System.currentTimeMillis()); + record.setLoginip("127.0.0.1"); + record.setUserid(i); + source.insert(record); + last = record; + c = i; + } + } catch (Exception e) { + System.out.println("异常了: " + c); + e.printStackTrace(); + } + long e = System.currentTimeMillis() - s; + System.out.println("耗时:" + e); + } +} diff --git a/test/org/redkale/test/source/LoginTestBean.java b/test/org/redkale/test/source/LoginTestBean.java new file mode 100644 index 000000000..1310b5ec9 --- /dev/null +++ b/test/org/redkale/test/source/LoginTestBean.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.source; + +import org.redkale.source.FilterBean; + +/** + * + * @author zhangjx + */ +public class LoginTestBean implements FilterBean { + + private String sessionid; + + public String getSessionid() { + return sessionid; + } + + public void setSessionid(String sessionid) { + this.sessionid = sessionid; + } + +} diff --git a/test/org/redkale/test/source/LoginTestRecord.java b/test/org/redkale/test/source/LoginTestRecord.java new file mode 100644 index 000000000..6e99d6967 --- /dev/null +++ b/test/org/redkale/test/source/LoginTestRecord.java @@ -0,0 +1,95 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.source; + +import javax.persistence.*; +import org.redkale.convert.json.*; + +/** + * CREATE TABLE `LoginTestRecord` ( + * `sessionid` VARCHAR(64) NOT NULL COMMENT '登陆会话ID', + * `userid` INT(11) NOT NULL COMMENT '登陆用户ID', + * `loginagent` VARCHAR(128) NOT NULL COMMENT '登陆端信息', + * `loginip` VARCHAR(255) NOT NULL COMMENT '登陆IP', + * `logintime` BIGINT(20) NOT NULL COMMENT '登陆时间', + * `logouttime` BIGINT(20) NOT NULL COMMENT '注销时间', + * PRIMARY KEY (`sessionid`) + * ) ENGINE=INNODB DEFAULT CHARSET=utf8; + * + * @author zhangjx + */ +@Entity +public class LoginTestRecord { + + @Id + @GeneratedValue + //@SequenceGenerator(name = "SEQ", initialValue = 100001, allocationSize = 1000) + private String sessionid; + + private int userid; + + private String loginagent; + + private String loginip; + + private long logintime; + + private long logouttime; + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public String getSessionid() { + return sessionid; + } + + public void setSessionid(String sessionid) { + this.sessionid = sessionid; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getLoginagent() { + return loginagent; + } + + public void setLoginagent(String loginagent) { + this.loginagent = loginagent; + } + + public String getLoginip() { + return loginip; + } + + public void setLoginip(String loginip) { + this.loginip = loginip; + } + + public long getLogintime() { + return logintime; + } + + public void setLogintime(long logintime) { + this.logintime = logintime; + } + + public long getLogouttime() { + return logouttime; + } + + public void setLogouttime(long logouttime) { + this.logouttime = logouttime; + } + +} diff --git a/test/org/redkale/test/source/TestSourceCache.java b/test/org/redkale/test/source/TestSourceCache.java new file mode 100644 index 000000000..cf7f6e2dd --- /dev/null +++ b/test/org/redkale/test/source/TestSourceCache.java @@ -0,0 +1,134 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.source; + +import java.util.*; +import org.redkale.source.VirtualEntity; +import org.redkale.source.FilterNodeBean; +import org.redkale.source.FilterExpress; +import org.redkale.source.FilterColumn; +import org.redkale.util.Sheet; +import org.redkale.source.FilterBean; +import org.redkale.source.Flipper; +import org.redkale.source.EntityInfo; +import org.redkale.source.FilterNode; +import java.util.concurrent.*; +import javax.persistence.*; +import org.redkale.convert.json.*; + +/** + * + * @author zhangjx + */ +public class TestSourceCache { + + public static class TestEntityBean implements FilterBean { + + @FilterColumn(express = FilterExpress.GREATERTHAN) + public int userid; + + @FilterColumn(express = FilterExpress.LIKE) + public String username; + + public TestEntityBean(int userid, String username) { + this.userid = userid; + this.username = username; + } + } + + public static void main(String[] args) throws Exception { + final EntityInfo info = EntityInfo.load(TestEntity.class, 0, false,new Properties(), null); + TestEntity[] entitys = new TestEntity[10_0000]; + for (int i = 0; i < entitys.length; i++) { + entitys[i] = new TestEntity(i + 1, "用户_" + (i + 1)); + } + long s = System.currentTimeMillis(); + for (TestEntity en : entitys) { + info.getCache().insert(en); + } + long e = System.currentTimeMillis() - s; + System.out.println("插入十万条记录耗时: " + e / 1000.0 + " 秒"); + + s = System.currentTimeMillis(); + TestEntity one = info.getCache().find(9999); + e = System.currentTimeMillis() - s; + System.out.println("十万条数据中查询一条记录耗时: " + e / 1000.0 + " 秒 " + one); + + final Flipper flipper = new Flipper(2); + flipper.setSort("userid DESC, createtime DESC"); + final FilterNode node = FilterNode.create("userid", FilterExpress.GREATERTHAN, 1000).and("username", FilterExpress.LIKE, "用户"); + System.out.println("node = " + node); + Sheet sheet = info.getCache().querySheet(null, flipper, node); + System.out.println(sheet); + System.out.println(info.getCache().querySheet(null, flipper, FilterNodeBean.createFilterNode(new TestEntityBean(1000, "用户")))); + final CountDownLatch cdl = new CountDownLatch(100); + s = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + new Thread() { + @Override + public void run() { + for (int k = 0; k < 10; k++) { + info.getCache().querySheet(true, null, flipper, node); + } + cdl.countDown(); + } + }.start(); + } + cdl.await(); + e = System.currentTimeMillis() - s; + System.out.println("十万条数据中查询一页记录耗时: " + e / 1000.0 + " 秒 " + sheet); // CopyOnWriteArrayList 0.798 ConcurrentLinkedQueue 1.063 + } + + @VirtualEntity + @Cacheable + public static class TestEntity { + + @Id + private int userid; + + private String username; + + private long createtime = System.currentTimeMillis(); + + public TestEntity() { + + } + + public TestEntity(int userid, String username) { + this.userid = userid; + this.username = username; + } + + public int getUserid() { + return userid; + } + + public void setUserid(int userid) { + this.userid = userid; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public long getCreatetime() { + return createtime; + } + + public void setCreatetime(long createtime) { + this.createtime = createtime; + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + } +} diff --git a/test/org/redkale/test/util/CreatorRecord.java b/test/org/redkale/test/util/CreatorRecord.java new file mode 100644 index 000000000..a9d4d41f4 --- /dev/null +++ b/test/org/redkale/test/util/CreatorRecord.java @@ -0,0 +1,97 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.util; + +import java.beans.*; +import org.redkale.convert.json.*; +import org.redkale.util.*; + +/** + * + * @author zhangjx + */ +public class CreatorRecord { + + private int id = -1; + + private String name; + + private long lval; + + private boolean tval; + + private byte bval; + + private short sval; + + private char cval; + + private float fval; + + private double dval; + + @ConstructorProperties({"id", "name", "lval", "tval", "bval", "sval", "cval", "fval", "dval"}) + CreatorRecord(int id, String name, long lval, boolean tval, byte bval, short sval, char cval, float fval, double dval) { + this.id = id; + this.name = name; + this.lval = lval; + this.tval = tval; + this.bval = bval; + this.sval = sval; + this.cval = cval; + this.fval = fval; + this.dval = dval; + } + + public static void main(String[] args) throws Exception { + CreatorRecord record = Creator.create(CreatorRecord.class).create(new Object[]{null, "ss", null, true, null, (short) 45, null, 4.3f, null}); + String json = record.toString(); + System.out.println(json); + System.out.println(JsonConvert.root().convertFrom(CreatorRecord.class, json).toString()); + } + + @Override + public String toString() { + return JsonConvert.root().convertTo(this); + } + + public int getId() { + return id; + } + + public String getName() { + return name; + } + + public long getLval() { + return lval; + } + + public boolean isTval() { + return tval; + } + + public byte getBval() { + return bval; + } + + public short getSval() { + return sval; + } + + public char getCval() { + return cval; + } + + public float getFval() { + return fval; + } + + public double getDval() { + return dval; + } + +} diff --git a/test/org/redkale/test/util/ResourceTest.java b/test/org/redkale/test/util/ResourceTest.java new file mode 100644 index 000000000..5460d5000 --- /dev/null +++ b/test/org/redkale/test/util/ResourceTest.java @@ -0,0 +1,153 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template bigint, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.util; + +import java.math.*; +import javax.annotation.*; +import org.redkale.util.*; + +/** + * + * @author zhangjx + */ +public class ResourceTest { + +public static void main(String[] args) throws Exception { + ResourceFactory factory = ResourceFactory.root(); + factory.register("property.id", "2345"); //注入String类型的property.id + AService aservice = new AService(); + BService bservice = new BService("eeeee"); + + factory.register(aservice); //放进Resource池内,默认的资源名name为"" + factory.register(bservice); //放进Resource池内,默认的资源名name为"" + + factory.inject(aservice); //给aservice注入id、bservice,bigint没有资源,所以为null + factory.inject(bservice); //给bservice注入id、aservice + System.out.println(aservice); //输出结果为:{id:"2345", intid: 2345, bigint:null, bservice:{name:eeeee}} + System.out.println(bservice); //输出结果为:{name:"eeeee", id: 2345, aserivce:{id:"2345", intid: 2345, bigint:null, bservice:{name:eeeee}}} + + factory.register("seqid", 200); //放进Resource池内, 同时ResourceFactory会自动更新aservice的seqid值 + System.out.println(factory.find("seqid", int.class)); //输出结果为:200 + factory.register("bigint", new BigInteger("666666666666666")); //放进Resource池内, 同时ResourceFactory会自动更新aservice对象的bigint值 + System.out.println(aservice); //输出结果为:{id:"2345", intid: 2345, bigint:666666666666666, bservice:{name:eeeee}} 可以看出seqid与bigint值都已自动更新 + + factory.register("property.id", "6789"); //更新Resource池内的id资源值, 同时ResourceFactory会自动更新aservice、bservice的id值 + System.out.println(aservice); //输出结果为:{id:"6789", intid: 6789, bigint:666666666666666, bservice:{name:eeeee}} + System.out.println(bservice); //输出结果为:{name:"eeeee", id: 6789, aserivce:{id:"6789", intid: 6789, bigint:666666666666666, bservice:{name:eeeee}}} + + bservice = new BService("ffff"); + factory.register(bservice); //更新Resource池内name=""的BService资源, 同时ResourceFactory会自动更新aservice的bservice对象 + factory.inject(bservice); + System.out.println(aservice); //输出结果为:{id:"6789", intid: 6789, bigint:666666666666666, bservice:{name:ffff}} + +} + +} + +class BService { + + @Resource(name = "property.id") + private String id; + + @Resource + private AService aservice; + + private String name = ""; + + @java.beans.ConstructorProperties({"name"}) + public BService(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public AService getAservice() { + return aservice; + } + + public void setAservice(AService aservice) { + this.aservice = aservice; + } + + @Override + public String toString() { + return "{name:\"" + name + "\", id: " + id + ", aserivce:" + aservice + "}"; + } +} + +class AService { + + @Resource(name = "property.id") + private String id; + + @Resource(name = "property.id") //property.开头的资源名允许String自动转换成primitive数值类型 + private int intid; + + @Resource(name = "bigint") + private BigInteger bigint; + + @Resource(name = "seqid") + private int seqid; + + @Resource + private BService bservice; + + @Override + public String toString() { + return "{id:\"" + id + "\", intid: " + intid + ", bigint:" + bigint + ", bservice:" + (bservice == null ? null : ("{name:" + bservice.getName() + "}")) + "}"; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getIntid() { + return intid; + } + + public void setIntid(int intid) { + this.intid = intid; + } + + public int getSeqid() { + return seqid; + } + + public void setSeqid(int seqid) { + this.seqid = seqid; + } + + public BigInteger getBigint() { + return bigint; + } + + public void setBigint(BigInteger bigint) { + this.bigint = bigint; + } + + public void setBservice(BService bservice) { + this.bservice = bservice; + } + +} diff --git a/test/org/redkale/test/util/TestABean.java b/test/org/redkale/test/util/TestABean.java new file mode 100644 index 000000000..9e594f310 --- /dev/null +++ b/test/org/redkale/test/util/TestABean.java @@ -0,0 +1,14 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.util; + +/** + * + * @author zhangjx + */ +public class TestABean { + public long time; +} diff --git a/test/org/redkale/test/util/TestBean.java b/test/org/redkale/test/util/TestBean.java new file mode 100644 index 000000000..9f9f77c93 --- /dev/null +++ b/test/org/redkale/test/util/TestBean.java @@ -0,0 +1,46 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.util; + +import java.util.Map; + +/** + * + * @author zhangjx + */ +public class TestBean extends TestABean { + + private String name; + + private int id; + + private Map map; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + +} diff --git a/test/org/redkale/test/util/TestXBean.java b/test/org/redkale/test/util/TestXBean.java new file mode 100644 index 000000000..d7fe82282 --- /dev/null +++ b/test/org/redkale/test/util/TestXBean.java @@ -0,0 +1,15 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package org.redkale.test.util; + +/** + * + * @author zhangjx + */ +public class TestXBean extends TestBean{ + +} diff --git a/test/org/redkale/test/util/UntilTestMain.java b/test/org/redkale/test/util/UntilTestMain.java new file mode 100644 index 000000000..33f147e9b --- /dev/null +++ b/test/org/redkale/test/util/UntilTestMain.java @@ -0,0 +1,103 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.util; + +import org.redkale.util.Reproduce; +import org.redkale.util.Attribute; + +/** + * + * @author zhangjx + */ +public class UntilTestMain { + + public static void main(String[] args) throws Throwable { + reproduce(args); + attribute(args); + } + + public static void reproduce(String[] args) throws Throwable { + final TestBean bean = new TestBean(); + bean.setId(123456); + bean.setName("zhangjx"); + bean.time = 2000; + final TestXBean beanx = new TestXBean(); + Reproduce action1 = Reproduce.create(TestXBean.class, TestBean.class); + Reproduce action2 = new Reproduce() { + + @Override + public TestXBean copy(TestXBean dest, TestBean src) { + dest.time = src.time; + dest.setId(src.getId()); + dest.setName(src.getName()); + dest.setMap(src.getMap()); + return dest; + } + }; + final int count = 1_000_000; + long s = System.nanoTime(); + for (int i = 0; i < count; i++) { + action2.copy(beanx, bean); + } + long e = System.nanoTime() - s; + System.out.println("静态Reproduce耗时: " + e); + s = System.nanoTime(); + for (int i = 0; i < count; i++) { + action1.copy(beanx, bean); + } + e = System.nanoTime() - s; + System.out.println("动态Reproduce耗时: " + e); + System.out.println(); + } + + public static void attribute(String[] args) throws Throwable { + final TestBean bean = new TestBean(); + bean.setId(123456); + bean.setName("zhangjx"); + Attribute action1 = Attribute.create(TestBean.class.getDeclaredField("name")); + Attribute action2 = new Attribute() { + + @Override + public String field() { + return "name"; + } + + @Override + public String get(TestBean obj) { + return obj.getName(); + } + + @Override + public void set(TestBean obj, String value) { + obj.setName(value); + } + + @Override + public Class type() { + return String.class; + } + + @Override + public Class declaringClass() { + return TestBean.class; + } + }; + final int count = 1_000_000; + long s = System.nanoTime(); + for (int i = 0; i < count; i++) { + action2.set(bean, "zhangjx2"); + } + long e = System.nanoTime() - s; + System.out.println("静态Attribute耗时: " + e); + s = System.nanoTime(); + for (int i = 0; i < count; i++) { + action1.set(bean, "zhangjx2"); + } + e = System.nanoTime() - s; + System.out.println("动态Attribute耗时: " + e); + System.out.println(); + } +} diff --git a/test/org/redkale/test/websocket/ChatWebSocketServlet.java b/test/org/redkale/test/websocket/ChatWebSocketServlet.java new file mode 100644 index 000000000..ff5410646 --- /dev/null +++ b/test/org/redkale/test/websocket/ChatWebSocketServlet.java @@ -0,0 +1,77 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.websocket; + +import org.redkale.net.http.WebServlet; +import org.redkale.net.http.WebSocketServlet; +import org.redkale.net.http.WebSocket; +import java.io.*; +import static java.lang.Thread.sleep; +import java.text.*; +import java.util.concurrent.atomic.*; +import static java.lang.Thread.sleep; +import static java.lang.Thread.sleep; +import static java.lang.Thread.sleep; + +/** + * + * @author zhangjx + */ +@WebServlet("/ws/chat") +public class ChatWebSocketServlet extends WebSocketServlet { + + private final AtomicLong counter = new AtomicLong(); + + private final AtomicLong icounter = new AtomicLong(); + + private final boolean debug; + + public ChatWebSocketServlet() { + debug = "true".equalsIgnoreCase(System.getProperty("debug", "false")); + Thread t = new Thread() { + + private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + { + setName("Debug-ChatWebSocket-ShowCount-Thread"); + } + + @Override + public void run() { + while (true) { + try { + sleep(60 * 1000); + } catch (Exception e) { + return; + } + System.out.println(format.format(new java.util.Date()) + ": 消息总数: " + counter.get() + ",间隔消息数: " + icounter.getAndSet(0)); + } + } + }; + t.start(); + } + + @Override + protected WebSocket createWebSocket() { + + return new WebSocket() { + + @Override + public void onMessage(String text) { + icounter.incrementAndGet(); + counter.incrementAndGet(); + if (debug) System.out.println("收到消息: " + text); + super.getWebSocketGroup().getWebSockets().forEach(x -> x.send(text)); + } + + @Override + protected Serializable createGroupid() { + return ""; + } + }; + } + +} diff --git a/test/org/redkale/test/websocket/Flash843.java b/test/org/redkale/test/websocket/Flash843.java new file mode 100644 index 000000000..bd29f8ddf --- /dev/null +++ b/test/org/redkale/test/websocket/Flash843.java @@ -0,0 +1,29 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.websocket; + +import java.io.ByteArrayOutputStream; +import java.net.Socket; + +/** + * + * @author zhangjx + */ +public class Flash843 { + + public static void main(String[] args) throws Exception { + Socket socket = new Socket("113.105.88.229", 843); + socket.getOutputStream().write("".getBytes()); + socket.getOutputStream().flush(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] bytes = new byte[1024]; + int pos; + while ((pos = socket.getInputStream().read(bytes)) != -1) { + out.write(bytes, 0, pos); + } + System.out.println(out.toString()); + } +} diff --git a/test/org/redkale/test/websocket/VideoWebSocketServlet.java b/test/org/redkale/test/websocket/VideoWebSocketServlet.java new file mode 100644 index 000000000..79bec9478 --- /dev/null +++ b/test/org/redkale/test/websocket/VideoWebSocketServlet.java @@ -0,0 +1,134 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package org.redkale.test.websocket; + +import org.redkale.net.http.WebServlet; +import org.redkale.net.http.WebSocketServlet; +import org.redkale.net.http.HttpRequest; +import org.redkale.net.http.WebSocket; +import org.redkale.net.http.HttpServer; +import org.redkale.util.TypeToken; +import org.redkale.util.AnyValue; +import java.io.*; +import java.util.*; +import java.util.concurrent.CountDownLatch; + +/** + * + * @author zhangjx + */ +@WebServlet({"/ws/listen"}) +public class VideoWebSocketServlet extends WebSocketServlet { + + private final Map sessions = new java.util.concurrent.ConcurrentHashMap<>(); + + private final Map users = new HashMap<>(); + + private static final class Entry { + + public WebSocket socket; + + public String username; + + public Serializable userid; + + } + + public VideoWebSocketServlet() { + super(); + users.put("zhangjx", "xxxx"); + } + + @Override + protected WebSocket createWebSocket() { + WebSocket socket = new WebSocket() { + + private final TypeToken> mapToken = new TypeToken>() { + }; + + private boolean repeat = false; + + @Override + public String onOpen(final HttpRequest request) { + String uri = request.getRequestURI(); + int pos = uri.indexOf("/listen/"); + uri = uri.substring(pos + "/listen/".length()); + this.repeat = sessions.get(uri) != null; + if (!this.repeat) this.repeat = users.get(uri) == null; + String sessionid = Long.toString(System.nanoTime()); + if (uri.indexOf('\'') >= 0 || uri.indexOf('"') >= 0) return null; + if (!repeat) sessionid = uri; + return sessionid; + } + + @Override + public void onConnected() { + if (repeat) { + super.close(); + } else { + Entry entry = new Entry(); + entry.userid = this.getSessionid(); + entry.username = users.get(entry.userid); + sessions.put(this.getSessionid(), entry); + StringBuilder sb = new StringBuilder(); + for (Map.Entry en : sessions.entrySet()) { + if (sb.length() > 0) sb.append(','); + sb.append("{'userid':'").append(en.getKey()).append("','username':'").append(en.getValue().username).append("'}"); + } + super.send(("{'type':'user_list','users':[" + sb + "]}").replace('\'', '"')); + String msg = ("{'type':'discover_user','user':{'userid':'" + this.getSessionid() + "','username':'" + users.get(this.getSessionid()) + "'}}").replace('\'', '"'); + super.getWebSocketGroup().getWebSockets().filter(x -> x != this).forEach(x -> { + x.send(msg); + }); + } + } + + @Override + public void onMessage(String text) { + //System.out.println("接收到消息: " + text); + super.getWebSocketGroup().getWebSockets().filter(x -> x != this).forEach(x -> { + x.send(text); + }); + } + + @Override + public void onClose(int code, String reason) { + sessions.remove(this.getSessionid()); + String msg = ("{'type':'remove_user','user':{'userid':'" + this.getSessionid() + "','username':'" + users.get(this.getSessionid()) + "'}}").replace('\'', '"'); + super.getWebSocketGroup().getWebSockets().filter(x -> x != this).forEach(x -> { + x.send(msg); + }); + } + + @Override + protected Serializable createGroupid() { + return ""; + } + }; + return socket; + } + + public static void main(String[] args) throws Throwable { + CountDownLatch cdl = new CountDownLatch(1); + AnyValue.DefaultAnyValue config = new AnyValue.DefaultAnyValue(); + config.addValue("threads", System.getProperty("threads")); + config.addValue("bufferPoolSize", System.getProperty("bufferPoolSize")); + config.addValue("responsePoolSize", System.getProperty("responsePoolSize")); + config.addValue("host", System.getProperty("host", "0.0.0.0")); + config.addValue("port", System.getProperty("port", "8070")); + config.addValue("root", System.getProperty("root", "./root3/")); + AnyValue.DefaultAnyValue resConf = new AnyValue.DefaultAnyValue(); + resConf.setValue("cacheMaxLength", "200M"); + resConf.setValue("cacheMaxItemLength", "10M"); + config.setValue("ResourceServlet", resConf); + HttpServer server = new HttpServer(); + server.addHttpServlet(new VideoWebSocketServlet(), "/pipes", null, "/listen/*"); + server.init(config); + server.start(); + cdl.await(); + } + +}