format
This commit is contained in:
@@ -11,29 +11,29 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class AsmCreator {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
boolean realasm = false; // 从http://forge.ow2.org/projects/asm/ 下载最新asm的src放在 srcasmroot 目录下
|
||||
File srcasmroot = new File("D:/JAVA/JDK源码/jdk/internal/org/objectweb/asm");
|
||||
if (realasm) srcasmroot = new File("D:/JAVA/JDK源码/org/objectweb/asm");
|
||||
File destasmroot = new File("D:/Java-Projects/RedkaleProject/src/main/java/org/redkale/asm");
|
||||
String line = null;
|
||||
LineNumberReader txtin = new LineNumberReader(new FileReader(new File(destasmroot, "asm.txt")));
|
||||
while ((line = txtin.readLine()) != null) {
|
||||
line = line.trim();
|
||||
if (!line.endsWith(".java")) continue;
|
||||
File srcfile = new File(srcasmroot, line);
|
||||
if (!srcfile.isFile()) continue;
|
||||
File destfile = new File(destasmroot, line);
|
||||
String content = Utility.readThenClose(new FileInputStream(srcfile));
|
||||
FileOutputStream out = new FileOutputStream(destfile);
|
||||
out.write(content.replace("jdk.internal.org.objectweb", "org.redkale")
|
||||
.replace("org.objectweb", "org.redkale")
|
||||
.replace("<tt>", "<tt>")
|
||||
.replace("</tt>", "</tt>")
|
||||
.replace("{@link org.redkale.asm.tree.MethodNode#getLabelNode} method.", "")
|
||||
.getBytes());
|
||||
out.close();
|
||||
}
|
||||
// 需要屏蔽ClassReader中判断checks the class version的部分
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
boolean realasm = false; // 从http://forge.ow2.org/projects/asm/ 下载最新asm的src放在 srcasmroot 目录下
|
||||
File srcasmroot = new File("D:/JAVA/JDK源码/jdk/internal/org/objectweb/asm");
|
||||
if (realasm) srcasmroot = new File("D:/JAVA/JDK源码/org/objectweb/asm");
|
||||
File destasmroot = new File("D:/Java-Projects/RedkaleProject/src/main/java/org/redkale/asm");
|
||||
String line = null;
|
||||
LineNumberReader txtin = new LineNumberReader(new FileReader(new File(destasmroot, "asm.txt")));
|
||||
while ((line = txtin.readLine()) != null) {
|
||||
line = line.trim();
|
||||
if (!line.endsWith(".java")) continue;
|
||||
File srcfile = new File(srcasmroot, line);
|
||||
if (!srcfile.isFile()) continue;
|
||||
File destfile = new File(destasmroot, line);
|
||||
String content = Utility.readThenClose(new FileInputStream(srcfile));
|
||||
FileOutputStream out = new FileOutputStream(destfile);
|
||||
out.write(content.replace("jdk.internal.org.objectweb", "org.redkale")
|
||||
.replace("org.objectweb", "org.redkale")
|
||||
.replace("<tt>", "<tt>")
|
||||
.replace("</tt>", "</tt>")
|
||||
.replace("{@link org.redkale.asm.tree.MethodNode#getLabelNode} method.", "")
|
||||
.getBytes());
|
||||
out.close();
|
||||
}
|
||||
// 需要屏蔽ClassReader中判断checks the class version的部分
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,100 +20,100 @@ import org.redkale.util.RedkaleException;
|
||||
/** @author zhangjx */
|
||||
public class CacheInstance implements Service {
|
||||
|
||||
@Resource
|
||||
private CacheManager cacheManager;
|
||||
@Resource
|
||||
private CacheManager cacheManager;
|
||||
|
||||
// 修改远程缓存的key值
|
||||
public void updateName(String code, Map<String, Long> map) {
|
||||
cacheManager.remoteSetString(code, code + "_" + map.get("id"), Duration.ofMillis(60));
|
||||
}
|
||||
// 修改远程缓存的key值
|
||||
public void updateName(String code, Map<String, Long> map) {
|
||||
cacheManager.remoteSetString(code, code + "_" + map.get("id"), Duration.ofMillis(60));
|
||||
}
|
||||
|
||||
@Cached(key = "#{code}_#{map.id}", remoteExpire = "60", timeUnit = TimeUnit.MILLISECONDS)
|
||||
public String getName(String code, Map<String, Long> map) {
|
||||
return code + "-" + map;
|
||||
}
|
||||
@Cached(key = "#{code}_#{map.id}", remoteExpire = "60", timeUnit = TimeUnit.MILLISECONDS)
|
||||
public String getName(String code, Map<String, Long> map) {
|
||||
return code + "-" + map;
|
||||
}
|
||||
|
||||
@Cached(key = "name", localExpire = "30")
|
||||
public String getName() {
|
||||
return "haha";
|
||||
}
|
||||
@Cached(key = "name", localExpire = "30")
|
||||
public String getName() {
|
||||
return "haha";
|
||||
}
|
||||
|
||||
@Cached(key = "name", localExpire = "30", remoteExpire = "60")
|
||||
public String getName2() throws RedkaleException {
|
||||
return "haha";
|
||||
}
|
||||
@Cached(key = "name", localExpire = "30", remoteExpire = "60")
|
||||
public String getName2() throws RedkaleException {
|
||||
return "haha";
|
||||
}
|
||||
|
||||
@Cached(key = "name", localExpire = "30")
|
||||
public CompletableFuture<String> getNameAsync() {
|
||||
return CompletableFuture.completedFuture("nameAsync");
|
||||
}
|
||||
@Cached(key = "name", localExpire = "30")
|
||||
public CompletableFuture<String> getNameAsync() {
|
||||
return CompletableFuture.completedFuture("nameAsync");
|
||||
}
|
||||
|
||||
@Cached(key = "name", localExpire = "30", remoteExpire = "60")
|
||||
public CompletableFuture<String> getName2Async() throws IOException, InstantiationException {
|
||||
return CompletableFuture.completedFuture("name2Async");
|
||||
}
|
||||
@Cached(key = "name", localExpire = "30", remoteExpire = "60")
|
||||
public CompletableFuture<String> getName2Async() throws IOException, InstantiationException {
|
||||
return CompletableFuture.completedFuture("name2Async");
|
||||
}
|
||||
|
||||
@Cached(key = "info_#{id}_file#{files.one}", localExpire = "30", remoteExpire = "60")
|
||||
public File getInfo(ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return new File("aa.txt");
|
||||
}
|
||||
@Cached(key = "info_#{id}_file#{files.one}", localExpire = "30", remoteExpire = "60")
|
||||
public File getInfo(ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return new File("aa.txt");
|
||||
}
|
||||
|
||||
@Cached(key = "info_#{id}_file#{files.one}", localExpire = "30", remoteExpire = "60")
|
||||
public CompletableFuture<File> getInfoAsync(ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return CompletableFuture.completedFuture(new File("aa.txt"));
|
||||
}
|
||||
@Cached(key = "info_#{id}_file#{files.one}", localExpire = "30", remoteExpire = "60")
|
||||
public CompletableFuture<File> getInfoAsync(ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return CompletableFuture.completedFuture(new File("aa.txt"));
|
||||
}
|
||||
|
||||
@Cached(
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
localExpire = "30",
|
||||
remoteExpire = "60",
|
||||
timeUnit = TimeUnit.MILLISECONDS)
|
||||
public CompletableFuture<Map<String, Integer>> getInfo2Async(
|
||||
ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
@Cached(
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
localExpire = "30",
|
||||
remoteExpire = "60",
|
||||
timeUnit = TimeUnit.MILLISECONDS)
|
||||
public CompletableFuture<Map<String, Integer>> getInfo2Async(
|
||||
ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
public static class ParamBean {
|
||||
public static class ParamBean {
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private int day;
|
||||
private int day;
|
||||
|
||||
private Integer status;
|
||||
private Integer status;
|
||||
|
||||
private Range.IntRange range;
|
||||
private Range.IntRange range;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getDay() {
|
||||
return day;
|
||||
}
|
||||
public int getDay() {
|
||||
return day;
|
||||
}
|
||||
|
||||
public void setDay(int day) {
|
||||
this.day = day;
|
||||
}
|
||||
public void setDay(int day) {
|
||||
this.day = day;
|
||||
}
|
||||
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
public Integer getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
public void setStatus(Integer status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Range.IntRange getRange() {
|
||||
return range;
|
||||
}
|
||||
public Range.IntRange getRange() {
|
||||
return range;
|
||||
}
|
||||
|
||||
public void setRange(Range.IntRange range) {
|
||||
this.range = range;
|
||||
}
|
||||
}
|
||||
public void setRange(Range.IntRange range) {
|
||||
this.range = range;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,41 +22,41 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class CacheInstanceTest {
|
||||
|
||||
private static ResourceFactory resourceFactory;
|
||||
private static ResourceFactory resourceFactory;
|
||||
|
||||
private static CacheManagerService manager;
|
||||
private static CacheManagerService manager;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CacheInstanceTest test = new CacheInstanceTest();
|
||||
init();
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CacheInstanceTest test = new CacheInstanceTest();
|
||||
init();
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
resourceFactory = ResourceFactory.create();
|
||||
resourceFactory.register(new Environment());
|
||||
CacheMemorySource remoteSource = new CacheMemorySource("cache-remote");
|
||||
remoteSource.init(null);
|
||||
manager = CacheManagerService.create(remoteSource);
|
||||
manager.init(null);
|
||||
resourceFactory.register("", CacheManager.class, manager);
|
||||
}
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
resourceFactory = ResourceFactory.create();
|
||||
resourceFactory.register(new Environment());
|
||||
CacheMemorySource remoteSource = new CacheMemorySource("cache-remote");
|
||||
remoteSource.init(null);
|
||||
manager = CacheManagerService.create(remoteSource);
|
||||
manager.init(null);
|
||||
resourceFactory.register("", CacheManager.class, manager);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Class<CacheInstance> serviceClass = CacheInstance.class;
|
||||
CacheAsmMethodBoost boost = new CacheAsmMethodBoost(false, serviceClass);
|
||||
SncpRpcGroups grous = new SncpRpcGroups();
|
||||
AsyncGroup iGroup = AsyncGroup.create("", Utility.newScheduledExecutor(1), 0, 0);
|
||||
SncpClient client = new SncpClient(
|
||||
"", iGroup, "0", new InetSocketAddress("127.0.0.1", 8080), new ClientAddress(), "TCP", 1, 16);
|
||||
CacheInstance instance = Sncp.createLocalService(
|
||||
null, "", serviceClass, boost, resourceFactory, grous, client, null, null, null);
|
||||
// System.out.println(instance.getName());
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Class<CacheInstance> serviceClass = CacheInstance.class;
|
||||
CacheAsmMethodBoost boost = new CacheAsmMethodBoost(false, serviceClass);
|
||||
SncpRpcGroups grous = new SncpRpcGroups();
|
||||
AsyncGroup iGroup = AsyncGroup.create("", Utility.newScheduledExecutor(1), 0, 0);
|
||||
SncpClient client = new SncpClient(
|
||||
"", iGroup, "0", new InetSocketAddress("127.0.0.1", 8080), new ClientAddress(), "TCP", 1, 16);
|
||||
CacheInstance instance = Sncp.createLocalService(
|
||||
null, "", serviceClass, boost, resourceFactory, grous, client, null, null, null);
|
||||
// System.out.println(instance.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {}
|
||||
@Test
|
||||
public void run2() throws Exception {}
|
||||
}
|
||||
|
||||
@@ -15,130 +15,130 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class CacheManagerTest {
|
||||
|
||||
private static CacheManagerService manager;
|
||||
private static CacheManagerService manager;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CacheManagerTest test = new CacheManagerTest();
|
||||
init();
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CacheManagerTest test = new CacheManagerTest();
|
||||
init();
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
CacheMemorySource remoteSource = new CacheMemorySource("cache-remote");
|
||||
remoteSource.init(null);
|
||||
manager = CacheManagerService.create(remoteSource);
|
||||
manager.init(null);
|
||||
}
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
CacheMemorySource remoteSource = new CacheMemorySource("cache-remote");
|
||||
remoteSource.init(null);
|
||||
manager = CacheManagerService.create(remoteSource);
|
||||
manager.init(null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Duration expire = Duration.ofMillis(290);
|
||||
manager.localSetString("user", "name:haha", "myha", expire);
|
||||
Assertions.assertEquals(manager.localGetString("user", "name:haha"), "myha");
|
||||
Utility.sleep(300);
|
||||
Assertions.assertTrue(manager.localGetString("user", "name:haha") == null);
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Duration expire = Duration.ofMillis(290);
|
||||
manager.localSetString("user", "name:haha", "myha", expire);
|
||||
Assertions.assertEquals(manager.localGetString("user", "name:haha"), "myha");
|
||||
Utility.sleep(300);
|
||||
Assertions.assertTrue(manager.localGetString("user", "name:haha") == null);
|
||||
|
||||
CachingBean bean = new CachingBean();
|
||||
bean.setName("tom");
|
||||
bean.setRemark("这是名字备注");
|
||||
CachingBean bean = new CachingBean();
|
||||
bean.setName("tom");
|
||||
bean.setRemark("这是名字备注");
|
||||
|
||||
String json = bean.toString();
|
||||
manager.localSet("user", bean.getName(), CachingBean.class, bean, expire);
|
||||
Assertions.assertEquals(
|
||||
manager.localGet("user", bean.getName(), CachingBean.class).toString(), json);
|
||||
bean.setRemark(bean.getRemark() + "-新备注");
|
||||
Assertions.assertEquals(
|
||||
manager.localGet("user", bean.getName(), CachingBean.class).toString(), json);
|
||||
}
|
||||
String json = bean.toString();
|
||||
manager.localSet("user", bean.getName(), CachingBean.class, bean, expire);
|
||||
Assertions.assertEquals(
|
||||
manager.localGet("user", bean.getName(), CachingBean.class).toString(), json);
|
||||
bean.setRemark(bean.getRemark() + "-新备注");
|
||||
Assertions.assertEquals(
|
||||
manager.localGet("user", bean.getName(), CachingBean.class).toString(), json);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
int count = 50;
|
||||
ParallelBean bean = new ParallelBean();
|
||||
Duration localExpire = Duration.ofMillis(190);
|
||||
Duration remoteExpire = Duration.ofMillis(400);
|
||||
{
|
||||
CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
new Thread(() -> {
|
||||
manager.bothGetSet(
|
||||
"ParallelBean",
|
||||
"name",
|
||||
String.class,
|
||||
false,
|
||||
localExpire,
|
||||
remoteExpire,
|
||||
() -> bean.getName());
|
||||
cdl.countDown();
|
||||
})
|
||||
.start();
|
||||
}
|
||||
cdl.await();
|
||||
}
|
||||
Assertions.assertEquals(1, ParallelBean.c1.get());
|
||||
Utility.sleep(200);
|
||||
manager.bothGetSet(
|
||||
"ParallelBean", "name", String.class, false, localExpire, remoteExpire, () -> bean.getName());
|
||||
Assertions.assertEquals(1, ParallelBean.c1.get());
|
||||
Utility.sleep(200);
|
||||
{
|
||||
CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
new Thread(() -> {
|
||||
manager.bothGetSet(
|
||||
"ParallelBean",
|
||||
"name",
|
||||
String.class,
|
||||
false,
|
||||
localExpire,
|
||||
remoteExpire,
|
||||
() -> bean.getName());
|
||||
cdl.countDown();
|
||||
})
|
||||
.start();
|
||||
}
|
||||
cdl.await();
|
||||
}
|
||||
Assertions.assertEquals(2, ParallelBean.c1.get());
|
||||
}
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
int count = 50;
|
||||
ParallelBean bean = new ParallelBean();
|
||||
Duration localExpire = Duration.ofMillis(190);
|
||||
Duration remoteExpire = Duration.ofMillis(400);
|
||||
{
|
||||
CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
new Thread(() -> {
|
||||
manager.bothGetSet(
|
||||
"ParallelBean",
|
||||
"name",
|
||||
String.class,
|
||||
false,
|
||||
localExpire,
|
||||
remoteExpire,
|
||||
() -> bean.getName());
|
||||
cdl.countDown();
|
||||
})
|
||||
.start();
|
||||
}
|
||||
cdl.await();
|
||||
}
|
||||
Assertions.assertEquals(1, ParallelBean.c1.get());
|
||||
Utility.sleep(200);
|
||||
manager.bothGetSet(
|
||||
"ParallelBean", "name", String.class, false, localExpire, remoteExpire, () -> bean.getName());
|
||||
Assertions.assertEquals(1, ParallelBean.c1.get());
|
||||
Utility.sleep(200);
|
||||
{
|
||||
CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 0; i < count; i++) {
|
||||
new Thread(() -> {
|
||||
manager.bothGetSet(
|
||||
"ParallelBean",
|
||||
"name",
|
||||
String.class,
|
||||
false,
|
||||
localExpire,
|
||||
remoteExpire,
|
||||
() -> bean.getName());
|
||||
cdl.countDown();
|
||||
})
|
||||
.start();
|
||||
}
|
||||
cdl.await();
|
||||
}
|
||||
Assertions.assertEquals(2, ParallelBean.c1.get());
|
||||
}
|
||||
|
||||
public static class ParallelBean {
|
||||
public static class ParallelBean {
|
||||
|
||||
public static final AtomicInteger c1 = new AtomicInteger();
|
||||
public static final AtomicInteger c1 = new AtomicInteger();
|
||||
|
||||
public String getName() {
|
||||
c1.incrementAndGet();
|
||||
System.out.println("执行了getName方法(" + c1.get() + ")");
|
||||
return "hello";
|
||||
}
|
||||
}
|
||||
public String getName() {
|
||||
c1.incrementAndGet();
|
||||
System.out.println("执行了getName方法(" + c1.get() + ")");
|
||||
return "hello";
|
||||
}
|
||||
}
|
||||
|
||||
public static class CachingBean {
|
||||
public static class CachingBean {
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private String remark;
|
||||
private String remark;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,150 +23,150 @@ import org.redkale.util.ThrowSupplier;
|
||||
@ResourceType(CacheInstance.class)
|
||||
public class _DynLocalCacheInstance extends CacheInstance {
|
||||
|
||||
private AnyValue _redkale_conf;
|
||||
private AnyValue _redkale_conf;
|
||||
|
||||
private String _redkale_mq;
|
||||
private String _redkale_mq;
|
||||
|
||||
private CacheAction _redkale_getNameCacheAction1;
|
||||
private CacheAction _redkale_getNameCacheAction1;
|
||||
|
||||
private CacheAction _redkale_getInfoCacheAction2;
|
||||
private CacheAction _redkale_getInfoCacheAction2;
|
||||
|
||||
private CacheAction _redkale_getNameAsyncCacheAction3;
|
||||
private CacheAction _redkale_getNameAsyncCacheAction3;
|
||||
|
||||
private CacheAction _redkale_getInfo2AsyncCacheAction4;
|
||||
private CacheAction _redkale_getInfo2AsyncCacheAction4;
|
||||
|
||||
private CacheAction _redkale_getName2AsyncCacheAction5;
|
||||
private CacheAction _redkale_getName2AsyncCacheAction5;
|
||||
|
||||
private CacheAction _redkale_getInfoAsyncCacheAction6;
|
||||
private CacheAction _redkale_getInfoAsyncCacheAction6;
|
||||
|
||||
private CacheAction _redkale_getName2CacheAction7;
|
||||
private CacheAction _redkale_getName2CacheAction7;
|
||||
|
||||
public _DynLocalCacheInstance() {}
|
||||
public _DynLocalCacheInstance() {}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getNameCacheAction1",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "-1",
|
||||
localExpire = "30")
|
||||
public String getName() {
|
||||
ThrowSupplier<String> supplier = () -> this.getName_afterCache();
|
||||
return _redkale_getNameCacheAction1.get(supplier);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getNameCacheAction1",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "-1",
|
||||
localExpire = "30")
|
||||
public String getName() {
|
||||
ThrowSupplier<String> supplier = () -> this.getName_afterCache();
|
||||
return _redkale_getNameCacheAction1.get(supplier);
|
||||
}
|
||||
|
||||
private String getName_afterCache() {
|
||||
return super.getName();
|
||||
}
|
||||
private String getName_afterCache() {
|
||||
return super.getName();
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfoCacheAction2",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public File getInfo(CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
ThrowSupplier<File> supplier = () -> this.getInfo_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfoCacheAction2.get(supplier);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfoCacheAction2",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public File getInfo(CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
ThrowSupplier<File> supplier = () -> this.getInfo_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfoCacheAction2.get(supplier);
|
||||
}
|
||||
|
||||
private File getInfo_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return super.getInfo(bean, id, idList, files);
|
||||
}
|
||||
private File getInfo_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return super.getInfo(bean, id, idList, files);
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getNameAsyncCacheAction3",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "-1",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<String> getNameAsync() {
|
||||
ThrowSupplier<CompletableFuture<String>> supplier = () -> this.getNameAsync_afterCache();
|
||||
return _redkale_getNameAsyncCacheAction3.get(supplier);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getNameAsyncCacheAction3",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "-1",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<String> getNameAsync() {
|
||||
ThrowSupplier<CompletableFuture<String>> supplier = () -> this.getNameAsync_afterCache();
|
||||
return _redkale_getNameAsyncCacheAction3.get(supplier);
|
||||
}
|
||||
|
||||
private CompletableFuture<String> getNameAsync_afterCache() {
|
||||
return super.getNameAsync();
|
||||
}
|
||||
private CompletableFuture<String> getNameAsync_afterCache() {
|
||||
return super.getNameAsync();
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfo2AsyncCacheAction4",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<Map<String, Integer>> getInfo2Async(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
ThrowSupplier<CompletableFuture<Map<String, Integer>>> supplier =
|
||||
() -> this.getInfo2Async_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfo2AsyncCacheAction4.get(supplier, bean, id, idList, files);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfo2AsyncCacheAction4",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<Map<String, Integer>> getInfo2Async(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
ThrowSupplier<CompletableFuture<Map<String, Integer>>> supplier =
|
||||
() -> this.getInfo2Async_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfo2AsyncCacheAction4.get(supplier, bean, id, idList, files);
|
||||
}
|
||||
|
||||
private CompletableFuture<Map<String, Integer>> getInfo2Async_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
return super.getInfo2Async(bean, id, idList, files);
|
||||
}
|
||||
private CompletableFuture<Map<String, Integer>> getInfo2Async_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files)
|
||||
throws IOException, InstantiationException {
|
||||
return super.getInfo2Async(bean, id, idList, files);
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getName2AsyncCacheAction5",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<String> getName2Async() throws IOException, InstantiationException {
|
||||
ThrowSupplier<CompletableFuture<String>> supplier = () -> this.getName2Async_afterCache();
|
||||
return _redkale_getName2AsyncCacheAction5.get(supplier);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getName2AsyncCacheAction5",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<String> getName2Async() throws IOException, InstantiationException {
|
||||
ThrowSupplier<CompletableFuture<String>> supplier = () -> this.getName2Async_afterCache();
|
||||
return _redkale_getName2AsyncCacheAction5.get(supplier);
|
||||
}
|
||||
|
||||
private CompletableFuture<String> getName2Async_afterCache() throws IOException, InstantiationException {
|
||||
return super.getName2Async();
|
||||
}
|
||||
private CompletableFuture<String> getName2Async_afterCache() throws IOException, InstantiationException {
|
||||
return super.getName2Async();
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfoAsyncCacheAction6",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<File> getInfoAsync(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
ThrowSupplier<CompletableFuture<File>> supplier = () -> this.getInfoAsync_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfoAsyncCacheAction6.get(supplier, bean, id, idList, files);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getInfoAsyncCacheAction6",
|
||||
hash = "",
|
||||
key = "info_#{id}_file#{files.one}",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public CompletableFuture<File> getInfoAsync(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
ThrowSupplier<CompletableFuture<File>> supplier = () -> this.getInfoAsync_afterCache(bean, id, idList, files);
|
||||
return _redkale_getInfoAsyncCacheAction6.get(supplier, bean, id, idList, files);
|
||||
}
|
||||
|
||||
private CompletableFuture<File> getInfoAsync_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return super.getInfoAsync(bean, id, idList, files);
|
||||
}
|
||||
private CompletableFuture<File> getInfoAsync_afterCache(
|
||||
CacheInstance.ParamBean bean, int id, List<String> idList, Map<String, File> files) {
|
||||
return super.getInfoAsync(bean, id, idList, files);
|
||||
}
|
||||
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getName2CacheAction7",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public String getName2() throws RedkaleException {
|
||||
ThrowSupplier<String> supplier = () -> this.getName2_afterCache();
|
||||
return _redkale_getName2CacheAction7.get(supplier);
|
||||
}
|
||||
@DynForCache(
|
||||
dynField = "_redkale_getName2CacheAction7",
|
||||
hash = "",
|
||||
key = "name",
|
||||
nullable = false,
|
||||
timeUnit = TimeUnit.SECONDS,
|
||||
remoteExpire = "60",
|
||||
localExpire = "30")
|
||||
public String getName2() throws RedkaleException {
|
||||
ThrowSupplier<String> supplier = () -> this.getName2_afterCache();
|
||||
return _redkale_getName2CacheAction7.get(supplier);
|
||||
}
|
||||
|
||||
private String getName2_afterCache() throws RedkaleException {
|
||||
return super.getName2();
|
||||
}
|
||||
private String getName2_afterCache() throws RedkaleException {
|
||||
return super.getName2();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,269 +18,269 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class BsonMainTest {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
BsonMainTest test = new BsonMainTest();
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
test.run4();
|
||||
test.run5();
|
||||
test.run6();
|
||||
test.run7();
|
||||
test.run8();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
BsonMainTest test = new BsonMainTest();
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
test.run4();
|
||||
test.run5();
|
||||
test.run6();
|
||||
test.run7();
|
||||
test.run8();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
Serializable[] sers = new Serializable[] {"aaa", 4};
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
byte[] bytes = convert.convertTo(sers);
|
||||
Utility.println("---", bytes);
|
||||
byte[] checks = new byte[] {
|
||||
0x00, 0x00, 0x00, 0x02, 0x7f, 0x01, 0x41, 0x00, 0x00, 0x00, 0x03, 0x61, 0x61, 0x61, 0x01, 0x69, 0x00, 0x00,
|
||||
0x00, 0x04
|
||||
};
|
||||
Assertions.assertArrayEquals(checks, bytes);
|
||||
Serializable[] a = convert.convertFrom(Serializable[].class, bytes);
|
||||
Assertions.assertEquals("[aaa, 4]", Arrays.toString(a));
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
Serializable[] sers = new Serializable[] {"aaa", 4};
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
byte[] bytes = convert.convertTo(sers);
|
||||
Utility.println("---", bytes);
|
||||
byte[] checks = new byte[] {
|
||||
0x00, 0x00, 0x00, 0x02, 0x7f, 0x01, 0x41, 0x00, 0x00, 0x00, 0x03, 0x61, 0x61, 0x61, 0x01, 0x69, 0x00, 0x00,
|
||||
0x00, 0x04
|
||||
};
|
||||
Assertions.assertArrayEquals(checks, bytes);
|
||||
Serializable[] a = convert.convertFrom(Serializable[].class, bytes);
|
||||
Assertions.assertEquals("[aaa, 4]", Arrays.toString(a));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
SimpleChildEntity entry = SimpleChildEntity.create();
|
||||
byte[] bytes = convert.convertTo(SimpleEntity.class, entry);
|
||||
System.out.println("长度: " + bytes.length);
|
||||
Assertions.assertEquals(260, bytes.length);
|
||||
BsonByteBufferWriter writer = convert.pollWriter(() -> 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);
|
||||
Assertions.assertEquals(260, len);
|
||||
SimpleChildEntity entry2 = convert.convertFrom(SimpleChildEntity.class, buffers);
|
||||
System.out.println(entry);
|
||||
Assertions.assertEquals(entry.toString(), entry2.toString());
|
||||
}
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
SimpleChildEntity entry = SimpleChildEntity.create();
|
||||
byte[] bytes = convert.convertTo(SimpleEntity.class, entry);
|
||||
System.out.println("长度: " + bytes.length);
|
||||
Assertions.assertEquals(260, bytes.length);
|
||||
BsonByteBufferWriter writer = convert.pollWriter(() -> 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);
|
||||
Assertions.assertEquals(260, len);
|
||||
SimpleChildEntity entry2 = convert.convertFrom(SimpleChildEntity.class, buffers);
|
||||
System.out.println(entry);
|
||||
Assertions.assertEquals(entry.toString(), entry2.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run3() 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);
|
||||
Assertions.assertEquals(JsonConvert.root().convertTo(entry), rs.toString());
|
||||
@Test
|
||||
public void run3() 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);
|
||||
Assertions.assertEquals(JsonConvert.root().convertTo(entry), rs.toString());
|
||||
|
||||
ComplextEntity bean = new ComplextEntity();
|
||||
byte[] bytes2 = convert.convertTo(Object.class, bean);
|
||||
final int len = bytes2.length;
|
||||
BsonByteBufferWriter writer = convert.pollWriter(() -> ByteBuffer.allocate(len / 2));
|
||||
convert.convertTo(writer, bean);
|
||||
bytes2 = writer.toArray();
|
||||
System.out.println(convert.convertFrom(ComplextEntity.class, bytes2).toString());
|
||||
Assertions.assertEquals(
|
||||
"{\"chname\":\"\",\"flag\":true,\"userid\":0}",
|
||||
convert.convertFrom(ComplextEntity.class, bytes2).toString());
|
||||
}
|
||||
ComplextEntity bean = new ComplextEntity();
|
||||
byte[] bytes2 = convert.convertTo(Object.class, bean);
|
||||
final int len = bytes2.length;
|
||||
BsonByteBufferWriter writer = convert.pollWriter(() -> ByteBuffer.allocate(len / 2));
|
||||
convert.convertTo(writer, bean);
|
||||
bytes2 = writer.toArray();
|
||||
System.out.println(convert.convertFrom(ComplextEntity.class, bytes2).toString());
|
||||
Assertions.assertEquals(
|
||||
"{\"chname\":\"\",\"flag\":true,\"userid\":0}",
|
||||
convert.convertFrom(ComplextEntity.class, bytes2).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run4() 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);
|
||||
SimpleEntity rs = convert.convertFrom(SimpleEntity.class, new ByteArrayInputStream(bytes));
|
||||
System.out.println(rs.toString());
|
||||
Assertions.assertEquals(JsonConvert.root().convertTo(entry), rs.toString());
|
||||
}
|
||||
@Test
|
||||
public void run4() 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);
|
||||
SimpleEntity rs = convert.convertFrom(SimpleEntity.class, new ByteArrayInputStream(bytes));
|
||||
System.out.println(rs.toString());
|
||||
Assertions.assertEquals(JsonConvert.root().convertTo(entry), rs.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run5() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
@Test
|
||||
public void run5() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
|
||||
LinkedHashMap map = new LinkedHashMap();
|
||||
map.put("1", 1);
|
||||
map.put("2", "a2");
|
||||
byte[] bs = convert.convertTo(Object.class, map);
|
||||
Object mapobj = convert.convertFrom(Object.class, bs);
|
||||
System.out.println(mapobj);
|
||||
Assertions.assertEquals("{1=1, 2=a2}", mapobj.toString());
|
||||
}
|
||||
LinkedHashMap map = new LinkedHashMap();
|
||||
map.put("1", 1);
|
||||
map.put("2", "a2");
|
||||
byte[] bs = convert.convertTo(Object.class, map);
|
||||
Object mapobj = convert.convertFrom(Object.class, bs);
|
||||
System.out.println(mapobj);
|
||||
Assertions.assertEquals("{1=1, 2=a2}", mapobj.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run6() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
@Test
|
||||
public void run6() throws Exception {
|
||||
final BsonConvert convert = BsonFactory.root().getConvert();
|
||||
|
||||
Optional<String> val = Optional.ofNullable("haha");
|
||||
byte[] bs = convert.convertTo(val);
|
||||
Object obj = convert.convertFrom(Optional.class, bs);
|
||||
System.out.println(obj);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
bs = convert.convertTo(Object.class, val);
|
||||
obj = convert.convertFrom(Object.class, bs);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
bs = convert.convertTo(new TypeToken<Optional<String>>() {}.getType(), val);
|
||||
obj = convert.convertFrom(new TypeToken<Optional<String>>() {}.getType(), bs);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
System.out.println(JsonConvert.root().convertTo(val));
|
||||
Assertions.assertEquals("\"haha\"", JsonConvert.root().convertTo(val));
|
||||
}
|
||||
Optional<String> val = Optional.ofNullable("haha");
|
||||
byte[] bs = convert.convertTo(val);
|
||||
Object obj = convert.convertFrom(Optional.class, bs);
|
||||
System.out.println(obj);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
bs = convert.convertTo(Object.class, val);
|
||||
obj = convert.convertFrom(Object.class, bs);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
bs = convert.convertTo(new TypeToken<Optional<String>>() {}.getType(), val);
|
||||
obj = convert.convertFrom(new TypeToken<Optional<String>>() {}.getType(), bs);
|
||||
Assertions.assertEquals("Optional[haha]", obj.toString());
|
||||
System.out.println(JsonConvert.root().convertTo(val));
|
||||
Assertions.assertEquals("\"haha\"", JsonConvert.root().convertTo(val));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run7() throws Throwable {
|
||||
Two two = new Two();
|
||||
two.setKey("key111");
|
||||
two.setCode(12345);
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("haha");
|
||||
two.setList(list);
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("222", "333");
|
||||
two.setStringMap(map);
|
||||
@Test
|
||||
public void run7() throws Throwable {
|
||||
Two two = new Two();
|
||||
two.setKey("key111");
|
||||
two.setCode(12345);
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("haha");
|
||||
two.setList(list);
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("222", "333");
|
||||
two.setStringMap(map);
|
||||
|
||||
List<ConvertRecord> records = new ArrayList<>();
|
||||
records.add(ConvertRecord.createDefault());
|
||||
two.setRecords(records);
|
||||
List<ConvertRecord> records = new ArrayList<>();
|
||||
records.add(ConvertRecord.createDefault());
|
||||
two.setRecords(records);
|
||||
|
||||
Map<String, ConvertRecord> rmap = new HashMap<>();
|
||||
rmap.put("222", ConvertRecord.createDefault());
|
||||
two.setRecordMap(rmap);
|
||||
Map<String, ConvertRecord> rmap = new HashMap<>();
|
||||
rmap.put("222", ConvertRecord.createDefault());
|
||||
two.setRecordMap(rmap);
|
||||
|
||||
byte[] bs = BsonFactory.root().getConvert().convertTo(two);
|
||||
byte[] bs = BsonFactory.root().getConvert().convertTo(two);
|
||||
|
||||
One one = BsonFactory.root().getConvert().convertFrom(One.class, bs);
|
||||
System.out.println(one);
|
||||
Assertions.assertEquals(
|
||||
"{\"bytes\":[3,4,5],\"code\":12345,\"ints\":[3000,4000,5000],\"key\":\"key111\"}", one.toString());
|
||||
}
|
||||
One one = BsonFactory.root().getConvert().convertFrom(One.class, bs);
|
||||
System.out.println(one);
|
||||
Assertions.assertEquals(
|
||||
"{\"bytes\":[3,4,5],\"code\":12345,\"ints\":[3000,4000,5000],\"key\":\"key111\"}", one.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run8() throws Exception {
|
||||
final JsonConvert jsonConvert = JsonConvert.root();
|
||||
final BsonConvert bsonConvert = BsonFactory.root().getConvert();
|
||||
ConstructorArgsEntity bean = new ConstructorArgsEntity(12345678, "哈哈");
|
||||
bean.setCreatetime(12345678901L);
|
||||
String json = jsonConvert.convertTo(bean);
|
||||
System.out.println(json);
|
||||
Assertions.assertEquals("{\"createtime\":12345678901,\"name\":\"哈哈\",\"userid\":12345678}", json);
|
||||
Assertions.assertEquals(
|
||||
jsonConvert.convertFrom(ConstructorArgsEntity.class, json).toString(), json);
|
||||
byte[] bytes = bsonConvert.convertTo(bean);
|
||||
Assertions.assertEquals(
|
||||
bsonConvert.convertFrom(ConstructorArgsEntity.class, bytes).toString(), json);
|
||||
}
|
||||
@Test
|
||||
public void run8() throws Exception {
|
||||
final JsonConvert jsonConvert = JsonConvert.root();
|
||||
final BsonConvert bsonConvert = BsonFactory.root().getConvert();
|
||||
ConstructorArgsEntity bean = new ConstructorArgsEntity(12345678, "哈哈");
|
||||
bean.setCreatetime(12345678901L);
|
||||
String json = jsonConvert.convertTo(bean);
|
||||
System.out.println(json);
|
||||
Assertions.assertEquals("{\"createtime\":12345678901,\"name\":\"哈哈\",\"userid\":12345678}", json);
|
||||
Assertions.assertEquals(
|
||||
jsonConvert.convertFrom(ConstructorArgsEntity.class, json).toString(), json);
|
||||
byte[] bytes = bsonConvert.convertTo(bean);
|
||||
Assertions.assertEquals(
|
||||
bsonConvert.convertFrom(ConstructorArgsEntity.class, bytes).toString(), json);
|
||||
}
|
||||
|
||||
public static class ComplextEntity {
|
||||
public static class ComplextEntity {
|
||||
|
||||
@Id
|
||||
private int userid;
|
||||
@Id
|
||||
private int userid;
|
||||
|
||||
private String chname = "";
|
||||
private String chname = "";
|
||||
|
||||
@Transient
|
||||
private boolean flag = true;
|
||||
@Transient
|
||||
private boolean flag = true;
|
||||
|
||||
@Transient
|
||||
private List<SimpleChildEntity> children;
|
||||
@Transient
|
||||
private List<SimpleChildEntity> children;
|
||||
|
||||
@Transient
|
||||
private SimpleEntity user;
|
||||
@Transient
|
||||
private SimpleEntity user;
|
||||
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getChname() {
|
||||
return chname;
|
||||
}
|
||||
public String getChname() {
|
||||
return chname;
|
||||
}
|
||||
|
||||
public void setChname(String chname) {
|
||||
this.chname = chname;
|
||||
}
|
||||
public void setChname(String chname) {
|
||||
this.chname = chname;
|
||||
}
|
||||
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setFlag(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
public void setFlag(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
public List<SimpleChildEntity> getChildren() {
|
||||
return children;
|
||||
}
|
||||
public List<SimpleChildEntity> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
public void setChildren(List<SimpleChildEntity> children) {
|
||||
this.children = children;
|
||||
}
|
||||
public void setChildren(List<SimpleChildEntity> children) {
|
||||
this.children = children;
|
||||
}
|
||||
|
||||
public SimpleEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
public SimpleEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(SimpleEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
public void setUser(SimpleEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConstructorArgsEntity {
|
||||
public static class ConstructorArgsEntity {
|
||||
|
||||
private final int userid;
|
||||
private final int userid;
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private long createtime;
|
||||
private long createtime;
|
||||
|
||||
@ConstructorParameters({"userid", "name"})
|
||||
public ConstructorArgsEntity(int userid, String name) {
|
||||
this.userid = userid;
|
||||
this.name = name;
|
||||
}
|
||||
@ConstructorParameters({"userid", "name"})
|
||||
public ConstructorArgsEntity(int userid, String name) {
|
||||
this.userid = userid;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,74 +13,74 @@ import org.redkale.convert.json.JsonConvert;
|
||||
/** @author zhangjx */
|
||||
public class ConvertCoderTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ConvertCoderTest test = new ConvertCoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ConvertCoderTest test = new ConvertCoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
BigMessage msg = new BigMessage();
|
||||
msg.big = new BigInteger("255");
|
||||
msg.big2 = new BigInteger("255");
|
||||
msg.big3 = new BigInteger("255");
|
||||
msg.map = new HashMap<>();
|
||||
msg.map.put("haha", new BigInteger("254"));
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
BigMessage msg = new BigMessage();
|
||||
msg.big = new BigInteger("255");
|
||||
msg.big2 = new BigInteger("255");
|
||||
msg.big3 = new BigInteger("255");
|
||||
msg.map = new HashMap<>();
|
||||
msg.map.put("haha", new BigInteger("254"));
|
||||
|
||||
BigMessage2 msg2 = new BigMessage2();
|
||||
msg2.big = new BigInteger("255");
|
||||
msg2.big2 = new BigInteger("255");
|
||||
msg2.big3 = new BigInteger("255");
|
||||
msg2.map = new HashMap<>();
|
||||
msg2.map.put("haha", new BigInteger("254"));
|
||||
BigMessage2 msg2 = new BigMessage2();
|
||||
msg2.big = new BigInteger("255");
|
||||
msg2.big2 = new BigInteger("255");
|
||||
msg2.big3 = new BigInteger("255");
|
||||
msg2.map = new HashMap<>();
|
||||
msg2.map.put("haha", new BigInteger("254"));
|
||||
|
||||
System.out.println(convert.convertTo(msg));
|
||||
String json = "{\"big\":\"0xff\",\"big2\":\"0xff\",\"big3\":\"255\",\"map\":{\"haha\":\"0xfe\"},\"num1\":0}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(convert.convertTo(msg), json);
|
||||
}
|
||||
BigMessage msg12 = convert.convertFrom(BigMessage.class, json);
|
||||
if (!main) {
|
||||
Assertions.assertEquals(convert.convertTo(msg12), json);
|
||||
}
|
||||
System.out.println(convert.convertTo(msg));
|
||||
String json = "{\"big\":\"0xff\",\"big2\":\"0xff\",\"big3\":\"255\",\"map\":{\"haha\":\"0xfe\"},\"num1\":0}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(convert.convertTo(msg), json);
|
||||
}
|
||||
BigMessage msg12 = convert.convertFrom(BigMessage.class, json);
|
||||
if (!main) {
|
||||
Assertions.assertEquals(convert.convertTo(msg12), json);
|
||||
}
|
||||
|
||||
byte[] bs1 = BsonConvert.root().convertTo(msg);
|
||||
byte[] bs2 = BsonConvert.root().convertTo(msg2);
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
}
|
||||
}
|
||||
byte[] bs1 = BsonConvert.root().convertTo(msg);
|
||||
byte[] bs2 = BsonConvert.root().convertTo(msg2);
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
}
|
||||
}
|
||||
|
||||
public static class BigMessage {
|
||||
public static class BigMessage {
|
||||
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public BigInteger big;
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public BigInteger big;
|
||||
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public BigInteger big2;
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public BigInteger big2;
|
||||
|
||||
public BigInteger big3;
|
||||
public BigInteger big3;
|
||||
|
||||
public int num1;
|
||||
public int num1;
|
||||
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public Map<String, BigInteger> map;
|
||||
}
|
||||
@ConvertCoder(encoder = BigIntegerHexJsonSimpledCoder.class, decoder = BigIntegerHexJsonSimpledCoder.class)
|
||||
public Map<String, BigInteger> map;
|
||||
}
|
||||
|
||||
public static class BigMessage2 {
|
||||
public static class BigMessage2 {
|
||||
|
||||
public BigInteger big;
|
||||
public BigInteger big;
|
||||
|
||||
public BigInteger big2;
|
||||
public BigInteger big2;
|
||||
|
||||
public BigInteger big3;
|
||||
public BigInteger big3;
|
||||
|
||||
public int num1;
|
||||
public int num1;
|
||||
|
||||
public Map<String, BigInteger> map;
|
||||
}
|
||||
public Map<String, BigInteger> map;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,30 +12,30 @@ import org.redkale.convert.json.JsonConvert;
|
||||
/** @author zhangjx */
|
||||
public class ConvertImplTest {
|
||||
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
String json = "{'name':'hellow'}";
|
||||
OneEntity one = JsonConvert.root().convertFrom(OneEntity.class, json);
|
||||
Assertions.assertTrue(one instanceof OneImpl);
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
String json = "{'name':'hellow'}";
|
||||
OneEntity one = JsonConvert.root().convertFrom(OneEntity.class, json);
|
||||
Assertions.assertTrue(one instanceof OneImpl);
|
||||
}
|
||||
|
||||
@ConvertImpl(OneImpl.class)
|
||||
public static interface OneEntity {
|
||||
@ConvertImpl(OneImpl.class)
|
||||
public static interface OneEntity {
|
||||
|
||||
public String getName();
|
||||
}
|
||||
public String getName();
|
||||
}
|
||||
|
||||
public static class OneImpl implements OneEntity {
|
||||
public static class OneImpl implements OneEntity {
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
@Override
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,146 +10,146 @@ import java.util.*;
|
||||
/** @author redkale */
|
||||
public class ConvertRecord {
|
||||
|
||||
private String aname;
|
||||
private String aname;
|
||||
|
||||
private String desc = "";
|
||||
private String desc = "";
|
||||
|
||||
private int id = (int) System.currentTimeMillis();
|
||||
private int id = (int) System.currentTimeMillis();
|
||||
|
||||
private int[] integers;
|
||||
private int[] integers;
|
||||
|
||||
private long[] longs;
|
||||
private long[] longs;
|
||||
|
||||
private List<String> strings;
|
||||
private List<String> strings;
|
||||
|
||||
private Map<String, Integer> map;
|
||||
private Map<String, Integer> 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<String> list = new ArrayList<>();
|
||||
list.add("str_a");
|
||||
list.add("str_b");
|
||||
list.add("str_c");
|
||||
v.setStrings(list);
|
||||
Map<String, Integer> 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 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<String> list = new ArrayList<>();
|
||||
list.add("str_a");
|
||||
list.add("str_b");
|
||||
list.add("str_c");
|
||||
v.setStrings(list);
|
||||
Map<String, Integer> 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 main(String[] args) throws Exception {
|
||||
final ConvertRecord entry = ConvertRecord.createDefault();
|
||||
run(ConvertRecord.class, entry);
|
||||
}
|
||||
|
||||
public static <T> void run(final Class<T> 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));
|
||||
*
|
||||
* <p>com.alibaba.fastjson.JSON.parseObject(entryString, type); System.out.println("fastjson 1.2.7: " +
|
||||
* com.alibaba.fastjson.JSON.toJSONString(entry));
|
||||
*
|
||||
* <p>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));
|
||||
*
|
||||
* <p>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));
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>s = System.currentTimeMillis(); for (int i = 0; i < count; i++) { convert.convertFrom(type, entryString);
|
||||
* } e = System.currentTimeMillis() - s; System.out.println("\t " + e);
|
||||
*
|
||||
* <p>//---------------------------------------------------------------------------- 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);
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>s = System.currentTimeMillis(); for (int i = 0; i < count; i++) { gson.fromJson(entryString, type); } e =
|
||||
* System.currentTimeMillis() - s; System.out.println("\t " + e);
|
||||
* //----------------------------------------------------------------------------
|
||||
*/
|
||||
}
|
||||
public static <T> void run(final Class<T> 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));
|
||||
*
|
||||
* <p>com.alibaba.fastjson.JSON.parseObject(entryString, type); System.out.println("fastjson 1.2.7: " +
|
||||
* com.alibaba.fastjson.JSON.toJSONString(entry));
|
||||
*
|
||||
* <p>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));
|
||||
*
|
||||
* <p>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));
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>s = System.currentTimeMillis(); for (int i = 0; i < count; i++) { convert.convertFrom(type, entryString);
|
||||
* } e = System.currentTimeMillis() - s; System.out.println("\t " + e);
|
||||
*
|
||||
* <p>//---------------------------------------------------------------------------- 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);
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>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);
|
||||
*
|
||||
* <p>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 String getAname() {
|
||||
return aname;
|
||||
}
|
||||
|
||||
public void setAname(String aname) {
|
||||
this.aname = aname;
|
||||
}
|
||||
public void setAname(String aname) {
|
||||
this.aname = aname;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int[] getIntegers() {
|
||||
return integers;
|
||||
}
|
||||
public int[] getIntegers() {
|
||||
return integers;
|
||||
}
|
||||
|
||||
public void setIntegers(int[] integers) {
|
||||
this.integers = integers;
|
||||
}
|
||||
public void setIntegers(int[] integers) {
|
||||
this.integers = integers;
|
||||
}
|
||||
|
||||
public long[] getLongs() {
|
||||
return longs;
|
||||
}
|
||||
public long[] getLongs() {
|
||||
return longs;
|
||||
}
|
||||
|
||||
public void setLongs(long[] longs) {
|
||||
this.longs = longs;
|
||||
}
|
||||
public void setLongs(long[] longs) {
|
||||
this.longs = longs;
|
||||
}
|
||||
|
||||
public List<String> getStrings() {
|
||||
return strings;
|
||||
}
|
||||
public List<String> getStrings() {
|
||||
return strings;
|
||||
}
|
||||
|
||||
public void setStrings(List<String> strings) {
|
||||
this.strings = strings;
|
||||
}
|
||||
public void setStrings(List<String> strings) {
|
||||
this.strings = strings;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getMap() {
|
||||
return map;
|
||||
}
|
||||
public Map<String, Integer> getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map<String, Integer> map) {
|
||||
this.map = map;
|
||||
}
|
||||
public void setMap(Map<String, Integer> map) {
|
||||
this.map = map;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,202 +15,202 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class CustMessage2Test {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CustMessage2Test test = new CustMessage2Test();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CustMessage2Test test = new CustMessage2Test();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
System.out.println(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
System.out.println(msg2);
|
||||
if (!main) Assertions.assertEquals(msg1.toString(), msg2.toString());
|
||||
System.out.println();
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
System.out.println(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
System.out.println(msg2);
|
||||
if (!main) Assertions.assertEquals(msg1.toString(), msg2.toString());
|
||||
System.out.println();
|
||||
|
||||
String json = msg1.toString();
|
||||
OnPlayerLeaveMessage2 newmsg2 = JsonConvert.root().convertFrom(OnPlayerLeaveMessage2.class, json);
|
||||
System.out.println(newmsg2);
|
||||
System.out.println();
|
||||
String json = msg1.toString();
|
||||
OnPlayerLeaveMessage2 newmsg2 = JsonConvert.root().convertFrom(OnPlayerLeaveMessage2.class, json);
|
||||
System.out.println(newmsg2);
|
||||
System.out.println();
|
||||
|
||||
JsonConvert convert = JsonConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(convert.convertTo(msg1));
|
||||
System.out.println(convert.convertTo(msg2));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(msg1), convert.convertTo(msg2));
|
||||
}
|
||||
JsonConvert convert = JsonConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(convert.convertTo(msg1));
|
||||
System.out.println(convert.convertTo(msg2));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(msg1), convert.convertTo(msg2));
|
||||
}
|
||||
|
||||
public static interface BaseMessage {
|
||||
public static interface BaseMessage {
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
|
||||
String value();
|
||||
}
|
||||
String value();
|
||||
}
|
||||
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectEncoder encoder = new ObjectEncoder<Writer, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
EnMember member1 = new EnMember(attribute1, factory.loadEncoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachEnMember(factory, member1);
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectEncoder encoder = new ObjectEncoder<Writer, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
EnMember member1 = new EnMember(attribute1, factory.loadEncoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachEnMember(factory, member1);
|
||||
|
||||
Function func2 = t -> t;
|
||||
Attribute attribute2 = Attribute.create(clazz, "result", clazz, func2, null);
|
||||
EnMember member2 = new EnMember(attribute2, valEncoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachEnMember(factory, member2);
|
||||
this.members = new EnMember[] {member1, member2};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
Function func2 = t -> t;
|
||||
Attribute attribute2 = Attribute.create(clazz, "result", clazz, func2, null);
|
||||
EnMember member2 = new EnMember(attribute2, valEncoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachEnMember(factory, member2);
|
||||
this.members = new EnMember[] {member1, member2};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectDecoder decoder = new ObjectDecoder<Reader, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
DeMember member1 = new DeMember(attribute1, factory.loadDecoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachDeMember(factory, member1);
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectDecoder decoder = new ObjectDecoder<Reader, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
DeMember member1 = new DeMember(attribute1, factory.loadDecoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachDeMember(factory, member1);
|
||||
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func2 = t -> t;
|
||||
BiConsumer consumer2 = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute2 = Attribute.create(clazz, "result", clazz, func2, consumer2);
|
||||
DeMember member2 = new DeMember(attribute2, valDecoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachDeMember(factory, member2);
|
||||
this.members = new DeMember[] {member1, member2};
|
||||
}
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func2 = t -> t;
|
||||
BiConsumer consumer2 = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute2 = Attribute.create(clazz, "result", clazz, func2, consumer2);
|
||||
DeMember member2 = new DeMember(attribute2, valDecoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachDeMember(factory, member2);
|
||||
this.members = new DeMember[] {member1, member2};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseMessage convertFrom(Reader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BaseMessage convertFrom(Reader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveMessage {
|
||||
public static class OnPlayerLeaveMessage {
|
||||
|
||||
private String event = "onPlayerLeaveMessage";
|
||||
private String event = "onPlayerLeaveMessage";
|
||||
|
||||
private OnPlayerLeaveContent result;
|
||||
private OnPlayerLeaveContent result;
|
||||
|
||||
public OnPlayerLeaveMessage() {}
|
||||
public OnPlayerLeaveMessage() {}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.result = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.result = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.result = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.result = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent getResult() {
|
||||
return result;
|
||||
}
|
||||
public OnPlayerLeaveContent getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setResult(OnPlayerLeaveContent result) {
|
||||
this.result = result;
|
||||
}
|
||||
public void setResult(OnPlayerLeaveContent result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveContent {
|
||||
public static class OnPlayerLeaveContent {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveContent() {}
|
||||
public OnPlayerLeaveContent() {}
|
||||
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,174 +15,174 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class CustMessageTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CustMessageTest test = new CustMessageTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
CustMessageTest test = new CustMessageTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
System.out.println(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
System.out.println(msg2);
|
||||
if (!main) Assertions.assertEquals(msg1.toString(), msg2.toString());
|
||||
System.out.println();
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
System.out.println(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
System.out.println(msg2);
|
||||
if (!main) Assertions.assertEquals(msg1.toString(), msg2.toString());
|
||||
System.out.println();
|
||||
|
||||
String json = msg1.toString();
|
||||
OnPlayerLeaveMessage2 newmsg2 = JsonConvert.root().convertFrom(OnPlayerLeaveMessage2.class, json);
|
||||
System.out.println(newmsg2);
|
||||
System.out.println();
|
||||
String json = msg1.toString();
|
||||
OnPlayerLeaveMessage2 newmsg2 = JsonConvert.root().convertFrom(OnPlayerLeaveMessage2.class, json);
|
||||
System.out.println(newmsg2);
|
||||
System.out.println();
|
||||
|
||||
JsonConvert convert = JsonConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(convert.convertTo(msg1));
|
||||
System.out.println(convert.convertTo(msg2));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(msg1), convert.convertTo(msg2));
|
||||
}
|
||||
JsonConvert convert = JsonConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(convert.convertTo(msg1));
|
||||
System.out.println(convert.convertTo(msg2));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(msg1), convert.convertTo(msg2));
|
||||
}
|
||||
|
||||
public static interface BaseMessage {
|
||||
public static interface BaseMessage {
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
|
||||
String value();
|
||||
}
|
||||
String value();
|
||||
}
|
||||
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(ConvertFactory factory, Class<?> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
ObjectEncoder encoder = new ObjectEncoder<Writer, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func = t -> t;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, null);
|
||||
EnMember member = new EnMember(attribute, valEncoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachEnMember(factory, member);
|
||||
this.members = new EnMember[] {member};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(ConvertFactory factory, Class<?> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
ObjectEncoder encoder = new ObjectEncoder<Writer, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func = t -> t;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, null);
|
||||
EnMember member = new EnMember(attribute, valEncoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachEnMember(factory, member);
|
||||
this.members = new EnMember[] {member};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(ConvertFactory factory, Class<?> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
ObjectDecoder decoder = new ObjectDecoder<Reader, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func = t -> t;
|
||||
BiConsumer consumer = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, consumer);
|
||||
DeMember member = new DeMember(attribute, valDecoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachDeMember(factory, member);
|
||||
this.members = new DeMember[] {member};
|
||||
}
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(ConvertFactory factory, Class<?> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
ObjectDecoder decoder = new ObjectDecoder<Reader, BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func = t -> t;
|
||||
BiConsumer consumer = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, consumer);
|
||||
DeMember member = new DeMember(attribute, valDecoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachDeMember(factory, member);
|
||||
this.members = new DeMember[] {member};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseMessage convertFrom(Reader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BaseMessage convertFrom(Reader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveMessage {
|
||||
public static class OnPlayerLeaveMessage {
|
||||
|
||||
private OnPlayerLeaveContent onPlayerLeaveMessage;
|
||||
private OnPlayerLeaveContent onPlayerLeaveMessage;
|
||||
|
||||
public OnPlayerLeaveMessage() {}
|
||||
public OnPlayerLeaveMessage() {}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
|
||||
return onPlayerLeaveMessage;
|
||||
}
|
||||
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
|
||||
return onPlayerLeaveMessage;
|
||||
}
|
||||
|
||||
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
|
||||
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
|
||||
}
|
||||
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
|
||||
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveContent {
|
||||
public static class OnPlayerLeaveContent {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveContent() {}
|
||||
public OnPlayerLeaveContent() {}
|
||||
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,53 +12,53 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class DyncJsonTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
DyncJsonTest test = new DyncJsonTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
DyncJsonTest test = new DyncJsonTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
SimpleDyncBean bean = new SimpleDyncBean();
|
||||
bean.name = "haha";
|
||||
System.out.println(JsonConvert.root().convertTo(bean));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean));
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
SimpleDyncBean bean = new SimpleDyncBean();
|
||||
bean.name = "haha";
|
||||
System.out.println(JsonConvert.root().convertTo(bean));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean));
|
||||
|
||||
SimpleDyncBean2 bean2 = new SimpleDyncBean2();
|
||||
bean2.name = "haha";
|
||||
SimpleDyncBean2 bean2 = new SimpleDyncBean2();
|
||||
bean2.name = "haha";
|
||||
|
||||
System.out.println(JsonConvert.root().convertTo(bean2));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean2));
|
||||
SimpleDyncBean3 bean3 = new SimpleDyncBean3();
|
||||
bean3.name = "haha";
|
||||
System.out.println(JsonConvert.root().convertTo(bean3));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean3));
|
||||
}
|
||||
System.out.println(JsonConvert.root().convertTo(bean2));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean2));
|
||||
SimpleDyncBean3 bean3 = new SimpleDyncBean3();
|
||||
bean3.name = "haha";
|
||||
System.out.println(JsonConvert.root().convertTo(bean3));
|
||||
if (!main)
|
||||
Assertions.assertEquals("{\"name\":\"haha\"}", JsonConvert.root().convertTo(bean3));
|
||||
}
|
||||
|
||||
public static class SimpleDyncBean {
|
||||
public static class SimpleDyncBean {
|
||||
|
||||
public String name;
|
||||
public String name;
|
||||
|
||||
public List<SimpleDyncBean> beans;
|
||||
}
|
||||
public List<SimpleDyncBean> beans;
|
||||
}
|
||||
|
||||
public static class SimpleDyncBean2 {
|
||||
public static class SimpleDyncBean2 {
|
||||
|
||||
public String name;
|
||||
public String name;
|
||||
|
||||
public SimpleDyncBean2 bean2;
|
||||
}
|
||||
public SimpleDyncBean2 bean2;
|
||||
}
|
||||
|
||||
public static class SimpleDyncBean3 {
|
||||
public static class SimpleDyncBean3 {
|
||||
|
||||
public String name;
|
||||
public String name;
|
||||
|
||||
public Map<String, SimpleDyncBean3> beanmap;
|
||||
}
|
||||
public Map<String, SimpleDyncBean3> beanmap;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,49 +11,49 @@ import org.redkale.convert.json.JsonConvert;
|
||||
/** @author zhangjx */
|
||||
public class EnumBeanTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
EnumBeanTest test = new EnumBeanTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
EnumBeanTest test = new EnumBeanTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
EnumBean bean = new EnumBean();
|
||||
bean.v1 = EnumKey.TWO;
|
||||
bean.v2 = 5;
|
||||
String expect = "{\"v1\":2,\"v2\":5}";
|
||||
String json = JsonConvert.root().convertTo(bean);
|
||||
if (!main) Assertions.assertEquals(expect, json);
|
||||
System.out.println(json);
|
||||
EnumBean b = JsonConvert.root().convertFrom(EnumBean.class, json);
|
||||
String js = JsonConvert.root().convertTo(b);
|
||||
System.out.println(js);
|
||||
if (!main) Assertions.assertEquals(expect, js);
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
EnumBean bean = new EnumBean();
|
||||
bean.v1 = EnumKey.TWO;
|
||||
bean.v2 = 5;
|
||||
String expect = "{\"v1\":2,\"v2\":5}";
|
||||
String json = JsonConvert.root().convertTo(bean);
|
||||
if (!main) Assertions.assertEquals(expect, json);
|
||||
System.out.println(json);
|
||||
EnumBean b = JsonConvert.root().convertFrom(EnumBean.class, json);
|
||||
String js = JsonConvert.root().convertTo(b);
|
||||
System.out.println(js);
|
||||
if (!main) Assertions.assertEquals(expect, js);
|
||||
}
|
||||
|
||||
public static class EnumBean {
|
||||
public static class EnumBean {
|
||||
|
||||
public EnumKey v1;
|
||||
public EnumKey v1;
|
||||
|
||||
public int v2;
|
||||
}
|
||||
public int v2;
|
||||
}
|
||||
|
||||
@ConvertEnumValue("code")
|
||||
public static enum EnumKey {
|
||||
ONE(1),
|
||||
TWO(2);
|
||||
@ConvertEnumValue("code")
|
||||
public static enum EnumKey {
|
||||
ONE(1),
|
||||
TWO(2);
|
||||
|
||||
private final int code;
|
||||
private final int code;
|
||||
|
||||
private EnumKey(int v) {
|
||||
this.code = v;
|
||||
}
|
||||
private EnumKey(int v) {
|
||||
this.code = v;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,41 +11,41 @@ import org.redkale.persistence.Id;
|
||||
/** @author zhangjx */
|
||||
public class Fortune implements Comparable<Fortune> {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
private String message = "";
|
||||
private String message = "";
|
||||
|
||||
public Fortune() {}
|
||||
public Fortune() {}
|
||||
|
||||
public Fortune(int id, String message) {
|
||||
this.id = id;
|
||||
this.message = message;
|
||||
}
|
||||
public Fortune(int id, String message) {
|
||||
this.id = id;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Fortune o) {
|
||||
return message.compareTo(o.message);
|
||||
}
|
||||
@Override
|
||||
public int compareTo(Fortune o) {
|
||||
return message.compareTo(o.message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,87 +20,87 @@ import org.redkale.util.TypeToken;
|
||||
*/
|
||||
public class GenericEntity<T, K, V> {
|
||||
|
||||
private K name;
|
||||
private K name;
|
||||
|
||||
private List<? extends T> list;
|
||||
private List<? extends T> list;
|
||||
|
||||
private Entry<K, V> entry;
|
||||
private Entry<K, V> entry;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
GenericEntity<Long, String, SimpleEntity> bean = new GenericEntity<>();
|
||||
bean.setName("你好");
|
||||
List<Long> list = new ArrayList<>();
|
||||
list.add(1234567890L);
|
||||
bean.setList(list);
|
||||
bean.setEntry(new Entry<>("aaaa", SimpleEntity.create()));
|
||||
final Type type = new TypeToken<GenericEntity<Long, String, SimpleEntity>>() {}.getType();
|
||||
JsonFactory.root().withTinyFeature(true);
|
||||
String json = JsonConvert.root().convertTo(bean);
|
||||
System.out.println(json);
|
||||
System.out.println(JsonConvert.root().convertFrom(type, json).toString());
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
GenericEntity<Long, String, SimpleEntity> bean = new GenericEntity<>();
|
||||
bean.setName("你好");
|
||||
List<Long> list = new ArrayList<>();
|
||||
list.add(1234567890L);
|
||||
bean.setList(list);
|
||||
bean.setEntry(new Entry<>("aaaa", SimpleEntity.create()));
|
||||
final Type type = new TypeToken<GenericEntity<Long, String, SimpleEntity>>() {}.getType();
|
||||
JsonFactory.root().withTinyFeature(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 + "\"}";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"entry\":" + entry + ",\"list\":" + list + ",\"name\":\"" + name + "\"}";
|
||||
}
|
||||
|
||||
public K getName() {
|
||||
return name;
|
||||
}
|
||||
public K getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(K name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(K name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public List<? extends T> getList() {
|
||||
return list;
|
||||
}
|
||||
public List<? extends T> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List<? extends T> list) {
|
||||
this.list = list;
|
||||
}
|
||||
public void setList(List<? extends T> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Entry<K, V> getEntry() {
|
||||
return entry;
|
||||
}
|
||||
public Entry<K, V> getEntry() {
|
||||
return entry;
|
||||
}
|
||||
|
||||
public void setEntry(Entry<K, V> entry) {
|
||||
this.entry = entry;
|
||||
}
|
||||
public void setEntry(Entry<K, V> entry) {
|
||||
this.entry = entry;
|
||||
}
|
||||
|
||||
public static class Entry<K, V> {
|
||||
public static class Entry<K, V> {
|
||||
|
||||
private K key;
|
||||
private K key;
|
||||
|
||||
private V value;
|
||||
private V value;
|
||||
|
||||
public Entry() {}
|
||||
public Entry() {}
|
||||
|
||||
public Entry(K key, V value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
public Entry(K key, V value) {
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public K getKey() {
|
||||
return key;
|
||||
}
|
||||
public K getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(K key) {
|
||||
this.key = key;
|
||||
}
|
||||
public void setKey(K key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public V getValue() {
|
||||
return value;
|
||||
}
|
||||
public V getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(V value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
public void setValue(V value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,115 +14,115 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class InnerCoderEntity {
|
||||
|
||||
private final String val;
|
||||
private final String val;
|
||||
|
||||
private final int id;
|
||||
private final int id;
|
||||
|
||||
private InnerCoderEntity(int id, String value) {
|
||||
this.id = id;
|
||||
this.val = value;
|
||||
}
|
||||
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);
|
||||
}
|
||||
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
|
||||
*/
|
||||
static SimpledCoder<Reader, Writer, InnerCoderEntity> createConvertCoder(
|
||||
final org.redkale.convert.ConvertFactory factory) {
|
||||
return new SimpledCoder<Reader, Writer, InnerCoderEntity>() {
|
||||
/**
|
||||
* 该方法提供给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
|
||||
*/
|
||||
static SimpledCoder<Reader, Writer, InnerCoderEntity> createConvertCoder(
|
||||
final org.redkale.convert.ConvertFactory factory) {
|
||||
return new SimpledCoder<Reader, Writer, InnerCoderEntity>() {
|
||||
|
||||
private Map<String, DeMember> deMemberFieldMap;
|
||||
private Map<String, DeMember> deMemberFieldMap;
|
||||
|
||||
private Map<Integer, DeMember> deMemberTagMap;
|
||||
private Map<Integer, DeMember> deMemberTagMap;
|
||||
|
||||
// 必须与EnMember[] 顺序一致
|
||||
private final DeMember[] deMembers = new DeMember[] {
|
||||
DeMember.create(factory, InnerCoderEntity.class, "id"),
|
||||
DeMember.create(factory, InnerCoderEntity.class, "val")
|
||||
};
|
||||
// 必须与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")
|
||||
};
|
||||
// 必须与DeMember[] 顺序一致
|
||||
private final EnMember[] enMembers = new EnMember[] {
|
||||
EnMember.create(factory, InnerCoderEntity.class, "id"),
|
||||
EnMember.create(factory, InnerCoderEntity.class, "val")
|
||||
};
|
||||
|
||||
{
|
||||
this.deMemberFieldMap = new HashMap<>(this.deMembers.length);
|
||||
this.deMemberTagMap = new HashMap<>(this.deMembers.length);
|
||||
for (DeMember member : this.deMembers) {
|
||||
this.deMemberFieldMap.put(member.getAttribute().field(), member);
|
||||
this.deMemberTagMap.put(member.getTag(), member);
|
||||
}
|
||||
}
|
||||
{
|
||||
this.deMemberFieldMap = new HashMap<>(this.deMembers.length);
|
||||
this.deMemberTagMap = new HashMap<>(this.deMembers.length);
|
||||
for (DeMember member : this.deMembers) {
|
||||
this.deMemberFieldMap.put(member.getAttribute().field(), member);
|
||||
this.deMemberTagMap.put(member.getTag(), member);
|
||||
}
|
||||
}
|
||||
|
||||
@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 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, deMemberFieldMap, deMemberTagMap); // 读取字段名
|
||||
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]);
|
||||
}
|
||||
};
|
||||
}
|
||||
@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, deMemberFieldMap, deMemberTagMap); // 读取字段名
|
||||
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 int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getVal() {
|
||||
return val;
|
||||
}
|
||||
public String getVal() {
|
||||
return val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@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());
|
||||
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);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,93 +10,93 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class Json5Test {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Json5Test test = new Json5Test();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Json5Test test = new Json5Test();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
JsonFactory factory = JsonFactory.root().withFeatures(Convert.FEATURE_TINY | Convert.FEATURE_NULLABLE);
|
||||
final JsonConvert convert = factory.getConvert();
|
||||
Json5Bean bean = new Json5Bean();
|
||||
bean.id = 60;
|
||||
System.out.println(convert.convertTo(bean));
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
JsonFactory factory = JsonFactory.root().withFeatures(Convert.FEATURE_TINY | Convert.FEATURE_NULLABLE);
|
||||
final JsonConvert convert = factory.getConvert();
|
||||
Json5Bean bean = new Json5Bean();
|
||||
bean.id = 60;
|
||||
System.out.println(convert.convertTo(bean));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
Json5Bean bean = new Json5Bean();
|
||||
bean.id = 500;
|
||||
bean.decmails = 3.2f;
|
||||
bean.value = 44444;
|
||||
bean.name = "haha";
|
||||
String json = "{/*多行\r\n注释**/\"decmails\":3.2,//单行注释\r\n\"id\":0x1F4,\"name\":\"haha\",\"value\":44444,}";
|
||||
Json5Bean bean2 = convert.convertFrom(Json5Bean.class, json);
|
||||
if (!main) {
|
||||
Assertions.assertTrue(bean.equals(bean2));
|
||||
}
|
||||
System.out.println(convert.convertTo(bean2));
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
Json5Bean bean = new Json5Bean();
|
||||
bean.id = 500;
|
||||
bean.decmails = 3.2f;
|
||||
bean.value = 44444;
|
||||
bean.name = "haha";
|
||||
String json = "{/*多行\r\n注释**/\"decmails\":3.2,//单行注释\r\n\"id\":0x1F4,\"name\":\"haha\",\"value\":44444,}";
|
||||
Json5Bean bean2 = convert.convertFrom(Json5Bean.class, json);
|
||||
if (!main) {
|
||||
Assertions.assertTrue(bean.equals(bean2));
|
||||
}
|
||||
System.out.println(convert.convertTo(bean2));
|
||||
|
||||
String arrayJson = "[" + json + "," + json + "," + "]";
|
||||
Json5Bean[] beans = convert.convertFrom(Json5Bean[].class, arrayJson);
|
||||
System.out.println(convert.convertTo(beans));
|
||||
String arrayJson = "[" + json + "," + json + "," + "]";
|
||||
Json5Bean[] beans = convert.convertFrom(Json5Bean[].class, arrayJson);
|
||||
System.out.println(convert.convertTo(beans));
|
||||
|
||||
String intjson = "[1,2,3,4,]";
|
||||
int[] ints1 = convert.convertFrom(int[].class, intjson);
|
||||
System.out.println(Arrays.toString(ints1));
|
||||
}
|
||||
String intjson = "[1,2,3,4,]";
|
||||
int[] ints1 = convert.convertFrom(int[].class, intjson);
|
||||
System.out.println(Arrays.toString(ints1));
|
||||
}
|
||||
|
||||
public static class Json5Bean {
|
||||
public static class Json5Bean {
|
||||
|
||||
public int id;
|
||||
public int id;
|
||||
|
||||
public float decmails;
|
||||
public float decmails;
|
||||
|
||||
public long value;
|
||||
public long value;
|
||||
|
||||
public String name;
|
||||
public String name;
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 47 * hash + this.id;
|
||||
hash = 47 * hash + Float.floatToIntBits(this.decmails);
|
||||
hash = 47 * hash + (int) (this.value ^ (this.value >>> 32));
|
||||
hash = 47 * hash + Objects.hashCode(this.name);
|
||||
return hash;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 47 * hash + this.id;
|
||||
hash = 47 * hash + Float.floatToIntBits(this.decmails);
|
||||
hash = 47 * hash + (int) (this.value ^ (this.value >>> 32));
|
||||
hash = 47 * hash + Objects.hashCode(this.name);
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Json5Bean other = (Json5Bean) obj;
|
||||
if (this.id != other.id) {
|
||||
return false;
|
||||
}
|
||||
if (Float.floatToIntBits(this.decmails) != Float.floatToIntBits(other.decmails)) {
|
||||
return false;
|
||||
}
|
||||
if (this.value != other.value) {
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(this.name, other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (getClass() != obj.getClass()) {
|
||||
return false;
|
||||
}
|
||||
final Json5Bean other = (Json5Bean) obj;
|
||||
if (this.id != other.id) {
|
||||
return false;
|
||||
}
|
||||
if (Float.floatToIntBits(this.decmails) != Float.floatToIntBits(other.decmails)) {
|
||||
return false;
|
||||
}
|
||||
if (this.value != other.value) {
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(this.name, other.name)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,135 +15,135 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class JsonMainTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMainTest test = new JsonMainTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
test.run4();
|
||||
test.run5();
|
||||
test.run6();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMainTest test = new JsonMainTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
test.run4();
|
||||
test.run5();
|
||||
test.run6();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
JsonFactory factory = JsonFactory.root().withFeatures(Convert.FEATURE_TINY);
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
String json =
|
||||
"{\"access_token\":\"null\",\"priv\":null, vvv:nulla,\"priv2\":\"nulla\",\"expires_in\":7200, \"aa\":\"\"}";
|
||||
Map<String, String> map = convert.convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, json);
|
||||
System.out.println(map);
|
||||
System.out.println(map.get("priv") == null);
|
||||
String rs = convert.convertTo(map);
|
||||
System.out.println(rs);
|
||||
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));
|
||||
Assertions.assertEquals(rs, new String(bs));
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Throwable {
|
||||
JsonFactory factory = JsonFactory.root().withFeatures(Convert.FEATURE_TINY);
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
String json =
|
||||
"{\"access_token\":\"null\",\"priv\":null, vvv:nulla,\"priv2\":\"nulla\",\"expires_in\":7200, \"aa\":\"\"}";
|
||||
Map<String, String> map = convert.convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, json);
|
||||
System.out.println(map);
|
||||
System.out.println(map.get("priv") == null);
|
||||
String rs = convert.convertTo(map);
|
||||
System.out.println(rs);
|
||||
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));
|
||||
Assertions.assertEquals(rs, new String(bs));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
SimpleChildEntity entry = SimpleChildEntity.create();
|
||||
String json = convert.convertTo(SimpleEntity.class, entry);
|
||||
System.out.println("长度: " + json.length());
|
||||
JsonByteBufferWriter writer = new JsonByteBufferWriter(0, () -> 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);
|
||||
}
|
||||
@Test
|
||||
public void run2() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
SimpleChildEntity entry = SimpleChildEntity.create();
|
||||
String json = convert.convertTo(SimpleEntity.class, entry);
|
||||
System.out.println("长度: " + json.length());
|
||||
JsonByteBufferWriter writer = new JsonByteBufferWriter(0, () -> 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);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run3() throws Throwable {
|
||||
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);
|
||||
Map rs = (Map) convert.convertFrom(entry2.toString());
|
||||
System.out.println(convert.convertTo(rs));
|
||||
}
|
||||
@Test
|
||||
public void run3() throws Throwable {
|
||||
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);
|
||||
Map rs = (Map) convert.convertFrom(entry2.toString());
|
||||
System.out.println(convert.convertTo(rs));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run4() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
|
||||
String json = convert.convertTo(date);
|
||||
System.out.println("java.sql.Date 值: " + json);
|
||||
java.sql.Date rs = convert.convertFrom(java.sql.Date.class, json);
|
||||
System.out.println(convert.convertTo(rs));
|
||||
}
|
||||
@Test
|
||||
public void run4() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
|
||||
String json = convert.convertTo(date);
|
||||
System.out.println("java.sql.Date 值: " + json);
|
||||
java.sql.Date rs = convert.convertFrom(java.sql.Date.class, json);
|
||||
System.out.println(convert.convertTo(rs));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run5() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
long v = convert.convertFrom(long.class, "100");
|
||||
Assertions.assertEquals(100, v);
|
||||
}
|
||||
@Test
|
||||
public void run5() throws Throwable {
|
||||
final JsonConvert convert = JsonConvert.root();
|
||||
long v = convert.convertFrom(long.class, "100");
|
||||
Assertions.assertEquals(100, v);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run6() throws Throwable {
|
||||
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"
|
||||
+ " }"
|
||||
+ " ]"
|
||||
+ "}";
|
||||
JsonObject obj = JsonObject.convertFrom(str);
|
||||
JsonObject obj2 = JsonConvert.root().convertFrom(JsonObject.class, str);
|
||||
System.out.println("结果1: " + obj);
|
||||
System.out.println("结果2: " + obj2);
|
||||
System.out.println("结果3: " + JsonConvert.root().convertTo(obj2));
|
||||
Assertions.assertEquals(
|
||||
JsonObject.class.getName(), obj.get("media").getClass().getName());
|
||||
Assertions.assertEquals(
|
||||
JsonArray.class.getName(), obj.get("images").getClass().getName());
|
||||
}
|
||||
@Test
|
||||
public void run6() throws Throwable {
|
||||
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"
|
||||
+ " }"
|
||||
+ " ]"
|
||||
+ "}";
|
||||
JsonObject obj = JsonObject.convertFrom(str);
|
||||
JsonObject obj2 = JsonConvert.root().convertFrom(JsonObject.class, str);
|
||||
System.out.println("结果1: " + obj);
|
||||
System.out.println("结果2: " + obj2);
|
||||
System.out.println("结果3: " + JsonConvert.root().convertTo(obj2));
|
||||
Assertions.assertEquals(
|
||||
JsonObject.class.getName(), obj.get("media").getClass().getName());
|
||||
Assertions.assertEquals(
|
||||
JsonArray.class.getName(), obj.get("images").getClass().getName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,21 +9,21 @@ import org.redkale.convert.json.JsonConvert;
|
||||
/** @author zhangjx */
|
||||
public class JsonMultiDecoderTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMultiDecoderTest test = new JsonMultiDecoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMultiDecoderTest test = new JsonMultiDecoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaa\",{\"name\":\"haha\"}]";
|
||||
Type[] types = new Type[] {String.class, JsonConvert.TYPE_MAP_STRING_STRING};
|
||||
Object[] objs = convert.convertFrom(types, json);
|
||||
System.out.println(convert.convertTo(objs));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(objs), json);
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaa\",{\"name\":\"haha\"}]";
|
||||
Type[] types = new Type[] {String.class, JsonConvert.TYPE_MAP_STRING_STRING};
|
||||
Object[] objs = convert.convertFrom(types, json);
|
||||
System.out.println(convert.convertTo(objs));
|
||||
if (!main) Assertions.assertEquals(convert.convertTo(objs), json);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,111 +9,111 @@ import org.redkale.convert.json.JsonConvert;
|
||||
/** @author zhangjx */
|
||||
public class JsonMultiObjectDecoderTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMultiObjectDecoderTest test = new JsonMultiObjectDecoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonMultiObjectDecoderTest test = new JsonMultiObjectDecoderTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a6\":\"666\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean69.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a2\":\"222\",\"a4\":\"444\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean423.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a6\":\"666\",\"a5\":\"555\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean65.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a6\":\"666\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean69.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a2\":\"222\",\"a4\":\"444\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean423.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
{
|
||||
String json = "{\"a0\":\"000\",\"a6\":\"666\",\"a5\":\"555\"}";
|
||||
AbstractBean bean = JsonConvert.root().convertFrom(AbstractBean.class, json);
|
||||
if (!main) Assertions.assertEquals(bean.getClass().getName(), Bean65.class.getName());
|
||||
System.out.println(bean);
|
||||
}
|
||||
}
|
||||
|
||||
// [{"1", "2", "3"}, {"2", "3"}, {"4", "2", "3"}, {"6", "7", "8"}, {"6", "5"}, {"6", "9"}]
|
||||
@ConvertImpl(types = {Bean123.class, Bean23.class, Bean423.class, Bean678.class, Bean65.class, Bean69.class})
|
||||
public abstract static class AbstractBean {
|
||||
// [{"1", "2", "3"}, {"2", "3"}, {"4", "2", "3"}, {"6", "7", "8"}, {"6", "5"}, {"6", "9"}]
|
||||
@ConvertImpl(types = {Bean123.class, Bean23.class, Bean423.class, Bean678.class, Bean65.class, Bean69.class})
|
||||
public abstract static class AbstractBean {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Bean123 extends AbstractBean {
|
||||
public static class Bean123 extends AbstractBean {
|
||||
|
||||
public String a1;
|
||||
public String a1;
|
||||
|
||||
public String a2;
|
||||
public String a2;
|
||||
|
||||
public String a3;
|
||||
}
|
||||
public String a3;
|
||||
}
|
||||
|
||||
public static class Bean23 extends AbstractBean {
|
||||
public static class Bean23 extends AbstractBean {
|
||||
|
||||
public String a2;
|
||||
public String a2;
|
||||
|
||||
public String a3;
|
||||
}
|
||||
public String a3;
|
||||
}
|
||||
|
||||
public static class Bean423 extends AbstractBean {
|
||||
public static class Bean423 extends AbstractBean {
|
||||
|
||||
public String a4;
|
||||
public String a4;
|
||||
|
||||
public String a2;
|
||||
public String a2;
|
||||
|
||||
public String a3;
|
||||
}
|
||||
public String a3;
|
||||
}
|
||||
|
||||
public static class Bean678 extends AbstractBean {
|
||||
public static class Bean678 extends AbstractBean {
|
||||
|
||||
public String a6;
|
||||
public String a6;
|
||||
|
||||
public String a7;
|
||||
public String a7;
|
||||
|
||||
public String a8;
|
||||
}
|
||||
public String a8;
|
||||
}
|
||||
|
||||
public static class Bean69 extends AbstractBean {
|
||||
public static class Bean69 extends AbstractBean {
|
||||
|
||||
public String a6;
|
||||
public String a6;
|
||||
|
||||
public String a9;
|
||||
public String a9;
|
||||
|
||||
public Bean69(String a9) {
|
||||
this.a9 = a9;
|
||||
}
|
||||
}
|
||||
public Bean69(String a9) {
|
||||
this.a9 = a9;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Bean65 extends AbstractBean {
|
||||
public static class Bean65 extends AbstractBean {
|
||||
|
||||
private String a6;
|
||||
private String a6;
|
||||
|
||||
private String a5;
|
||||
private String a5;
|
||||
|
||||
public Bean65(String a5) {
|
||||
this.a5 = a5;
|
||||
}
|
||||
public Bean65(String a5) {
|
||||
this.a5 = a5;
|
||||
}
|
||||
|
||||
public String getA6() {
|
||||
return a6;
|
||||
}
|
||||
public String getA6() {
|
||||
return a6;
|
||||
}
|
||||
|
||||
public void setA6(String a6) {
|
||||
this.a6 = a6;
|
||||
}
|
||||
public void setA6(String a6) {
|
||||
this.a6 = a6;
|
||||
}
|
||||
|
||||
public String getA5() {
|
||||
return a5;
|
||||
}
|
||||
}
|
||||
public String getA5() {
|
||||
return a5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,196 +15,196 @@ import org.redkale.util.TypeToken;
|
||||
/** @author zhangjx */
|
||||
public class JsonPvBeanTest {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonPvBeanTest test = new JsonPvBeanTest();
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
JsonPvBeanTest test = new JsonPvBeanTest();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
String json = "[\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"首页\",\n"
|
||||
+ " \"cate\": \"home_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"茶室\",\n"
|
||||
+ " \"type\": \"tea\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"桌游\",\n"
|
||||
+ " \"type\": \"board\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"密室\",\n"
|
||||
+ " \"type\": \"escape\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"剧本杀\",\n"
|
||||
+ " \"type\": \"drama\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"PS5/switch\",\n"
|
||||
+ " \"type\": \"ps5\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"电竞\",\n"
|
||||
+ " \"type\": \"game\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"赛事\",\n"
|
||||
+ " \"type\": \"match\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"预约\",\n"
|
||||
+ " \"type\": \"book\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"充值\",\n"
|
||||
+ " \"type\": \"charge\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"福利中心\",\n"
|
||||
+ " \"type\": \"weal\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"福利中心\",\n"
|
||||
+ " \"cate\": \"weal_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"卡券套餐\",\n"
|
||||
+ " \"type\": \"card\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"优惠券\",\n"
|
||||
+ " \"type\": \"coupon\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"充值\",\n"
|
||||
+ " \"type\": \"charge\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"团购\",\n"
|
||||
+ " \"type\": \"group\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"地图找店\",\n"
|
||||
+ " \"cate\": \"map_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"搜索框\",\n"
|
||||
+ " \"type\": \"search\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"店铺详情\",\n"
|
||||
+ " \"type\": \"site\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"城市切换\",\n"
|
||||
+ " \"type\": \"city\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"房间服务\",\n"
|
||||
+ " \"cate\": \"site_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"切换门店\",\n"
|
||||
+ " \"type\": \"venue\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"确认支付\",\n"
|
||||
+ " \"type\": \"pay\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"个人中心\",\n"
|
||||
+ " \"cate\": \"personal_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"会员中心\",\n"
|
||||
+ " \"type\": \"vip\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"余额\",\n"
|
||||
+ " \"type\": \"amount\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"优惠券\",\n"
|
||||
+ " \"type\": \"coupon\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"卡券套餐\",\n"
|
||||
+ " \"type\": \"card\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"积分\",\n"
|
||||
+ " \"type\": \"exp\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " }\n"
|
||||
+ "]\n"
|
||||
+ "";
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
String json = "[\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"首页\",\n"
|
||||
+ " \"cate\": \"home_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"茶室\",\n"
|
||||
+ " \"type\": \"tea\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"桌游\",\n"
|
||||
+ " \"type\": \"board\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"密室\",\n"
|
||||
+ " \"type\": \"escape\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"剧本杀\",\n"
|
||||
+ " \"type\": \"drama\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"PS5/switch\",\n"
|
||||
+ " \"type\": \"ps5\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"电竞\",\n"
|
||||
+ " \"type\": \"game\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"赛事\",\n"
|
||||
+ " \"type\": \"match\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"预约\",\n"
|
||||
+ " \"type\": \"book\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"充值\",\n"
|
||||
+ " \"type\": \"charge\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"福利中心\",\n"
|
||||
+ " \"type\": \"weal\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"福利中心\",\n"
|
||||
+ " \"cate\": \"weal_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"卡券套餐\",\n"
|
||||
+ " \"type\": \"card\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"优惠券\",\n"
|
||||
+ " \"type\": \"coupon\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"充值\",\n"
|
||||
+ " \"type\": \"charge\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"团购\",\n"
|
||||
+ " \"type\": \"group\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"地图找店\",\n"
|
||||
+ " \"cate\": \"map_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"搜索框\",\n"
|
||||
+ " \"type\": \"search\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"店铺详情\",\n"
|
||||
+ " \"type\": \"site\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"城市切换\",\n"
|
||||
+ " \"type\": \"city\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"房间服务\",\n"
|
||||
+ " \"cate\": \"site_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"切换门店\",\n"
|
||||
+ " \"type\": \"venue\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"确认支付\",\n"
|
||||
+ " \"type\": \"pay\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"pagename\": \"个人中心\",\n"
|
||||
+ " \"cate\": \"personal_page\",\n"
|
||||
+ " \"functions\": [\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"会员中心\",\n"
|
||||
+ " \"type\": \"vip\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"余额\",\n"
|
||||
+ " \"type\": \"amount\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"优惠券\",\n"
|
||||
+ " \"type\": \"coupon\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"卡券套餐\",\n"
|
||||
+ " \"type\": \"card\"\n"
|
||||
+ " },\n"
|
||||
+ " {\n"
|
||||
+ " \"functionname\": \"积分\",\n"
|
||||
+ " \"type\": \"exp\"\n"
|
||||
+ " }\n"
|
||||
+ " ]\n"
|
||||
+ " }\n"
|
||||
+ "]\n"
|
||||
+ "";
|
||||
|
||||
List<JsonPvBean> list = null;
|
||||
list = JsonConvert.root().convertFrom(new TypeToken<List<JsonPvBean>>() {}.getType(), json);
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println("-----------------");
|
||||
List<JsonPvBean> list = null;
|
||||
list = JsonConvert.root().convertFrom(new TypeToken<List<JsonPvBean>>() {}.getType(), json);
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println("-----------------");
|
||||
|
||||
list = JsonConvert.root()
|
||||
.convertFrom(
|
||||
new TypeToken<List<JsonPvBean>>() {}.getType(),
|
||||
ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8)));
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println("-----------------");
|
||||
list = JsonConvert.root()
|
||||
.convertFrom(
|
||||
new TypeToken<List<JsonPvBean>>() {}.getType(),
|
||||
ByteBuffer.wrap(json.getBytes(StandardCharsets.UTF_8)));
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println("-----------------");
|
||||
|
||||
InputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
|
||||
list = JsonConvert.root().convertFrom(new TypeToken<List<JsonPvBean>>() {}.getType(), in);
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println(list);
|
||||
}
|
||||
InputStream in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
|
||||
list = JsonConvert.root().convertFrom(new TypeToken<List<JsonPvBean>>() {}.getType(), in);
|
||||
Assertions.assertNotNull(list);
|
||||
Assertions.assertEquals(5, list.size());
|
||||
System.out.println(list);
|
||||
}
|
||||
|
||||
public static class JsonPvBean {
|
||||
public static class JsonPvBean {
|
||||
|
||||
@Comment("页面名称")
|
||||
public String pagename;
|
||||
@Comment("页面名称")
|
||||
public String pagename;
|
||||
|
||||
@Comment("页面类别")
|
||||
public String cate;
|
||||
@Comment("页面类别")
|
||||
public String cate;
|
||||
|
||||
@Comment("页面类别")
|
||||
public String code;
|
||||
@Comment("页面类别")
|
||||
public String code;
|
||||
|
||||
@Comment("页面功能点")
|
||||
public List<Functions> functions;
|
||||
@Comment("页面功能点")
|
||||
public List<Functions> functions;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"pagename\":\"" + pagename + "\",\"cate\":\"" + cate + "\",\"code\":\"" + code
|
||||
+ "\",\"functions\":" + functions + "}";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"pagename\":\"" + pagename + "\",\"cate\":\"" + cate + "\",\"code\":\"" + code
|
||||
+ "\",\"functions\":" + functions + "}";
|
||||
}
|
||||
|
||||
public static class Functions {
|
||||
public static class Functions {
|
||||
|
||||
@Comment("功能名称")
|
||||
public String functionname;
|
||||
@Comment("功能名称")
|
||||
public String functionname;
|
||||
|
||||
@Comment("功能类型")
|
||||
public String type;
|
||||
@Comment("功能类型")
|
||||
public String type;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"functionname\":\"" + functionname + "\",\"type\":\"" + type + "\"}";
|
||||
}
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"functionname\":\"" + functionname + "\",\"type\":\"" + type + "\"}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,35 +9,35 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class MapIgnoreColumnTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
MapIgnoreColumnTest test = new MapIgnoreColumnTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
MapIgnoreColumnTest test = new MapIgnoreColumnTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("aaa", "123");
|
||||
map.put("bbb", List.of(1, 2));
|
||||
System.out.println(JsonConvert.root().convertTo(map));
|
||||
JsonFactory factory = JsonFactory.create();
|
||||
factory.register(Map.class, true, "aaa");
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String rs = "{\"bbb\":[1,2]}";
|
||||
if (!main) Assertions.assertEquals(rs, convert.convertTo(map));
|
||||
System.out.println(convert.convertTo(map));
|
||||
JsonConvert convert2 = JsonConvert.root()
|
||||
.newConvert(
|
||||
null,
|
||||
(k, v) -> {
|
||||
if ("bbb".equals(k)) return null;
|
||||
return v;
|
||||
},
|
||||
null);
|
||||
if (!main) Assertions.assertEquals("{\"aaa\":\"123\",\"bbb\":null}", convert2.convertTo(map));
|
||||
System.out.println(convert2.convertTo(map));
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("aaa", "123");
|
||||
map.put("bbb", List.of(1, 2));
|
||||
System.out.println(JsonConvert.root().convertTo(map));
|
||||
JsonFactory factory = JsonFactory.create();
|
||||
factory.register(Map.class, true, "aaa");
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String rs = "{\"bbb\":[1,2]}";
|
||||
if (!main) Assertions.assertEquals(rs, convert.convertTo(map));
|
||||
System.out.println(convert.convertTo(map));
|
||||
JsonConvert convert2 = JsonConvert.root()
|
||||
.newConvert(
|
||||
null,
|
||||
(k, v) -> {
|
||||
if ("bbb".equals(k)) return null;
|
||||
return v;
|
||||
},
|
||||
null);
|
||||
if (!main) Assertions.assertEquals("{\"aaa\":\"123\",\"bbb\":null}", convert2.convertTo(map));
|
||||
System.out.println(convert2.convertTo(map));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,74 +14,74 @@ import org.redkale.util.ByteArray;
|
||||
/** @author zhangjx */
|
||||
public final class Message {
|
||||
|
||||
protected boolean flag;
|
||||
protected boolean flag;
|
||||
|
||||
private int[] ints;
|
||||
private int[] ints;
|
||||
|
||||
private List<Long> longs;
|
||||
private List<Long> longs;
|
||||
|
||||
@ConvertSmallString
|
||||
private String message;
|
||||
@ConvertSmallString
|
||||
private String message;
|
||||
|
||||
public Message() {}
|
||||
public Message() {}
|
||||
|
||||
public List<Long> getLongs() {
|
||||
return longs;
|
||||
}
|
||||
public List<Long> getLongs() {
|
||||
return longs;
|
||||
}
|
||||
|
||||
public void setLongs(List<Long> longs) {
|
||||
this.longs = longs;
|
||||
}
|
||||
public void setLongs(List<Long> longs) {
|
||||
this.longs = longs;
|
||||
}
|
||||
|
||||
public int[] getInts() {
|
||||
return ints;
|
||||
}
|
||||
public int[] getInts() {
|
||||
return ints;
|
||||
}
|
||||
|
||||
public void setInts(int[] ints) {
|
||||
this.ints = ints;
|
||||
}
|
||||
public void setInts(int[] ints) {
|
||||
this.ints = ints;
|
||||
}
|
||||
|
||||
public Message(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
public Message(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
public boolean isFlag() {
|
||||
return flag;
|
||||
}
|
||||
|
||||
public void setFlag(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
public void setFlag(boolean flag) {
|
||||
this.flag = flag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Message msg = new Message();
|
||||
msg.message = "dddd";
|
||||
List<Long> longs = new ArrayList<>();
|
||||
longs.add(2222L);
|
||||
longs.add(3333L);
|
||||
msg.longs = longs;
|
||||
msg.ints = new int[] {2, 3, 4};
|
||||
JsonConvert convert = JsonFactory.root().getConvert();
|
||||
Encodeable encoder = JsonFactory.root().loadEncoder(Message.class);
|
||||
System.out.println(encoder);
|
||||
ByteArray array = new ByteArray();
|
||||
array.put("数据: ".getBytes(StandardCharsets.UTF_8));
|
||||
JsonConvert.root().convertToBytes(array, msg);
|
||||
System.out.println(array);
|
||||
Message[] mss = new Message[] {msg};
|
||||
System.out.println(JsonConvert.root().convertTo(mss));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Message msg = new Message();
|
||||
msg.message = "dddd";
|
||||
List<Long> longs = new ArrayList<>();
|
||||
longs.add(2222L);
|
||||
longs.add(3333L);
|
||||
msg.longs = longs;
|
||||
msg.ints = new int[] {2, 3, 4};
|
||||
JsonConvert convert = JsonFactory.root().getConvert();
|
||||
Encodeable encoder = JsonFactory.root().loadEncoder(Message.class);
|
||||
System.out.println(encoder);
|
||||
ByteArray array = new ByteArray();
|
||||
array.put("数据: ".getBytes(StandardCharsets.UTF_8));
|
||||
JsonConvert.root().convertToBytes(array, msg);
|
||||
System.out.println(array);
|
||||
Message[] mss = new Message[] {msg};
|
||||
System.out.println(JsonConvert.root().convertTo(mss));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,102 +10,102 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class ObjectOrStringTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ObjectOrStringTest test = new ObjectOrStringTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ObjectOrStringTest test = new ObjectOrStringTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaaa\",{\"id\":200,\"name\":\"haha\"}]";
|
||||
AbstractBean[] beans = convert.convertFrom(AbstractBean[].class, json);
|
||||
System.out.println(convert.convertTo(beans[0]));
|
||||
System.out.println(convert.convertTo(beans[1]));
|
||||
System.out.println(convert.convertTo(beans));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(beans));
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaaa\",{\"id\":200,\"name\":\"haha\"}]";
|
||||
AbstractBean[] beans = convert.convertFrom(AbstractBean[].class, json);
|
||||
System.out.println(convert.convertTo(beans[0]));
|
||||
System.out.println(convert.convertTo(beans[1]));
|
||||
System.out.println(convert.convertTo(beans));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(beans));
|
||||
}
|
||||
|
||||
public abstract static class AbstractBean {
|
||||
public abstract static class AbstractBean {
|
||||
|
||||
// 必须声明为private, 否则加载StringBean时配置Decoder会采用此方法
|
||||
private static Decodeable<JsonReader, AbstractBean> createDecoder(
|
||||
final org.redkale.convert.json.JsonFactory factory) {
|
||||
Decodeable<JsonReader, StringBean> stringDecoder = factory.loadDecoder(StringBean.class);
|
||||
Decodeable<JsonReader, ObjectBean> objectDecoder = factory.loadDecoder(ObjectBean.class);
|
||||
return new Decodeable<JsonReader, AbstractBean>() {
|
||||
@Override
|
||||
public AbstractBean convertFrom(JsonReader in) {
|
||||
Decodeable coder = in.isNextObject() ? objectDecoder : stringDecoder;
|
||||
return (AbstractBean) coder.convertFrom(in);
|
||||
}
|
||||
// 必须声明为private, 否则加载StringBean时配置Decoder会采用此方法
|
||||
private static Decodeable<JsonReader, AbstractBean> createDecoder(
|
||||
final org.redkale.convert.json.JsonFactory factory) {
|
||||
Decodeable<JsonReader, StringBean> stringDecoder = factory.loadDecoder(StringBean.class);
|
||||
Decodeable<JsonReader, ObjectBean> objectDecoder = factory.loadDecoder(ObjectBean.class);
|
||||
return new Decodeable<JsonReader, AbstractBean>() {
|
||||
@Override
|
||||
public AbstractBean convertFrom(JsonReader in) {
|
||||
Decodeable coder = in.isNextObject() ? objectDecoder : stringDecoder;
|
||||
return (AbstractBean) coder.convertFrom(in);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Type getType() {
|
||||
return AbstractBean.class;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public Type getType() {
|
||||
return AbstractBean.class;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static class ObjectBean extends AbstractBean {
|
||||
public static class ObjectBean extends AbstractBean {
|
||||
|
||||
private int id;
|
||||
private int id;
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringBean extends AbstractBean {
|
||||
public static class StringBean extends AbstractBean {
|
||||
|
||||
private String value;
|
||||
private String value;
|
||||
|
||||
public StringBean() {}
|
||||
public StringBean() {}
|
||||
|
||||
public StringBean(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
public StringBean(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
static SimpledCoder<Reader, Writer, StringBean> createConvertCoder(
|
||||
final org.redkale.convert.ConvertFactory factory) {
|
||||
return new SimpledCoder<Reader, Writer, StringBean>() {
|
||||
@Override
|
||||
public void convertTo(Writer out, StringBean val) {
|
||||
out.writeString(val == null ? null : val.value);
|
||||
}
|
||||
static SimpledCoder<Reader, Writer, StringBean> createConvertCoder(
|
||||
final org.redkale.convert.ConvertFactory factory) {
|
||||
return new SimpledCoder<Reader, Writer, StringBean>() {
|
||||
@Override
|
||||
public void convertTo(Writer out, StringBean val) {
|
||||
out.writeString(val == null ? null : val.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StringBean convertFrom(Reader in) {
|
||||
String val = in.readString();
|
||||
return new StringBean(val);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public StringBean convertFrom(Reader in) {
|
||||
String val = in.readString();
|
||||
return new StringBean(val);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,74 +12,74 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class One {
|
||||
|
||||
protected String key;
|
||||
protected String key;
|
||||
|
||||
protected int code;
|
||||
protected int code;
|
||||
|
||||
protected byte[] bytes = new byte[] {3, 4, 5};
|
||||
protected byte[] bytes = new byte[] {3, 4, 5};
|
||||
|
||||
protected int[] ints = new int[] {3000, 4000, 5000};
|
||||
protected int[] ints = new int[] {3000, 4000, 5000};
|
||||
|
||||
public One(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
public One(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
public String getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
public void setKey(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
public void setCode(int code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public byte[] getBytes() {
|
||||
return bytes;
|
||||
}
|
||||
public byte[] getBytes() {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public void setBytes(byte[] bytes) {
|
||||
this.bytes = bytes;
|
||||
}
|
||||
public void setBytes(byte[] bytes) {
|
||||
this.bytes = bytes;
|
||||
}
|
||||
|
||||
public int[] getInts() {
|
||||
return ints;
|
||||
}
|
||||
public int[] getInts() {
|
||||
return ints;
|
||||
}
|
||||
|
||||
public void setInts(int[] ints) {
|
||||
this.ints = ints;
|
||||
}
|
||||
public void setInts(int[] ints) {
|
||||
this.ints = ints;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
int count = 100_0000;
|
||||
One one = new One(234);
|
||||
one.bytes = new byte[] {1, 2, 3};
|
||||
one.key = "哈哈";
|
||||
public static void main(String[] args) throws Throwable {
|
||||
int count = 100_0000;
|
||||
One one = new One(234);
|
||||
one.bytes = new byte[] {1, 2, 3};
|
||||
one.key = "哈哈";
|
||||
|
||||
System.out.println(Arrays.toString(Utility.encodeUTF8(JsonConvert.root().convertTo(one))));
|
||||
System.out.println(Arrays.toString(JsonConvert.root().convertToBytes(one)));
|
||||
long s = System.currentTimeMillis();
|
||||
for (int i = 0; i < count; i++) {
|
||||
JsonConvert.root().convertTo(one).getBytes();
|
||||
}
|
||||
long e = System.currentTimeMillis() - s;
|
||||
System.out.println(Arrays.toString(Utility.encodeUTF8(JsonConvert.root().convertTo(one))));
|
||||
System.out.println(Arrays.toString(JsonConvert.root().convertToBytes(one)));
|
||||
long s = System.currentTimeMillis();
|
||||
for (int i = 0; i < count; i++) {
|
||||
JsonConvert.root().convertTo(one).getBytes();
|
||||
}
|
||||
long e = System.currentTimeMillis() - s;
|
||||
|
||||
long s2 = System.currentTimeMillis();
|
||||
for (int i = 0; i < count; i++) {
|
||||
JsonConvert.root().convertToBytes(one);
|
||||
}
|
||||
long e2 = System.currentTimeMillis() - s2;
|
||||
System.out.println(e);
|
||||
System.out.println(e2);
|
||||
}
|
||||
long s2 = System.currentTimeMillis();
|
||||
for (int i = 0; i < count; i++) {
|
||||
JsonConvert.root().convertToBytes(one);
|
||||
}
|
||||
long e2 = System.currentTimeMillis() - s2;
|
||||
System.out.println(e);
|
||||
System.out.println(e2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,39 +9,39 @@ import org.redkale.util.OneOrList;
|
||||
/** @author zhangjx */
|
||||
public class OneOrListTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
OneOrListTest test = new OneOrListTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
OneOrListTest test = new OneOrListTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaaa\"]";
|
||||
{
|
||||
StringOneList sol = convert.convertFrom(StringOneList.class, json);
|
||||
System.out.println("sol.list = " + convert.convertTo(sol.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(sol));
|
||||
System.out.println(convert.convertTo(sol));
|
||||
}
|
||||
{
|
||||
String2OneList sol2 = convert.convertFrom(String2OneList.class, json);
|
||||
System.out.println("sol2.list = " + convert.convertTo(sol2.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(sol2));
|
||||
System.out.println(convert.convertTo(sol2));
|
||||
}
|
||||
{
|
||||
OneOrList<String> sol3 = convert.convertFrom(OneOrList.TYPE_OL_STRING, json);
|
||||
System.out.println("sol3.list = " + convert.convertTo(sol3.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(OneOrList.TYPE_OL_STRING, sol3));
|
||||
System.out.println(convert.convertTo(OneOrList.TYPE_OL_STRING, sol3));
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
String json = "[\"aaaaa\"]";
|
||||
{
|
||||
StringOneList sol = convert.convertFrom(StringOneList.class, json);
|
||||
System.out.println("sol.list = " + convert.convertTo(sol.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(sol));
|
||||
System.out.println(convert.convertTo(sol));
|
||||
}
|
||||
{
|
||||
String2OneList sol2 = convert.convertFrom(String2OneList.class, json);
|
||||
System.out.println("sol2.list = " + convert.convertTo(sol2.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(sol2));
|
||||
System.out.println(convert.convertTo(sol2));
|
||||
}
|
||||
{
|
||||
OneOrList<String> sol3 = convert.convertFrom(OneOrList.TYPE_OL_STRING, json);
|
||||
System.out.println("sol3.list = " + convert.convertTo(sol3.getList()));
|
||||
if (!main) Assertions.assertEquals(json, convert.convertTo(OneOrList.TYPE_OL_STRING, sol3));
|
||||
System.out.println(convert.convertTo(OneOrList.TYPE_OL_STRING, sol3));
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringOneList extends OneOrList<String> {}
|
||||
public static class StringOneList extends OneOrList<String> {}
|
||||
|
||||
public static class String2OneList extends StringOneList {}
|
||||
public static class String2OneList extends StringOneList {}
|
||||
}
|
||||
|
||||
@@ -13,44 +13,44 @@ import org.redkale.convert.ConvertEntity;
|
||||
@ConvertEntity("myname")
|
||||
public class SimpleChildEntity extends SimpleEntity {
|
||||
|
||||
private short st = -1234;
|
||||
private short st = -1234;
|
||||
|
||||
private String extend;
|
||||
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<String> list = new ArrayList<>();
|
||||
list.add("aaaa");
|
||||
list.add("bbbb");
|
||||
list.add("cccc");
|
||||
v.setLists(list);
|
||||
Map<String, Integer> 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 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<String> list = new ArrayList<>();
|
||||
list.add("aaaa");
|
||||
list.add("bbbb");
|
||||
list.add("cccc");
|
||||
v.setLists(list);
|
||||
Map<String, Integer> 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 short getSt() {
|
||||
return st;
|
||||
}
|
||||
|
||||
public void setSt(short st) {
|
||||
this.st = st;
|
||||
}
|
||||
public void setSt(short st) {
|
||||
this.st = st;
|
||||
}
|
||||
|
||||
public String getExtend() {
|
||||
return extend;
|
||||
}
|
||||
public String getExtend() {
|
||||
return extend;
|
||||
}
|
||||
|
||||
public void setExtend(String extend) {
|
||||
this.extend = extend;
|
||||
}
|
||||
public void setExtend(String extend) {
|
||||
this.extend = extend;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,121 +13,121 @@ import org.redkale.util.Creator;
|
||||
/** @author zhangjx */
|
||||
public class SimpleEntity {
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private String desc = "";
|
||||
private String desc = "";
|
||||
|
||||
private int id = (int) System.currentTimeMillis();
|
||||
private int id = (int) System.currentTimeMillis();
|
||||
|
||||
private int[] addrs;
|
||||
private int[] addrs;
|
||||
|
||||
private List<String> lists;
|
||||
private List<String> lists;
|
||||
|
||||
private String[] strings;
|
||||
private String[] strings;
|
||||
|
||||
private Map<String, Integer> map;
|
||||
private Map<String, Integer> map;
|
||||
|
||||
private InetSocketAddress addr;
|
||||
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<String> list = new ArrayList<>();
|
||||
list.add("aaaa");
|
||||
list.add("bbbb");
|
||||
list.add("cccc");
|
||||
v.setLists(list);
|
||||
Map<String, Integer> 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 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<String> list = new ArrayList<>();
|
||||
list.add("aaaa");
|
||||
list.add("bbbb");
|
||||
list.add("cccc");
|
||||
v.setLists(list);
|
||||
Map<String, Integer> 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<SimpleEntity> 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());
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println(JsonConvert.root().convertTo(create()));
|
||||
Creator<SimpleEntity> 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);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public InetSocketAddress getAddr() {
|
||||
return addr;
|
||||
}
|
||||
public InetSocketAddress getAddr() {
|
||||
return addr;
|
||||
}
|
||||
|
||||
public void setAddr(InetSocketAddress addr) {
|
||||
this.addr = addr;
|
||||
}
|
||||
public void setAddr(InetSocketAddress addr) {
|
||||
this.addr = addr;
|
||||
}
|
||||
|
||||
public int[] getAddrs() {
|
||||
return addrs;
|
||||
}
|
||||
public int[] getAddrs() {
|
||||
return addrs;
|
||||
}
|
||||
|
||||
public void setAddrs(int[] addrs) {
|
||||
this.addrs = addrs;
|
||||
}
|
||||
public void setAddrs(int[] addrs) {
|
||||
this.addrs = addrs;
|
||||
}
|
||||
|
||||
public List<String> getLists() {
|
||||
return lists;
|
||||
}
|
||||
public List<String> getLists() {
|
||||
return lists;
|
||||
}
|
||||
|
||||
public void setLists(List<String> lists) {
|
||||
this.lists = lists;
|
||||
}
|
||||
public void setLists(List<String> lists) {
|
||||
this.lists = lists;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getMap() {
|
||||
return map;
|
||||
}
|
||||
public Map<String, Integer> getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map<String, Integer> map) {
|
||||
this.map = map;
|
||||
}
|
||||
public void setMap(Map<String, Integer> map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
public String getDesc() {
|
||||
return desc;
|
||||
}
|
||||
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
public void setDesc(String desc) {
|
||||
this.desc = desc;
|
||||
}
|
||||
|
||||
public String[] getStrings() {
|
||||
return strings;
|
||||
}
|
||||
public String[] getStrings() {
|
||||
return strings;
|
||||
}
|
||||
|
||||
public void setStrings(String[] strings) {
|
||||
this.strings = strings;
|
||||
}
|
||||
public void setStrings(String[] strings) {
|
||||
this.strings = strings;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,33 +10,33 @@ import org.redkale.util.StringWrapper;
|
||||
/** @author zhangjx */
|
||||
public class StringWrapperTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
StringWrapperTest test = new StringWrapperTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
StringWrapperTest test = new StringWrapperTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
{
|
||||
String val = "{}";
|
||||
StringWrapper wrapper = new StringWrapper(val);
|
||||
if (!main) Assertions.assertEquals(val, convert.convertTo(wrapper));
|
||||
if (!main) Assertions.assertEquals(val, new String(convert.convertToBytes(wrapper)));
|
||||
System.out.println(convert.convertTo(wrapper));
|
||||
System.out.println(new String(convert.convertToBytes(wrapper)));
|
||||
}
|
||||
{
|
||||
String val = "{id:'带中文'}";
|
||||
StringWrapper wrapper = new StringWrapper(val);
|
||||
if (!main) Assertions.assertEquals(val, convert.convertTo(wrapper));
|
||||
if (!main)
|
||||
Assertions.assertEquals(val, new String(convert.convertToBytes(wrapper), StandardCharsets.UTF_8));
|
||||
System.out.println(convert.convertTo(wrapper));
|
||||
System.out.println(new String(convert.convertToBytes(wrapper), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
JsonConvert convert = JsonConvert.root();
|
||||
{
|
||||
String val = "{}";
|
||||
StringWrapper wrapper = new StringWrapper(val);
|
||||
if (!main) Assertions.assertEquals(val, convert.convertTo(wrapper));
|
||||
if (!main) Assertions.assertEquals(val, new String(convert.convertToBytes(wrapper)));
|
||||
System.out.println(convert.convertTo(wrapper));
|
||||
System.out.println(new String(convert.convertToBytes(wrapper)));
|
||||
}
|
||||
{
|
||||
String val = "{id:'带中文'}";
|
||||
StringWrapper wrapper = new StringWrapper(val);
|
||||
if (!main) Assertions.assertEquals(val, convert.convertTo(wrapper));
|
||||
if (!main)
|
||||
Assertions.assertEquals(val, new String(convert.convertToBytes(wrapper), StandardCharsets.UTF_8));
|
||||
System.out.println(convert.convertTo(wrapper));
|
||||
System.out.println(new String(convert.convertToBytes(wrapper), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,42 +9,42 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class TinyTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
TinyTest test = new TinyTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
TinyTest test = new TinyTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
TinyRecord record = new TinyRecord();
|
||||
record.id = 5;
|
||||
{
|
||||
JsonFactory factory = JsonFactory.create().withFeatures(Convert.FEATURE_TINY);
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String json = "{\"id\":5}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(json, convert.convertTo(record));
|
||||
}
|
||||
System.out.println(convert.convertTo(record));
|
||||
}
|
||||
{
|
||||
JsonFactory factory = JsonFactory.create().withFeatures(0);
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String json = "{\"id\":5,\"name\":\"\"}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(json, convert.convertTo(record));
|
||||
}
|
||||
System.out.println(convert.convertTo(record));
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
TinyRecord record = new TinyRecord();
|
||||
record.id = 5;
|
||||
{
|
||||
JsonFactory factory = JsonFactory.create().withFeatures(Convert.FEATURE_TINY);
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String json = "{\"id\":5}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(json, convert.convertTo(record));
|
||||
}
|
||||
System.out.println(convert.convertTo(record));
|
||||
}
|
||||
{
|
||||
JsonFactory factory = JsonFactory.create().withFeatures(0);
|
||||
JsonConvert convert = factory.getConvert();
|
||||
String json = "{\"id\":5,\"name\":\"\"}";
|
||||
if (!main) {
|
||||
Assertions.assertEquals(json, convert.convertTo(record));
|
||||
}
|
||||
System.out.println(convert.convertTo(record));
|
||||
}
|
||||
}
|
||||
|
||||
public static class TinyRecord {
|
||||
public static class TinyRecord {
|
||||
|
||||
public String name = "";
|
||||
public String name = "";
|
||||
|
||||
public int id;
|
||||
}
|
||||
public int id;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,57 +10,57 @@ import java.util.*;
|
||||
/** @author zhangjx */
|
||||
public class Two extends One {
|
||||
|
||||
public Two() {
|
||||
super(90100119);
|
||||
}
|
||||
public Two() {
|
||||
super(90100119);
|
||||
}
|
||||
|
||||
protected List<String> list;
|
||||
protected List<String> list;
|
||||
|
||||
protected Map<String, String> stringMap;
|
||||
protected Map<String, String> stringMap;
|
||||
|
||||
protected List<ConvertRecord> records;
|
||||
protected List<ConvertRecord> records;
|
||||
|
||||
protected Map<String, ConvertRecord> recordMap;
|
||||
protected Map<String, ConvertRecord> recordMap;
|
||||
|
||||
public Map<String, String> getStringMap() {
|
||||
return stringMap;
|
||||
}
|
||||
public Map<String, String> getStringMap() {
|
||||
return stringMap;
|
||||
}
|
||||
|
||||
public void setStringMap(Map<String, String> stringMap) {
|
||||
this.stringMap = stringMap;
|
||||
}
|
||||
public void setStringMap(Map<String, String> stringMap) {
|
||||
this.stringMap = stringMap;
|
||||
}
|
||||
|
||||
String ip;
|
||||
String ip;
|
||||
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
public List<String> getList() {
|
||||
return list;
|
||||
}
|
||||
public List<String> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List<String> list) {
|
||||
this.list = list;
|
||||
}
|
||||
public void setList(List<String> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public List<ConvertRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
public List<ConvertRecord> getRecords() {
|
||||
return records;
|
||||
}
|
||||
|
||||
public void setRecords(List<ConvertRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
public void setRecords(List<ConvertRecord> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
public Map<String, ConvertRecord> getRecordMap() {
|
||||
return recordMap;
|
||||
}
|
||||
public Map<String, ConvertRecord> getRecordMap() {
|
||||
return recordMap;
|
||||
}
|
||||
|
||||
public void setRecordMap(Map<String, ConvertRecord> recordMap) {
|
||||
this.recordMap = recordMap;
|
||||
}
|
||||
public void setRecordMap(Map<String, ConvertRecord> recordMap) {
|
||||
this.recordMap = recordMap;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,45 +11,45 @@ import org.redkale.persistence.Id;
|
||||
/** @author zhangjx */
|
||||
public class World implements Comparable<World> {
|
||||
|
||||
@Id
|
||||
private int id;
|
||||
@Id
|
||||
private int id;
|
||||
|
||||
private int randomNumber;
|
||||
private int randomNumber;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getRandomNumber() {
|
||||
return randomNumber;
|
||||
}
|
||||
public int getRandomNumber() {
|
||||
return randomNumber;
|
||||
}
|
||||
|
||||
public void setRandomNumber(int randomNumber) {
|
||||
this.randomNumber = randomNumber;
|
||||
}
|
||||
public void setRandomNumber(int randomNumber) {
|
||||
this.randomNumber = randomNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(World o) {
|
||||
return Integer.compare(id, o.id);
|
||||
}
|
||||
@Override
|
||||
public int compareTo(World o) {
|
||||
return Integer.compare(id, o.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
World[] worlds = new World[20];
|
||||
int index = 8866;
|
||||
for (int i = 0; i < worlds.length; i++) {
|
||||
worlds[i] = new World();
|
||||
worlds[i].setId(8866 + i);
|
||||
worlds[i].setRandomNumber(9966 + i);
|
||||
}
|
||||
System.out.println(JsonConvert.root().convertTo(worlds));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
World[] worlds = new World[20];
|
||||
int index = 8866;
|
||||
for (int i = 0; i < worlds.length; i++) {
|
||||
worlds[i] = new World();
|
||||
worlds[i].setId(8866 + i);
|
||||
worlds[i].setRandomNumber(9966 + i);
|
||||
}
|
||||
System.out.println(JsonConvert.root().convertTo(worlds));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,36 +11,36 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class _DyncFortuneJsonEncoder extends JsonDynEncoder<Fortune> {
|
||||
|
||||
protected final byte[] idFieldBytes = "\"id\":".getBytes();
|
||||
protected final byte[] idFieldBytes = "\"id\":".getBytes();
|
||||
|
||||
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
|
||||
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
|
||||
|
||||
public _DyncFortuneJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
public _DyncFortuneJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, Fortune value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, Fortune value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
|
||||
out.writeTo('{');
|
||||
out.writeTo('{');
|
||||
|
||||
out.writeTo(idFieldBytes);
|
||||
out.writeInt(value.getId());
|
||||
out.writeTo(idFieldBytes);
|
||||
out.writeInt(value.getId());
|
||||
|
||||
String message = value.getMessage();
|
||||
if (message != null) {
|
||||
out.writeTo(messageCommaFieldBytes);
|
||||
out.writeString(message);
|
||||
}
|
||||
String message = value.getMessage();
|
||||
if (message != null) {
|
||||
out.writeTo(messageCommaFieldBytes);
|
||||
out.writeString(message);
|
||||
}
|
||||
|
||||
out.writeTo('}');
|
||||
}
|
||||
out.writeTo('}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,37 +11,37 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class _DyncMessageJsonEncoder extends JsonDynEncoder<Message> {
|
||||
|
||||
protected final byte[] messageFieldBytes = "\"message\":".getBytes();
|
||||
protected final byte[] messageFieldBytes = "\"message\":".getBytes();
|
||||
|
||||
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
|
||||
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
|
||||
|
||||
public _DyncMessageJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
public _DyncMessageJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, Message value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, Message value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
|
||||
out.writeTo('{');
|
||||
boolean comma = false;
|
||||
String message = value.getMessage();
|
||||
if (message != null) {
|
||||
if (comma) {
|
||||
out.writeTo(messageCommaFieldBytes);
|
||||
} else {
|
||||
out.writeTo(messageFieldBytes);
|
||||
comma = true;
|
||||
}
|
||||
out.writeLatin1To(true, message); // out.writeString(message);
|
||||
}
|
||||
out.writeTo('}');
|
||||
}
|
||||
out.writeTo('{');
|
||||
boolean comma = false;
|
||||
String message = value.getMessage();
|
||||
if (message != null) {
|
||||
if (comma) {
|
||||
out.writeTo(messageCommaFieldBytes);
|
||||
} else {
|
||||
out.writeTo(messageFieldBytes);
|
||||
comma = true;
|
||||
}
|
||||
out.writeLatin1To(true, message); // out.writeString(message);
|
||||
}
|
||||
out.writeTo('}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,34 +11,34 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public class _DyncWorldJsonEncoder extends JsonDynEncoder<World> {
|
||||
|
||||
protected final byte[] idFieldBytes = "\"id\":".getBytes();
|
||||
protected final byte[] idFieldBytes = "\"id\":".getBytes();
|
||||
|
||||
protected final byte[] randomNumberFieldBytes = ",\"randomNumber\":".getBytes();
|
||||
protected final byte[] randomNumberFieldBytes = ",\"randomNumber\":".getBytes();
|
||||
|
||||
public _DyncWorldJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
public _DyncWorldJsonEncoder(JsonFactory factory, Type type) {
|
||||
super(factory, type);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, World value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
@Override
|
||||
public void convertTo(JsonWriter out, World value) {
|
||||
if (value == null) {
|
||||
out.writeObjectNull(null);
|
||||
return;
|
||||
}
|
||||
if (!out.isExtFuncEmpty()) {
|
||||
objectEncoder.convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
|
||||
out.writeTo('{');
|
||||
boolean comma = false;
|
||||
out.writeTo('{');
|
||||
boolean comma = false;
|
||||
|
||||
out.writeTo(idFieldBytes);
|
||||
out.writeInt(value.getId());
|
||||
out.writeTo(idFieldBytes);
|
||||
out.writeInt(value.getId());
|
||||
|
||||
out.writeTo(randomNumberFieldBytes);
|
||||
out.writeInt(value.getRandomNumber());
|
||||
out.writeTo(randomNumberFieldBytes);
|
||||
out.writeInt(value.getRandomNumber());
|
||||
|
||||
out.writeTo('}');
|
||||
}
|
||||
out.writeTo('}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,107 +8,107 @@ package org.redkale.test.convert.media;
|
||||
/** @author redkale */
|
||||
public class Image implements java.io.Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public enum Size {
|
||||
SMALL,
|
||||
LARGE
|
||||
}
|
||||
public enum Size {
|
||||
SMALL,
|
||||
LARGE
|
||||
}
|
||||
|
||||
private String uri;
|
||||
private String uri;
|
||||
|
||||
private String title; // Can be null
|
||||
private String title; // Can be null
|
||||
|
||||
private int width;
|
||||
private int width;
|
||||
|
||||
private int height;
|
||||
private int height;
|
||||
|
||||
private Size size;
|
||||
private Size size;
|
||||
|
||||
public Image() {}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Image image = (Image) o;
|
||||
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);
|
||||
}
|
||||
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 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();
|
||||
}
|
||||
@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 setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public void setSize(Size size) {
|
||||
this.size = size;
|
||||
}
|
||||
public void setSize(Size size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public Size getSize() {
|
||||
return size;
|
||||
}
|
||||
public Size getSize() {
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,201 +10,201 @@ import java.util.*;
|
||||
/** @author redkale */
|
||||
public class Media implements java.io.Serializable {
|
||||
|
||||
public enum Player {
|
||||
JAVA,
|
||||
FLASH;
|
||||
}
|
||||
public enum Player {
|
||||
JAVA,
|
||||
FLASH;
|
||||
}
|
||||
|
||||
private String uri;
|
||||
private String uri;
|
||||
|
||||
private String title; // Can be unset.
|
||||
private String title; // Can be unset.
|
||||
|
||||
private int width;
|
||||
private int width;
|
||||
|
||||
private int height;
|
||||
private int height;
|
||||
|
||||
private String format;
|
||||
private String format;
|
||||
|
||||
private long duration;
|
||||
private long duration;
|
||||
|
||||
private long size;
|
||||
private long size;
|
||||
|
||||
private int bitrate; // Can be unset.
|
||||
private int bitrate; // Can be unset.
|
||||
|
||||
private List<String> persons;
|
||||
private List<String> persons;
|
||||
|
||||
private Player player;
|
||||
private Player player;
|
||||
|
||||
private String copyright; // Can be unset.
|
||||
private String copyright; // Can be unset.
|
||||
|
||||
public Media() {}
|
||||
public Media() {}
|
||||
|
||||
public Media(
|
||||
String uri,
|
||||
String title,
|
||||
int width,
|
||||
int height,
|
||||
String format,
|
||||
long duration,
|
||||
long size,
|
||||
int bitrate,
|
||||
boolean hasBitrate,
|
||||
List<String> 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;
|
||||
public Media(
|
||||
String uri,
|
||||
String title,
|
||||
int width,
|
||||
int height,
|
||||
String format,
|
||||
long duration,
|
||||
long size,
|
||||
int bitrate,
|
||||
boolean hasBitrate,
|
||||
List<String> 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;
|
||||
}
|
||||
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 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 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();
|
||||
}
|
||||
@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 setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public void setFormat(String format) {
|
||||
this.format = format;
|
||||
}
|
||||
public void setFormat(String format) {
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
public void setDuration(long duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
public void setDuration(long duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
public void setSize(long size) {
|
||||
this.size = size;
|
||||
}
|
||||
public void setSize(long size) {
|
||||
this.size = size;
|
||||
}
|
||||
|
||||
public void setBitrate(int bitrate) {
|
||||
this.bitrate = bitrate;
|
||||
}
|
||||
public void setBitrate(int bitrate) {
|
||||
this.bitrate = bitrate;
|
||||
}
|
||||
|
||||
public void setPersons(List<String> persons) {
|
||||
this.persons = persons;
|
||||
}
|
||||
public void setPersons(List<String> persons) {
|
||||
this.persons = persons;
|
||||
}
|
||||
|
||||
public void setPlayer(Player player) {
|
||||
this.player = player;
|
||||
}
|
||||
public void setPlayer(Player player) {
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
public void setCopyright(String copyright) {
|
||||
this.copyright = copyright;
|
||||
}
|
||||
public void setCopyright(String copyright) {
|
||||
this.copyright = copyright;
|
||||
}
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public String getFormat() {
|
||||
return format;
|
||||
}
|
||||
public String getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public long getDuration() {
|
||||
return duration;
|
||||
}
|
||||
public long getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public long getSize() {
|
||||
return size;
|
||||
}
|
||||
public long getSize() {
|
||||
return size;
|
||||
}
|
||||
|
||||
public int getBitrate() {
|
||||
return bitrate;
|
||||
}
|
||||
public int getBitrate() {
|
||||
return bitrate;
|
||||
}
|
||||
|
||||
public List<String> getPersons() {
|
||||
return persons;
|
||||
}
|
||||
public List<String> getPersons() {
|
||||
return persons;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public String getCopyright() {
|
||||
return copyright;
|
||||
}
|
||||
public String getCopyright() {
|
||||
return copyright;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,94 +12,94 @@ import org.redkale.test.convert.*;
|
||||
/** @author redkale */
|
||||
public class MediaContent implements java.io.Serializable {
|
||||
|
||||
private Media media;
|
||||
private Media media;
|
||||
|
||||
private List<Image> images;
|
||||
private List<Image> images;
|
||||
|
||||
public MediaContent() {}
|
||||
public MediaContent() {}
|
||||
|
||||
public MediaContent(Media media, List<Image> images) {
|
||||
this.media = media;
|
||||
this.images = images;
|
||||
}
|
||||
public MediaContent(Media media, List<Image> 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 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);
|
||||
}
|
||||
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 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 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();
|
||||
}
|
||||
@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 setMedia(Media media) {
|
||||
this.media = media;
|
||||
}
|
||||
|
||||
public void setImages(List<Image> images) {
|
||||
this.images = images;
|
||||
}
|
||||
public void setImages(List<Image> images) {
|
||||
this.images = images;
|
||||
}
|
||||
|
||||
public Media getMedia() {
|
||||
return media;
|
||||
}
|
||||
public Media getMedia() {
|
||||
return media;
|
||||
}
|
||||
|
||||
public List<Image> getImages() {
|
||||
return images;
|
||||
}
|
||||
public List<Image> getImages() {
|
||||
return images;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,45 +12,45 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class ArrayBean {
|
||||
|
||||
public static class IntArrayBean {
|
||||
public static class IntArrayBean {
|
||||
|
||||
public int[] values1;
|
||||
}
|
||||
public int[] values1;
|
||||
}
|
||||
|
||||
public static class IntListBean {
|
||||
public static class IntListBean {
|
||||
|
||||
public List<Integer> values2;
|
||||
}
|
||||
public List<Integer> values2;
|
||||
}
|
||||
|
||||
public static class IntegerArrayBean {
|
||||
public static class IntegerArrayBean {
|
||||
|
||||
public Integer[] values3;
|
||||
}
|
||||
public Integer[] values3;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
IntArrayBean bean1 = new IntArrayBean();
|
||||
bean1.values1 = new int[] {2, 3, 4};
|
||||
IntListBean bean2 = new IntListBean();
|
||||
bean2.values2 = Utility.ofList(2, 3, 4);
|
||||
IntegerArrayBean bean3 = new IntegerArrayBean();
|
||||
bean3.values3 = new Integer[] {2, 3, 4};
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(bean1);
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(bean2);
|
||||
byte[] bs3 = ProtobufConvert.root().convertTo(bean3);
|
||||
if (!Arrays.equals(bs1, bs2)) {
|
||||
Utility.println("int数组: ", bs1);
|
||||
Utility.println("int列表: ", bs2);
|
||||
} else if (!Arrays.equals(bs1, bs3)) {
|
||||
Utility.println("int数组: ", bs1);
|
||||
Utility.println("int集合: ", bs3);
|
||||
} else {
|
||||
System.out.println("两者相同");
|
||||
}
|
||||
IntArrayBean bean11 = ProtobufConvert.root().convertFrom(IntArrayBean.class, bs1);
|
||||
IntListBean bean22 = ProtobufConvert.root().convertFrom(IntListBean.class, bs2);
|
||||
IntegerArrayBean bean33 = ProtobufConvert.root().convertFrom(IntegerArrayBean.class, bs3);
|
||||
System.out.println(Arrays.toString(bean11.values1));
|
||||
System.out.println(bean22.values2);
|
||||
System.out.println(Arrays.toString(bean33.values3));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
IntArrayBean bean1 = new IntArrayBean();
|
||||
bean1.values1 = new int[] {2, 3, 4};
|
||||
IntListBean bean2 = new IntListBean();
|
||||
bean2.values2 = Utility.ofList(2, 3, 4);
|
||||
IntegerArrayBean bean3 = new IntegerArrayBean();
|
||||
bean3.values3 = new Integer[] {2, 3, 4};
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(bean1);
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(bean2);
|
||||
byte[] bs3 = ProtobufConvert.root().convertTo(bean3);
|
||||
if (!Arrays.equals(bs1, bs2)) {
|
||||
Utility.println("int数组: ", bs1);
|
||||
Utility.println("int列表: ", bs2);
|
||||
} else if (!Arrays.equals(bs1, bs3)) {
|
||||
Utility.println("int数组: ", bs1);
|
||||
Utility.println("int集合: ", bs3);
|
||||
} else {
|
||||
System.out.println("两者相同");
|
||||
}
|
||||
IntArrayBean bean11 = ProtobufConvert.root().convertFrom(IntArrayBean.class, bs1);
|
||||
IntListBean bean22 = ProtobufConvert.root().convertFrom(IntListBean.class, bs2);
|
||||
IntegerArrayBean bean33 = ProtobufConvert.root().convertFrom(IntegerArrayBean.class, bs3);
|
||||
System.out.println(Arrays.toString(bean11.values1));
|
||||
System.out.println(bean22.values2);
|
||||
System.out.println(Arrays.toString(bean33.values3));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,218 +21,218 @@ import org.redkale.util.*;
|
||||
@SuppressWarnings("unchecked")
|
||||
public class PBCustMessage2Test {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
PBCustMessage2Test test = new PBCustMessage2Test();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
PBCustMessage2Test test = new PBCustMessage2Test();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) {
|
||||
return null;
|
||||
}
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(msg2);
|
||||
System.out.println(Arrays.toString(bs1));
|
||||
System.out.println(Arrays.toString(bs2));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
}
|
||||
System.out.println();
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) {
|
||||
return null;
|
||||
}
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(msg2);
|
||||
System.out.println(Arrays.toString(bs1));
|
||||
System.out.println(Arrays.toString(bs2));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
OnPlayerLeaveMessage2 newmsg2 = ProtobufConvert.root().convertFrom(OnPlayerLeaveMessage2.class, bs1);
|
||||
byte[] newbs2 = ProtobufConvert.root().convertTo(newmsg2);
|
||||
System.out.println(Arrays.toString(newbs2));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(newbs2));
|
||||
}
|
||||
System.out.println();
|
||||
OnPlayerLeaveMessage2 newmsg2 = ProtobufConvert.root().convertFrom(OnPlayerLeaveMessage2.class, bs1);
|
||||
byte[] newbs2 = ProtobufConvert.root().convertTo(newmsg2);
|
||||
System.out.println(Arrays.toString(newbs2));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(newbs2));
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
ProtobufConvert convert = ProtobufConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg1)));
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg2)));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(convert.convertTo(msg1)), Arrays.toString(convert.convertTo(msg2)));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
ProtobufConvert convert = ProtobufConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg1)));
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg2)));
|
||||
if (!main) {
|
||||
Assertions.assertEquals(Arrays.toString(convert.convertTo(msg1)), Arrays.toString(convert.convertTo(msg2)));
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static interface BaseMessage {
|
||||
public static interface BaseMessage {
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
|
||||
String value();
|
||||
}
|
||||
String value();
|
||||
}
|
||||
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) {
|
||||
return mn.value();
|
||||
}
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) {
|
||||
return mn.value();
|
||||
}
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectEncoder encoder = new ProtobufObjectEncoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
EnMember member1 = new EnMember(attribute1, factory.loadEncoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachEnMember(factory, member1);
|
||||
public static Encodeable<Writer, BaseMessage> createConvertEnCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectEncoder encoder = new ProtobufObjectEncoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
EnMember member1 = new EnMember(attribute1, factory.loadEncoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachEnMember(factory, member1);
|
||||
|
||||
Function func2 = t -> t;
|
||||
Attribute attribute2 = Attribute.create(clazz, "data", clazz, func2, null);
|
||||
EnMember member2 = new EnMember(attribute2, valEncoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachEnMember(factory, member2);
|
||||
this.members = new EnMember[] {member1, member2};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
Function func2 = t -> t;
|
||||
Attribute attribute2 = Attribute.create(clazz, "data", clazz, func2, null);
|
||||
EnMember member2 = new EnMember(attribute2, valEncoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachEnMember(factory, member2);
|
||||
this.members = new EnMember[] {member1, member2};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectDecoder decoder = new ProtobufObjectDecoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
DeMember member1 = new DeMember(attribute1, factory.loadDecoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachDeMember(factory, member1);
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(
|
||||
final ConvertFactory factory, final Class<? extends BaseMessage> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
final String eventName = getMessageName(clazz);
|
||||
ObjectDecoder decoder = new ProtobufObjectDecoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
Function func1 = t -> eventName;
|
||||
Attribute attribute1 = Attribute.create(clazz, "event", String.class, func1, null);
|
||||
DeMember member1 = new DeMember(attribute1, factory.loadDecoder(String.class), null, null);
|
||||
setIndex(member1, 1);
|
||||
setPosition(member1, 1);
|
||||
initForEachDeMember(factory, member1);
|
||||
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func2 = t -> t;
|
||||
BiConsumer consumer2 = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute2 = Attribute.create(clazz, "data", clazz, func2, consumer2);
|
||||
DeMember member2 = new DeMember(attribute2, valDecoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachDeMember(factory, member2);
|
||||
this.members = new DeMember[] {member1, member2};
|
||||
}
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func2 = t -> t;
|
||||
BiConsumer consumer2 = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute2 = Attribute.create(clazz, "data", clazz, func2, consumer2);
|
||||
DeMember member2 = new DeMember(attribute2, valDecoder, null, null);
|
||||
setIndex(member2, 2);
|
||||
setPosition(member2, 2);
|
||||
initForEachDeMember(factory, member2);
|
||||
this.members = new DeMember[] {member1, member2};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseMessage convertFrom(ProtobufReader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BaseMessage convertFrom(ProtobufReader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveMessage {
|
||||
public static class OnPlayerLeaveMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
private String event = "onPlayerLeaveMessage";
|
||||
@ConvertColumn(index = 1)
|
||||
private String event = "onPlayerLeaveMessage";
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
private OnPlayerLeaveContent result;
|
||||
@ConvertColumn(index = 2)
|
||||
private OnPlayerLeaveContent result;
|
||||
|
||||
public OnPlayerLeaveMessage() {}
|
||||
public OnPlayerLeaveMessage() {}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.result = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.result = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.result = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.result = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
public String getEvent() {
|
||||
return event;
|
||||
}
|
||||
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
public void setEvent(String event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent getResult() {
|
||||
return result;
|
||||
}
|
||||
public OnPlayerLeaveContent getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setResult(OnPlayerLeaveContent result) {
|
||||
this.result = result;
|
||||
}
|
||||
public void setResult(OnPlayerLeaveContent result) {
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveContent {
|
||||
public static class OnPlayerLeaveContent {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveContent() {}
|
||||
public OnPlayerLeaveContent() {}
|
||||
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,180 +21,180 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class PBCustMessageTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
PBCustMessageTest test = new PBCustMessageTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
PBCustMessageTest test = new PBCustMessageTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(msg2);
|
||||
System.out.println(Arrays.toString(bs1));
|
||||
System.out.println(Arrays.toString(bs2));
|
||||
if (!main) Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
System.out.println();
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final BiFunction<Attribute, Object, Object> objFieldFunc = (Attribute t, Object u) -> {
|
||||
if (t.field().equals("retinfo")) return null;
|
||||
return t.get(u);
|
||||
};
|
||||
OnPlayerLeaveMessage msg1 = new OnPlayerLeaveMessage(100, "haha");
|
||||
byte[] bs1 = ProtobufConvert.root().convertTo(msg1);
|
||||
OnPlayerLeaveMessage2 msg2 = new OnPlayerLeaveMessage2(100, "haha");
|
||||
byte[] bs2 = ProtobufConvert.root().convertTo(msg2);
|
||||
System.out.println(Arrays.toString(bs1));
|
||||
System.out.println(Arrays.toString(bs2));
|
||||
if (!main) Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(bs2));
|
||||
System.out.println();
|
||||
|
||||
OnPlayerLeaveMessage2 newmsg2 = ProtobufConvert.root().convertFrom(OnPlayerLeaveMessage2.class, bs1);
|
||||
byte[] newbs2 = ProtobufConvert.root().convertTo(newmsg2);
|
||||
System.out.println(Arrays.toString(newbs2));
|
||||
if (!main) Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(newbs2));
|
||||
System.out.println();
|
||||
OnPlayerLeaveMessage2 newmsg2 = ProtobufConvert.root().convertFrom(OnPlayerLeaveMessage2.class, bs1);
|
||||
byte[] newbs2 = ProtobufConvert.root().convertTo(newmsg2);
|
||||
System.out.println(Arrays.toString(newbs2));
|
||||
if (!main) Assertions.assertEquals(Arrays.toString(bs1), Arrays.toString(newbs2));
|
||||
System.out.println();
|
||||
|
||||
ProtobufConvert convert = ProtobufConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg1)));
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg2)));
|
||||
if (!main)
|
||||
Assertions.assertEquals(Arrays.toString(convert.convertTo(msg1)), Arrays.toString(convert.convertTo(msg2)));
|
||||
System.out.println();
|
||||
}
|
||||
ProtobufConvert convert = ProtobufConvert.root().newConvert(objFieldFunc);
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg1)));
|
||||
System.out.println(Arrays.toString(convert.convertTo(msg2)));
|
||||
if (!main)
|
||||
Assertions.assertEquals(Arrays.toString(convert.convertTo(msg1)), Arrays.toString(convert.convertTo(msg2)));
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static interface BaseMessage {
|
||||
public static interface BaseMessage {
|
||||
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
@Inherited
|
||||
@Documented
|
||||
@Target({TYPE})
|
||||
@Retention(RUNTIME)
|
||||
public @interface MessageName {
|
||||
|
||||
String value();
|
||||
}
|
||||
String value();
|
||||
}
|
||||
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
public static String getMessageName(Class<?> clazz) {
|
||||
MessageName mn = clazz.getAnnotation(MessageName.class);
|
||||
if (mn != null) return mn.value();
|
||||
char[] fieldChars = clazz.getSimpleName().toCharArray();
|
||||
fieldChars[0] = Character.toLowerCase(fieldChars[0]);
|
||||
return new String(fieldChars);
|
||||
}
|
||||
|
||||
public static Encodeable<Writer, BaseMessage> createConvertCoder(ProtobufFactory factory, Class<?> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
ObjectEncoder encoder = new ProtobufObjectEncoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func = t -> t;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, null);
|
||||
EnMember member = new EnMember(attribute, valEncoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachEnMember(factory, member);
|
||||
this.members = new EnMember[] {member};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
public static Encodeable<Writer, BaseMessage> createConvertCoder(ProtobufFactory factory, Class<?> clazz) {
|
||||
Encodeable valEncoder = factory.createEncoder(clazz, true);
|
||||
ObjectEncoder encoder = new ProtobufObjectEncoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitEnMember(ConvertFactory factory) {
|
||||
Function func = t -> t;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, null);
|
||||
EnMember member = new EnMember(attribute, valEncoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachEnMember(factory, member);
|
||||
this.members = new EnMember[] {member};
|
||||
}
|
||||
};
|
||||
encoder.init(factory);
|
||||
return encoder;
|
||||
}
|
||||
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(ProtobufFactory factory, Class<?> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
ObjectDecoder decoder = new ProtobufObjectDecoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func = t -> t;
|
||||
BiConsumer consumer = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, consumer);
|
||||
DeMember member = new DeMember(attribute, valDecoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachDeMember(factory, member);
|
||||
this.members = new DeMember[] {member};
|
||||
}
|
||||
public static Decodeable<Reader, BaseMessage> createConvertDeCoder(ProtobufFactory factory, Class<?> clazz) {
|
||||
Decodeable valDecoder = factory.createDecoder(clazz, true);
|
||||
ObjectDecoder decoder = new ProtobufObjectDecoder<BaseMessage>(clazz) {
|
||||
@Override
|
||||
protected void afterInitDeMember(ConvertFactory factory) {
|
||||
this.creator = (Creator) objs -> new Object[1];
|
||||
Function func = t -> t;
|
||||
BiConsumer consumer = (t, v) -> ((Object[]) t)[0] = v;
|
||||
Attribute attribute = Attribute.create(clazz, getMessageName(clazz), clazz, func, consumer);
|
||||
DeMember member = new DeMember(attribute, valDecoder, null, null);
|
||||
setIndex(member, 1);
|
||||
setPosition(member, 1);
|
||||
initForEachDeMember(factory, member);
|
||||
this.members = new DeMember[] {member};
|
||||
}
|
||||
|
||||
@Override
|
||||
public BaseMessage convertFrom(ProtobufReader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public BaseMessage convertFrom(ProtobufReader in) {
|
||||
Object result = (Object) super.convertFrom(in);
|
||||
return (BaseMessage) ((Object[]) result)[0];
|
||||
}
|
||||
};
|
||||
decoder.init(factory);
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
@BaseMessage.MessageName("onPlayerLeaveMessage")
|
||||
public static class OnPlayerLeaveMessage2 implements BaseMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
public OnPlayerLeaveMessage2() {}
|
||||
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveMessage2(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveMessage {
|
||||
public static class OnPlayerLeaveMessage {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
private OnPlayerLeaveContent onPlayerLeaveMessage;
|
||||
@ConvertColumn(index = 1)
|
||||
private OnPlayerLeaveContent onPlayerLeaveMessage;
|
||||
|
||||
public OnPlayerLeaveMessage() {}
|
||||
public OnPlayerLeaveMessage() {}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
public OnPlayerLeaveMessage(int userid, String retinfo) {
|
||||
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
|
||||
return onPlayerLeaveMessage;
|
||||
}
|
||||
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
|
||||
return onPlayerLeaveMessage;
|
||||
}
|
||||
|
||||
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
|
||||
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
|
||||
}
|
||||
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
|
||||
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
|
||||
}
|
||||
|
||||
public static class OnPlayerLeaveContent {
|
||||
public static class OnPlayerLeaveContent {
|
||||
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
@ConvertColumn(index = 1)
|
||||
public int userid;
|
||||
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
@ConvertColumn(index = 2)
|
||||
public String retinfo;
|
||||
|
||||
public OnPlayerLeaveContent() {}
|
||||
public OnPlayerLeaveContent() {}
|
||||
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
public OnPlayerLeaveContent(int userid, String retinfo) {
|
||||
this.userid = userid;
|
||||
this.retinfo = retinfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,329 +17,329 @@ import org.redkale.util.AnyValue;
|
||||
/** @author zhangjx */
|
||||
public interface HttpRequestDesc {
|
||||
|
||||
// 获取客户端地址IP
|
||||
public SocketAddress getRemoteAddress();
|
||||
// 获取客户端地址IP
|
||||
public SocketAddress getRemoteAddress();
|
||||
|
||||
// 获取客户端地址IP, 与getRemoteAddres() 的区别在于:
|
||||
// 本方法优先取header中指定为RemoteAddress名的值,没有则返回getRemoteAddres()的getHostAddress()。
|
||||
// 本方法适用于服务前端有如nginx的代理服务器进行中转,通过getRemoteAddres()是获取不到客户端的真实IP。
|
||||
public String getRemoteAddr();
|
||||
// 获取客户端地址IP, 与getRemoteAddres() 的区别在于:
|
||||
// 本方法优先取header中指定为RemoteAddress名的值,没有则返回getRemoteAddres()的getHostAddress()。
|
||||
// 本方法适用于服务前端有如nginx的代理服务器进行中转,通过getRemoteAddres()是获取不到客户端的真实IP。
|
||||
public String getRemoteAddr();
|
||||
|
||||
// 获取请求内容指定的编码字符串
|
||||
public String getBody(Charset charset);
|
||||
// 获取请求内容指定的编码字符串
|
||||
public String getBody(Charset charset);
|
||||
|
||||
// 获取请求内容的UTF-8编码字符串
|
||||
public String getBodyUTF8();
|
||||
// 获取请求内容的UTF-8编码字符串
|
||||
public String getBodyUTF8();
|
||||
|
||||
// 获取请求内容的byte[]
|
||||
public byte[] getBody();
|
||||
// 获取请求内容的byte[]
|
||||
public byte[] getBody();
|
||||
|
||||
// 获取请求内容的JavaBean对象
|
||||
public <T> T getBodyJson(java.lang.reflect.Type type);
|
||||
// 获取请求内容的JavaBean对象
|
||||
public <T> T getBodyJson(java.lang.reflect.Type type);
|
||||
|
||||
// 获取请求内容的JavaBean对象
|
||||
public <T> T getBodyJson(JsonConvert convert, java.lang.reflect.Type type);
|
||||
// 获取请求内容的JavaBean对象
|
||||
public <T> T getBodyJson(JsonConvert convert, java.lang.reflect.Type type);
|
||||
|
||||
// 获取文件上传对象
|
||||
public MultiContext getMultiContext();
|
||||
// 获取文件上传对象
|
||||
public MultiContext getMultiContext();
|
||||
|
||||
// 获取文件上传信息列表 等价于 getMultiContext().parts();
|
||||
public Iterable<MultiPart> multiParts() throws IOException;
|
||||
// 获取文件上传信息列表 等价于 getMultiContext().parts();
|
||||
public Iterable<MultiPart> multiParts() throws IOException;
|
||||
|
||||
// 设置当前用户信息, 通常在HttpServlet.preExecute方法里设置currentUser
|
||||
// 数据类型由@HttpUserType指定
|
||||
public <T> HttpRequest setCurrentUser(T user);
|
||||
// 设置当前用户信息, 通常在HttpServlet.preExecute方法里设置currentUser
|
||||
// 数据类型由@HttpUserType指定
|
||||
public <T> HttpRequest setCurrentUser(T user);
|
||||
|
||||
// 获取当前用户信息 数据类型由@HttpUserType指定
|
||||
public <T> T currentUser();
|
||||
// 获取当前用户信息 数据类型由@HttpUserType指定
|
||||
public <T> T currentUser();
|
||||
|
||||
// 获取模块ID,来自@HttpServlet.moduleid()
|
||||
public int getModuleid();
|
||||
// 获取模块ID,来自@HttpServlet.moduleid()
|
||||
public int getModuleid();
|
||||
|
||||
// 获取操作ID,来自@HttpMapping.actionid()
|
||||
public int getActionid();
|
||||
// 获取操作ID,来自@HttpMapping.actionid()
|
||||
public int getActionid();
|
||||
|
||||
// 获取sessionid
|
||||
public String getSessionid(boolean autoCreate);
|
||||
// 获取sessionid
|
||||
public String getSessionid(boolean autoCreate);
|
||||
|
||||
// 更新sessionid
|
||||
public String changeSessionid();
|
||||
// 更新sessionid
|
||||
public String changeSessionid();
|
||||
|
||||
// 指定值更新sessionid
|
||||
public String changeSessionid(String newsessionid);
|
||||
// 指定值更新sessionid
|
||||
public String changeSessionid(String newsessionid);
|
||||
|
||||
// 使sessionid失效
|
||||
public void invalidateSession();
|
||||
// 使sessionid失效
|
||||
public void invalidateSession();
|
||||
|
||||
// 获取所有Cookie对象
|
||||
public java.net.HttpCookie[] getCookies();
|
||||
// 获取所有Cookie对象
|
||||
public java.net.HttpCookie[] getCookies();
|
||||
|
||||
// 获取Cookie值
|
||||
public String getCookie(String name);
|
||||
// 获取Cookie值
|
||||
public String getCookie(String name);
|
||||
|
||||
// 获取Cookie值, 没有返回默认值
|
||||
public String getCookie(String name, String defaultValue);
|
||||
// 获取Cookie值, 没有返回默认值
|
||||
public String getCookie(String name, String defaultValue);
|
||||
|
||||
// 获取协议名 http、https、ws、wss等
|
||||
public String getProtocol();
|
||||
// 获取协议名 http、https、ws、wss等
|
||||
public String getProtocol();
|
||||
|
||||
// 获取请求方法 GET、POST等
|
||||
public String getMethod();
|
||||
// 获取请求方法 GET、POST等
|
||||
public String getMethod();
|
||||
|
||||
// 获取Content-Type的header值
|
||||
public String getContentType();
|
||||
// 获取Content-Type的header值
|
||||
public String getContentType();
|
||||
|
||||
// 获取请求内容的长度, 为-1表示内容长度不确定
|
||||
public long getContentLength();
|
||||
// 获取请求内容的长度, 为-1表示内容长度不确定
|
||||
public long getContentLength();
|
||||
|
||||
// 获取Connection的Header值
|
||||
public String getConnection();
|
||||
// 获取Connection的Header值
|
||||
public String getConnection();
|
||||
|
||||
// 获取Host的Header值
|
||||
public String getHost();
|
||||
// 获取Host的Header值
|
||||
public String getHost();
|
||||
|
||||
// 获取请求的URL
|
||||
public String getRequestURI();
|
||||
// 获取请求的URL
|
||||
public String getRequestURI();
|
||||
|
||||
// 截取getRequestURI最后的一个/后面的部分
|
||||
public String getRequstURILastPath();
|
||||
// 截取getRequestURI最后的一个/后面的部分
|
||||
public String getRequstURILastPath();
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的short值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: short type = request.getRequstURILastPath((short)0); //type = 2
|
||||
public short getRequstURILastPath(short defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的short值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: short type = request.getRequstURILastPath((short)0); //type = 2
|
||||
public short getRequstURILastPath(short defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的short值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: short type = request.getRequstURILastPath((short)0); //type = 2
|
||||
public short getRequstURILastPath(int radix, short defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的short值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: short type = request.getRequstURILastPath((short)0); //type = 2
|
||||
public short getRequstURILastPath(int radix, short defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的int值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: int type = request.getRequstURILastPath(0); //type = 2
|
||||
public int getRequstURILastPath(int defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的int值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: int type = request.getRequstURILastPath(0); //type = 2
|
||||
public int getRequstURILastPath(int defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的int值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: int type = request.getRequstURILastPath(0); //type = 2
|
||||
public int getRequstURILastPath(int radix, int defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的int值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: int type = request.getRequstURILastPath(0); //type = 2
|
||||
public int getRequstURILastPath(int radix, int defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的float值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: float type = request.getRequstURILastPath(0.f); //type = 2.f
|
||||
public float getRequstURILastPath(float defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的float值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: float type = request.getRequstURILastPath(0.f); //type = 2.f
|
||||
public float getRequstURILastPath(float defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的long值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: long type = request.getRequstURILastPath(0L); //type = 2
|
||||
public long getRequstURILastPath(long defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的long值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: long type = request.getRequstURILastPath(0L); //type = 2
|
||||
public long getRequstURILastPath(long defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的long值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: long type = request.getRequstURILastPath(0L); //type = 2
|
||||
public long getRequstURILastPath(int radix, long defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的long值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: long type = request.getRequstURILastPath(0L); //type = 2
|
||||
public long getRequstURILastPath(int radix, long defvalue);
|
||||
|
||||
// 获取请求URL最后的一个/后面的部分的double值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: double type = request.getRequstURILastPath(0.0); //type = 2.0
|
||||
public double getRequstURILastPath(double defvalue);
|
||||
// 获取请求URL最后的一个/后面的部分的double值 <br>
|
||||
// 例如请求URL /pipes/record/query/2 <br>
|
||||
// 获取type参数: double type = request.getRequstURILastPath(0.0); //type = 2.0
|
||||
public double getRequstURILastPath(double defvalue);
|
||||
|
||||
// 从prefix之后截取getRequestURI再对"/"进行分隔
|
||||
public String[] getRequstURIPaths(String prefix);
|
||||
// 从prefix之后截取getRequestURI再对"/"进行分隔
|
||||
public String[] getRequstURIPaths(String prefix);
|
||||
|
||||
// 获取请求URL分段中含prefix段的值
|
||||
// 例如请求URL /pipes/record/query/name:hello
|
||||
// 获取name参数: String name = request.getRequstURIPath("name:", "none");
|
||||
public String getRequstURIPath(String prefix, String 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);
|
||||
// 获取请求URL分段中含prefix段的short值
|
||||
// 例如请求URL /pipes/record/query/type:10
|
||||
// 获取type参数: short type = request.getRequstURIPath("type:", (short)0);
|
||||
public short getRequstURIPath(String prefix, short defaultValue);
|
||||
|
||||
// 获取请求URL分段中含prefix段的short值
|
||||
// 例如请求URL /pipes/record/query/type:a
|
||||
// 获取type参数: short type = request.getRequstURIPath(16, "type:", (short)0); type = 10
|
||||
public short getRequstURIPath(int radix, String prefix, short defvalue);
|
||||
// 获取请求URL分段中含prefix段的short值
|
||||
// 例如请求URL /pipes/record/query/type:a
|
||||
// 获取type参数: short type = request.getRequstURIPath(16, "type:", (short)0); type = 10
|
||||
public short getRequstURIPath(int radix, String prefix, short defvalue);
|
||||
|
||||
// 获取请求URL分段中含prefix段的int值
|
||||
// 例如请求URL /pipes/record/query/offset:2/limit:50
|
||||
// 获取offset参数: int offset = request.getRequstURIPath("offset:", 1);
|
||||
// 获取limit参数: int limit = request.getRequstURIPath("limit:", 20);
|
||||
public int getRequstURIPath(String prefix, int defaultValue);
|
||||
// 获取请求URL分段中含prefix段的int值
|
||||
// 例如请求URL /pipes/record/query/offset:2/limit:50
|
||||
// 获取offset参数: int offset = request.getRequstURIPath("offset:", 1);
|
||||
// 获取limit参数: int limit = request.getRequstURIPath("limit:", 20);
|
||||
public int getRequstURIPath(String prefix, int defaultValue);
|
||||
|
||||
// 获取请求URL分段中含prefix段的int值
|
||||
// 例如请求URL /pipes/record/query/offset:2/limit:10
|
||||
// 获取offset参数: int offset = request.getRequstURIPath("offset:", 1);
|
||||
// 获取limit参数: int limit = request.getRequstURIPath(16, "limit:", 20); // limit = 16
|
||||
public int getRequstURIPath(int radix, String prefix, int defaultValue);
|
||||
// 获取请求URL分段中含prefix段的int值
|
||||
// 例如请求URL /pipes/record/query/offset:2/limit:10
|
||||
// 获取offset参数: int offset = request.getRequstURIPath("offset:", 1);
|
||||
// 获取limit参数: int limit = request.getRequstURIPath(16, "limit:", 20); // limit = 16
|
||||
public int getRequstURIPath(int radix, String prefix, int defaultValue);
|
||||
|
||||
// 获取请求URL分段中含prefix段的float值
|
||||
// 例如请求URL /pipes/record/query/point:40.0
|
||||
// 获取time参数: float point = request.getRequstURIPath("point:", 0.0f);
|
||||
public float getRequstURIPath(String prefix, float defvalue);
|
||||
// 获取请求URL分段中含prefix段的float值
|
||||
// 例如请求URL /pipes/record/query/point:40.0
|
||||
// 获取time参数: float point = request.getRequstURIPath("point:", 0.0f);
|
||||
public float getRequstURIPath(String prefix, float defvalue);
|
||||
|
||||
// 获取请求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段的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段的long值
|
||||
// 例如请求URL /pipes/record/query/time:1453104341363/id:40
|
||||
// 获取time参数: long time = request.getRequstURIPath("time:", 0L);
|
||||
public long getRequstURIPath(int radix, String prefix, long defvalue);
|
||||
// 获取请求URL分段中含prefix段的long值
|
||||
// 例如请求URL /pipes/record/query/time:1453104341363/id:40
|
||||
// 获取time参数: long time = request.getRequstURIPath("time:", 0L);
|
||||
public long getRequstURIPath(int radix, String prefix, long defvalue);
|
||||
|
||||
// 获取请求URL分段中含prefix段的double值 <br>
|
||||
// 例如请求URL /pipes/record/query/point:40.0 <br>
|
||||
// 获取time参数: double point = request.getRequstURIPath("point:", 0.0);
|
||||
public double getRequstURIPath(String prefix, double defvalue);
|
||||
// 获取请求URL分段中含prefix段的double值 <br>
|
||||
// 例如请求URL /pipes/record/query/point:40.0 <br>
|
||||
// 获取time参数: double point = request.getRequstURIPath("point:", 0.0);
|
||||
public double getRequstURIPath(String prefix, double defvalue);
|
||||
|
||||
// 获取所有的header名
|
||||
public AnyValue getHeaders();
|
||||
// 获取所有的header名
|
||||
public AnyValue getHeaders();
|
||||
|
||||
// 将请求Header转换成Map
|
||||
public Map<String, String> getHeadersToMap(Map<String, String> map);
|
||||
// 将请求Header转换成Map
|
||||
public Map<String, String> getHeadersToMap(Map<String, String> map);
|
||||
|
||||
// 获取所有的header名
|
||||
public String[] getHeaderNames();
|
||||
// 获取所有的header名
|
||||
public String[] getHeaderNames();
|
||||
|
||||
// 获取指定的header值
|
||||
public String getHeader(String name);
|
||||
// 获取指定的header值
|
||||
public String getHeader(String name);
|
||||
|
||||
// 获取指定的header值, 没有返回默认值
|
||||
public String getHeader(String name, String defaultValue);
|
||||
// 获取指定的header值, 没有返回默认值
|
||||
public String getHeader(String name, String defaultValue);
|
||||
|
||||
// 获取指定的header的json值
|
||||
public <T> T getJsonHeader(Type type, String name);
|
||||
// 获取指定的header的json值
|
||||
public <T> T getJsonHeader(Type type, String name);
|
||||
|
||||
// 获取指定的header的json值
|
||||
public <T> T getJsonHeader(JsonConvert convert, Type type, String name);
|
||||
// 获取指定的header的json值
|
||||
public <T> T getJsonHeader(JsonConvert convert, Type type, String name);
|
||||
|
||||
// 获取指定的header的boolean值, 没有返回默认boolean值
|
||||
public boolean getBooleanHeader(String name, boolean defaultValue);
|
||||
// 获取指定的header的boolean值, 没有返回默认boolean值
|
||||
public boolean getBooleanHeader(String name, boolean defaultValue);
|
||||
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(String name, short defaultValue);
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(String name, short defaultValue);
|
||||
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(int radix, String name, short defaultValue);
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(int radix, String name, short defaultValue);
|
||||
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(String name, int defaultValue);
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(String name, int defaultValue);
|
||||
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(int radix, String name, int defaultValue);
|
||||
// 获取指定的header的short值, 没有返回默认short值
|
||||
public short getShortHeader(int radix, String name, int defaultValue);
|
||||
|
||||
// 获取指定的header的int值, 没有返回默认int值
|
||||
public int getIntHeader(String name, int defaultValue);
|
||||
// 获取指定的header的int值, 没有返回默认int值
|
||||
public int getIntHeader(String name, int defaultValue);
|
||||
|
||||
// 获取指定的header的int值, 没有返回默认int值
|
||||
public int getIntHeader(int radix, String name, int defaultValue);
|
||||
// 获取指定的header的int值, 没有返回默认int值
|
||||
public int getIntHeader(int radix, String name, int defaultValue);
|
||||
|
||||
// 获取指定的header的long值, 没有返回默认long值
|
||||
public long getLongHeader(String name, long defaultValue);
|
||||
// 获取指定的header的long值, 没有返回默认long值
|
||||
public long getLongHeader(String name, long defaultValue);
|
||||
|
||||
// 获取指定的header的long值, 没有返回默认long值
|
||||
public long getLongHeader(int radix, String name, long defaultValue);
|
||||
// 获取指定的header的long值, 没有返回默认long值
|
||||
public long getLongHeader(int radix, String name, long defaultValue);
|
||||
|
||||
// 获取指定的header的float值, 没有返回默认float值
|
||||
public float getFloatHeader(String name, float defaultValue);
|
||||
// 获取指定的header的float值, 没有返回默认float值
|
||||
public float getFloatHeader(String name, float defaultValue);
|
||||
|
||||
// 获取指定的header的double值, 没有返回默认double值
|
||||
public double getDoubleHeader(String name, double defaultValue);
|
||||
// 获取指定的header的double值, 没有返回默认double值
|
||||
public double getDoubleHeader(String name, double defaultValue);
|
||||
|
||||
// 获取请求参数总对象
|
||||
public AnyValue getParameters();
|
||||
// 获取请求参数总对象
|
||||
public AnyValue getParameters();
|
||||
|
||||
// 将请求参数转换成Map
|
||||
public Map<String, String> getParametersToMap(Map<String, String> map);
|
||||
// 将请求参数转换成Map
|
||||
public Map<String, String> getParametersToMap(Map<String, String> map);
|
||||
|
||||
// 将请求参数转换成String, 字符串格式为: bean1={}&id=13&name=xxx
|
||||
// 不会返回null,没有参数返回空字符串
|
||||
public String getParametersToString();
|
||||
// 将请求参数转换成String, 字符串格式为: bean1={}&id=13&name=xxx
|
||||
// 不会返回null,没有参数返回空字符串
|
||||
public String getParametersToString();
|
||||
|
||||
// 将请求参数转换成String, 字符串格式为: prefix + bean1={}&id=13&name=xxx
|
||||
// 拼接前缀, 如果无参数,返回的字符串不会含有拼接前缀
|
||||
// 不会返回null,没有参数返回空字符串
|
||||
public String getParametersToString(String prefix);
|
||||
// 将请求参数转换成String, 字符串格式为: prefix + bean1={}&id=13&name=xxx
|
||||
// 拼接前缀, 如果无参数,返回的字符串不会含有拼接前缀
|
||||
// 不会返回null,没有参数返回空字符串
|
||||
public String getParametersToString(String prefix);
|
||||
|
||||
// 获取所有参数名
|
||||
public String[] getParameterNames();
|
||||
// 获取所有参数名
|
||||
public String[] getParameterNames();
|
||||
|
||||
// 获取指定的参数值
|
||||
public String getParameter(String name);
|
||||
// 获取指定的参数值
|
||||
public String getParameter(String name);
|
||||
|
||||
// 获取指定的参数值, 没有返回默认值
|
||||
public String getParameter(String name, String defaultValue);
|
||||
// 获取指定的参数值, 没有返回默认值
|
||||
public String getParameter(String name, String defaultValue);
|
||||
|
||||
// 获取指定的参数json值
|
||||
public <T> T getJsonParameter(Type type, String name);
|
||||
// 获取指定的参数json值
|
||||
public <T> T getJsonParameter(Type type, String name);
|
||||
|
||||
// 获取指定的参数json值
|
||||
public <T> T getJsonParameter(JsonConvert convert, Type type, String name);
|
||||
// 获取指定的参数json值
|
||||
public <T> T getJsonParameter(JsonConvert convert, Type type, String name);
|
||||
|
||||
// 获取指定的参数boolean值, 没有返回默认boolean值
|
||||
public boolean getBooleanParameter(String name, boolean defaultValue);
|
||||
// 获取指定的参数boolean值, 没有返回默认boolean值
|
||||
public boolean getBooleanParameter(String name, boolean defaultValue);
|
||||
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(String name, short defaultValue);
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(String name, short defaultValue);
|
||||
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(int radix, String name, short defaultValue);
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(int radix, String name, short defaultValue);
|
||||
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(int radix, String name, int defaultValue);
|
||||
// 获取指定的参数short值, 没有返回默认short值
|
||||
public short getShortParameter(int radix, String name, int defaultValue);
|
||||
|
||||
// 获取指定的参数int值, 没有返回默认int值
|
||||
public int getIntParameter(String name, int defaultValue);
|
||||
// 获取指定的参数int值, 没有返回默认int值
|
||||
public int getIntParameter(String name, int defaultValue);
|
||||
|
||||
// 获取指定的参数int值, 没有返回默认int值
|
||||
public int getIntParameter(int radix, String name, int defaultValue);
|
||||
// 获取指定的参数int值, 没有返回默认int值
|
||||
public int getIntParameter(int radix, String name, int defaultValue);
|
||||
|
||||
// 获取指定的参数long值, 没有返回默认long值
|
||||
public long getLongParameter(String name, long defaultValue);
|
||||
// 获取指定的参数long值, 没有返回默认long值
|
||||
public long getLongParameter(String name, long defaultValue);
|
||||
|
||||
// 获取指定的参数long值, 没有返回默认long值
|
||||
public long getLongParameter(int radix, String name, long defaultValue);
|
||||
// 获取指定的参数long值, 没有返回默认long值
|
||||
public long getLongParameter(int radix, String name, long defaultValue);
|
||||
|
||||
// 获取指定的参数float值, 没有返回默认float值
|
||||
public float getFloatParameter(String name, float defaultValue);
|
||||
// 获取指定的参数float值, 没有返回默认float值
|
||||
public float getFloatParameter(String name, float defaultValue);
|
||||
|
||||
// 获取指定的参数double值, 没有返回默认double值
|
||||
public double getDoubleParameter(String name, double defaultValue);
|
||||
// 获取指定的参数double值, 没有返回默认double值
|
||||
public double getDoubleParameter(String name, double defaultValue);
|
||||
|
||||
// 获取翻页对象 同 getFlipper("flipper", false, 0);
|
||||
public org.redkale.source.Flipper getFlipper();
|
||||
// 获取翻页对象 同 getFlipper("flipper", false, 0);
|
||||
public org.redkale.source.Flipper getFlipper();
|
||||
|
||||
// 获取翻页对象 同 getFlipper("flipper", needcreate, 0);
|
||||
public org.redkale.source.Flipper getFlipper(boolean needcreate);
|
||||
// 获取翻页对象 同 getFlipper("flipper", needcreate, 0);
|
||||
public org.redkale.source.Flipper getFlipper(boolean needcreate);
|
||||
|
||||
// 获取翻页对象 同 getFlipper("flipper", false, maxLimit);
|
||||
public org.redkale.source.Flipper getFlipper(int maxLimit);
|
||||
// 获取翻页对象 同 getFlipper("flipper", false, maxLimit);
|
||||
public org.redkale.source.Flipper getFlipper(int maxLimit);
|
||||
|
||||
// 获取翻页对象 同 getFlipper("flipper", needcreate, maxLimit)
|
||||
public org.redkale.source.Flipper getFlipper(boolean needcreate, int maxLimit);
|
||||
// 获取翻页对象 同 getFlipper("flipper", needcreate, maxLimit)
|
||||
public org.redkale.source.Flipper getFlipper(boolean needcreate, int maxLimit);
|
||||
|
||||
// 获取翻页对象 http://redkale.org/pipes/records/list/offset:0/limit:20/sort:createtime%20ASC
|
||||
// http://redkale.org/pipes/records/list?flipper={'offset':0,'limit':20, 'sort':'createtime ASC'}
|
||||
// 以上两种接口都可以获取到翻页对象
|
||||
public org.redkale.source.Flipper getFlipper(String name, boolean needcreate, int maxLimit);
|
||||
// 获取翻页对象 http://redkale.org/pipes/records/list/offset:0/limit:20/sort:createtime%20ASC
|
||||
// http://redkale.org/pipes/records/list?flipper={'offset':0,'limit':20, 'sort':'createtime ASC'}
|
||||
// 以上两种接口都可以获取到翻页对象
|
||||
public org.redkale.source.Flipper getFlipper(String name, boolean needcreate, int maxLimit);
|
||||
|
||||
// 获取HTTP上下文对象
|
||||
public HttpContext getContext();
|
||||
// 获取HTTP上下文对象
|
||||
public HttpContext getContext();
|
||||
|
||||
// 获取所有属性值, servlet执行完后会被清空
|
||||
public Map<String, Object> getAttributes();
|
||||
// 获取所有属性值, servlet执行完后会被清空
|
||||
public Map<String, Object> getAttributes();
|
||||
|
||||
// 获取指定属性值, servlet执行完后会被清空
|
||||
public <T> T getAttribute(String name);
|
||||
// 获取指定属性值, servlet执行完后会被清空
|
||||
public <T> T getAttribute(String name);
|
||||
|
||||
// 删除指定属性
|
||||
public void removeAttribute(String name);
|
||||
// 删除指定属性
|
||||
public void removeAttribute(String name);
|
||||
|
||||
// 设置属性值, servlet执行完后会被清空
|
||||
public void setAttribute(String name, Object value);
|
||||
// 设置属性值, servlet执行完后会被清空
|
||||
public void setAttribute(String name, Object value);
|
||||
|
||||
// 获取request创建时间
|
||||
public long getCreatetime();
|
||||
// 获取request创建时间
|
||||
public long getCreatetime();
|
||||
}
|
||||
|
||||
@@ -20,152 +20,152 @@ import org.redkale.net.http.*;
|
||||
/** @author zhangjx */
|
||||
public interface HttpResponseDesc {
|
||||
|
||||
// 增加Cookie值
|
||||
public HttpResponse addCookie(HttpCookie... cookies);
|
||||
// 增加Cookie值
|
||||
public HttpResponse addCookie(HttpCookie... cookies);
|
||||
|
||||
// 增加Cookie值
|
||||
public HttpResponse addCookie(Collection<HttpCookie> cookies);
|
||||
// 增加Cookie值
|
||||
public HttpResponse addCookie(Collection<HttpCookie> cookies);
|
||||
|
||||
// 创建CompletionHandler实例,将非字符串对象以JSON格式输出,字符串以文本输出
|
||||
public CompletionHandler createAsyncHandler();
|
||||
// 创建CompletionHandler实例,将非字符串对象以JSON格式输出,字符串以文本输出
|
||||
public CompletionHandler createAsyncHandler();
|
||||
|
||||
// 传入的CompletionHandler子类必须是public,且保证其子类可被继承且completed、failed可被重载且包含空参数的构造函数
|
||||
public <H extends CompletionHandler> H createAsyncHandler(Class<H> handlerClass);
|
||||
// 传入的CompletionHandler子类必须是public,且保证其子类可被继承且completed、failed可被重载且包含空参数的构造函数
|
||||
public <H extends CompletionHandler> H createAsyncHandler(Class<H> handlerClass);
|
||||
|
||||
// 获取ByteBuffer生成器
|
||||
public Supplier<ByteBuffer> getBufferSupplier();
|
||||
// 获取ByteBuffer生成器
|
||||
public Supplier<ByteBuffer> getBufferSupplier();
|
||||
|
||||
// 设置状态码
|
||||
public void setStatus(int status);
|
||||
// 设置状态码
|
||||
public void setStatus(int status);
|
||||
|
||||
// 获取状态码
|
||||
public int getStatus();
|
||||
// 获取状态码
|
||||
public int getStatus();
|
||||
|
||||
// 获取 ContentType
|
||||
public String getContentType();
|
||||
// 获取 ContentType
|
||||
public String getContentType();
|
||||
|
||||
// 设置 ContentType
|
||||
public HttpResponse setContentType(String contentType);
|
||||
// 设置 ContentType
|
||||
public HttpResponse setContentType(String contentType);
|
||||
|
||||
// 获取内容长度
|
||||
public long getContentLength();
|
||||
// 获取内容长度
|
||||
public long getContentLength();
|
||||
|
||||
// 设置内容长度
|
||||
public HttpResponse setContentLength(long contentLength);
|
||||
// 设置内容长度
|
||||
public HttpResponse setContentLength(long contentLength);
|
||||
|
||||
// 设置Header值
|
||||
public HttpResponse setHeader(String name, Object value);
|
||||
// 设置Header值
|
||||
public HttpResponse setHeader(String name, Object value);
|
||||
|
||||
// 添加Header值
|
||||
public HttpResponse addHeader(String name, Object value);
|
||||
// 添加Header值
|
||||
public HttpResponse addHeader(String name, Object value);
|
||||
|
||||
// 添加Header值
|
||||
public HttpResponse addHeader(Map<String, ?> map);
|
||||
// 添加Header值
|
||||
public HttpResponse addHeader(Map<String, ?> map);
|
||||
|
||||
// 跳过header的输出
|
||||
// 通常应用场景是,调用者的输出内容里已经包含了HTTP的响应头信息,因此需要调用此方法避免重复输出HTTP响应头信息。
|
||||
public HttpResponse skipHeader();
|
||||
// 跳过header的输出
|
||||
// 通常应用场景是,调用者的输出内容里已经包含了HTTP的响应头信息,因此需要调用此方法避免重复输出HTTP响应头信息。
|
||||
public HttpResponse skipHeader();
|
||||
|
||||
// 异步输出指定内容
|
||||
public <A> void sendBody(ByteBuffer buffer, A attachment, CompletionHandler<Integer, A> handler);
|
||||
// 异步输出指定内容
|
||||
public <A> void sendBody(ByteBuffer buffer, A attachment, CompletionHandler<Integer, A> handler);
|
||||
|
||||
// 异步输出指定内容
|
||||
public <A> void sendBody(ByteBuffer[] buffers, A attachment, CompletionHandler<Integer, A> handler);
|
||||
// 异步输出指定内容
|
||||
public <A> void sendBody(ByteBuffer[] buffers, A attachment, CompletionHandler<Integer, A> handler);
|
||||
|
||||
// 关闭HTTP连接,如果是keep-alive则不强制关闭
|
||||
public void finish();
|
||||
// 关闭HTTP连接,如果是keep-alive则不强制关闭
|
||||
public void finish();
|
||||
|
||||
// 强制关闭HTTP连接
|
||||
public void finish(boolean kill);
|
||||
// 强制关闭HTTP连接
|
||||
public void finish(boolean kill);
|
||||
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(Object obj);
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(Object obj);
|
||||
|
||||
// 将对象数组用Map的形式以JSON格式输出
|
||||
// 例如: finishMap("a",2,"b",3) 输出结果为 {"a":2,"b":3}
|
||||
public void finishMapJson(final Object... objs);
|
||||
// 将对象数组用Map的形式以JSON格式输出
|
||||
// 例如: finishMap("a",2,"b",3) 输出结果为 {"a":2,"b":3}
|
||||
public void finishMapJson(final Object... objs);
|
||||
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(JsonConvert convert, Object obj);
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(JsonConvert convert, Object obj);
|
||||
|
||||
// 将对象数组用Map的形式以JSON格式输出
|
||||
// 例如: finishMap("a",2,"b",3) 输出结果为 {"a":2,"b":3}
|
||||
public void finishMapJson(final JsonConvert convert, final Object... objs);
|
||||
// 将对象数组用Map的形式以JSON格式输出
|
||||
// 例如: finishMap("a",2,"b",3) 输出结果为 {"a":2,"b":3}
|
||||
public void finishMapJson(final JsonConvert convert, final Object... objs);
|
||||
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(Type type, 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 JsonConvert convert, final Type type, final Object obj);
|
||||
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(final Object... objs);
|
||||
// 将对象以JSON格式输出
|
||||
public void finishJson(final Object... objs);
|
||||
|
||||
// 将RetResult对象以JSON格式输出
|
||||
public void finishJson(final org.redkale.service.RetResult ret);
|
||||
// 将RetResult对象以JSON格式输出
|
||||
public void finishJson(final org.redkale.service.RetResult ret);
|
||||
|
||||
// 将RetResult对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret);
|
||||
// 将RetResult对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final org.redkale.service.RetResult ret);
|
||||
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final CompletableFuture future);
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final CompletableFuture future);
|
||||
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final CompletableFuture future);
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final CompletableFuture future);
|
||||
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final Type type, final CompletableFuture future);
|
||||
// 将CompletableFuture的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final Type type, final CompletableFuture future);
|
||||
|
||||
// 将HttpResult的结果对象以JSON格式输出
|
||||
public void finishJson(final HttpResult result);
|
||||
// 将HttpResult的结果对象以JSON格式输出
|
||||
public void finishJson(final HttpResult result);
|
||||
|
||||
// 将HttpResult的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final HttpResult result);
|
||||
// 将HttpResult的结果对象以JSON格式输出
|
||||
public void finishJson(final JsonConvert convert, final HttpResult result);
|
||||
|
||||
// 将指定字符串以响应结果输出
|
||||
public void finish(String obj);
|
||||
// 将指定字符串以响应结果输出
|
||||
public void finish(String obj);
|
||||
|
||||
// 以指定响应码附带内容输出, message 可以为null
|
||||
public void finish(int status, String message);
|
||||
// 以指定响应码附带内容输出, message 可以为null
|
||||
public void finish(int status, String message);
|
||||
|
||||
// 将结果对象输出
|
||||
public void finish(final Object obj);
|
||||
// 将结果对象输出
|
||||
public void finish(final Object obj);
|
||||
|
||||
// 将结果对象输出
|
||||
public void finish(final Convert convert, final Object obj);
|
||||
// 将结果对象输出
|
||||
public void finish(final Convert convert, final Object obj);
|
||||
|
||||
// 将结果对象输出
|
||||
public void finish(final Convert convert, final Type type, final Object obj);
|
||||
// 将结果对象输出
|
||||
public void finish(final Convert convert, final Type type, final Object obj);
|
||||
|
||||
// 以304状态码输出
|
||||
public void finish304();
|
||||
// 以304状态码输出
|
||||
public void finish304();
|
||||
|
||||
// 以404状态码输出
|
||||
public void finish404();
|
||||
// 以404状态码输出
|
||||
public void finish404();
|
||||
|
||||
// 将指定byte[]按响应结果输出
|
||||
public void finish(final byte[] bs);
|
||||
// 将指定byte[]按响应结果输出
|
||||
public void finish(final byte[] bs);
|
||||
|
||||
// 将指定ByteBuffer按响应结果输出
|
||||
public void finish(ByteBuffer buffer);
|
||||
// 将指定ByteBuffer按响应结果输出
|
||||
public void finish(ByteBuffer buffer);
|
||||
|
||||
// 将指定ByteBuffer按响应结果输出
|
||||
// kill 输出后是否强制关闭连接
|
||||
public void finish(boolean kill, ByteBuffer buffer);
|
||||
// 将指定ByteBuffer按响应结果输出
|
||||
// kill 输出后是否强制关闭连接
|
||||
public void finish(boolean kill, ByteBuffer buffer);
|
||||
|
||||
// 将指定ByteBuffer数组按响应结果输出
|
||||
public void finish(ByteBuffer... buffers);
|
||||
// 将指定ByteBuffer数组按响应结果输出
|
||||
public void finish(ByteBuffer... buffers);
|
||||
|
||||
// 将指定ByteBuffer数组按响应结果输出
|
||||
// kill 输出后是否强制关闭连接
|
||||
public void finish(boolean kill, ByteBuffer... buffers);
|
||||
// 将指定ByteBuffer数组按响应结果输出
|
||||
// kill 输出后是否强制关闭连接
|
||||
public void finish(boolean kill, ByteBuffer... buffers);
|
||||
|
||||
// 将指定文件按响应结果输出
|
||||
public void finish(File file) throws IOException;
|
||||
// 将指定文件按响应结果输出
|
||||
public void finish(File file) throws IOException;
|
||||
|
||||
// 将文件按指定文件名输出
|
||||
public void finish(final String filename, File file) throws IOException;
|
||||
// 将文件按指定文件名输出
|
||||
public void finish(final String filename, File file) throws IOException;
|
||||
|
||||
// HttpResponse回收时回调的监听方法
|
||||
public void recycleListener(BiConsumer<HttpRequest, HttpResponse> recycleListener);
|
||||
// HttpResponse回收时回调的监听方法
|
||||
public void recycleListener(BiConsumer<HttpRequest, HttpResponse> recycleListener);
|
||||
}
|
||||
|
||||
@@ -18,99 +18,99 @@ import org.redkale.util.AnyValueWriter;
|
||||
/** @author zhangjx */
|
||||
public class HttpSimpleClientTest {
|
||||
|
||||
private static int port = 0;
|
||||
private static int port = 0;
|
||||
|
||||
private static Application application;
|
||||
private static Application application;
|
||||
|
||||
private static ResourceFactory factory;
|
||||
private static ResourceFactory factory;
|
||||
|
||||
private static HttpServer server;
|
||||
private static HttpServer server;
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
HttpSimpleClientTest test = new HttpSimpleClientTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
HttpSimpleClientTest test = new HttpSimpleClientTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
runServer();
|
||||
// Utility.sleep(50000);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
WebClient client = WebClient.create(asyncGroup);
|
||||
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", port);
|
||||
{
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", 100);
|
||||
System.out.println(client.getAsync("http://127.0.0.1:" + port + req.getPath() + "?id=100")
|
||||
.join());
|
||||
System.out.println(client.sendAsync(addr, req).join());
|
||||
}
|
||||
final int count = 10;
|
||||
{
|
||||
final CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 100; i < 100 + count; i++) {
|
||||
final int index = i;
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", index);
|
||||
client.getAsync("http://127.0.0.1:" + port + req.getPath() + "?id=" + index)
|
||||
.whenComplete((v, t) -> {
|
||||
cdl.countDown();
|
||||
Assertions.assertEquals("ok-" + index, new String((byte[]) v.getResult()));
|
||||
});
|
||||
}
|
||||
cdl.await();
|
||||
System.out.println("结束并发1");
|
||||
}
|
||||
{
|
||||
final CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 100; i < 100 + count; i++) {
|
||||
final int index = i;
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", index);
|
||||
client.sendAsync(addr, req).whenComplete((v, t) -> {
|
||||
cdl.countDown();
|
||||
System.out.println("输出: " + new String((byte[]) v.getResult()));
|
||||
Assertions.assertEquals("ok-" + index, new String((byte[]) v.getResult()));
|
||||
});
|
||||
}
|
||||
cdl.await();
|
||||
System.out.println("结束并发2");
|
||||
}
|
||||
server.shutdown();
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
runServer();
|
||||
// Utility.sleep(50000);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
WebClient client = WebClient.create(asyncGroup);
|
||||
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", port);
|
||||
{
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", 100);
|
||||
System.out.println(client.getAsync("http://127.0.0.1:" + port + req.getPath() + "?id=100")
|
||||
.join());
|
||||
System.out.println(client.sendAsync(addr, req).join());
|
||||
}
|
||||
final int count = 10;
|
||||
{
|
||||
final CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 100; i < 100 + count; i++) {
|
||||
final int index = i;
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", index);
|
||||
client.getAsync("http://127.0.0.1:" + port + req.getPath() + "?id=" + index)
|
||||
.whenComplete((v, t) -> {
|
||||
cdl.countDown();
|
||||
Assertions.assertEquals("ok-" + index, new String((byte[]) v.getResult()));
|
||||
});
|
||||
}
|
||||
cdl.await();
|
||||
System.out.println("结束并发1");
|
||||
}
|
||||
{
|
||||
final CountDownLatch cdl = new CountDownLatch(count);
|
||||
for (int i = 100; i < 100 + count; i++) {
|
||||
final int index = i;
|
||||
WebRequest req = WebRequest.createPostPath("/test").param("id", index);
|
||||
client.sendAsync(addr, req).whenComplete((v, t) -> {
|
||||
cdl.countDown();
|
||||
System.out.println("输出: " + new String((byte[]) v.getResult()));
|
||||
Assertions.assertEquals("ok-" + index, new String((byte[]) v.getResult()));
|
||||
});
|
||||
}
|
||||
cdl.await();
|
||||
System.out.println("结束并发2");
|
||||
}
|
||||
server.shutdown();
|
||||
}
|
||||
|
||||
private static void runServer() throws Exception {
|
||||
application = Application.create(true);
|
||||
factory = application.getResourceFactory();
|
||||
factory.register("", Application.class, application);
|
||||
final CountDownLatch cdl = new CountDownLatch(1);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-01");
|
||||
}
|
||||
private static void runServer() throws Exception {
|
||||
application = Application.create(true);
|
||||
factory = application.getResourceFactory();
|
||||
factory.register("", Application.class, application);
|
||||
final CountDownLatch cdl = new CountDownLatch(1);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-01");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + port);
|
||||
conf.addValue("protocol", "HTTP");
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
server = new HttpServer(factory);
|
||||
server.init(conf);
|
||||
server.addHttpServlet(new HttpSimpleServlet(), "/test");
|
||||
server.start();
|
||||
port = server.getSocketAddress().getPort();
|
||||
cdl.countDown();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
cdl.await();
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + port);
|
||||
conf.addValue("protocol", "HTTP");
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
server = new HttpServer(factory);
|
||||
server.init(conf);
|
||||
server.addHttpServlet(new HttpSimpleServlet(), "/test");
|
||||
server.start();
|
||||
port = server.getSocketAddress().getPort();
|
||||
cdl.countDown();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
cdl.await();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,9 @@ import org.redkale.net.http.HttpServlet;
|
||||
/** @author zhangjx */
|
||||
public class HttpSimpleServlet extends HttpServlet {
|
||||
|
||||
@HttpMapping(url = "/test")
|
||||
public void test(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
System.out.println("运行到test方法了, id=" + req.getParameter("id"));
|
||||
resp.finish("ok-" + req.getParameter("id", "0"));
|
||||
}
|
||||
@HttpMapping(url = "/test")
|
||||
public void test(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
System.out.println("运行到test方法了, id=" + req.getParameter("id"));
|
||||
resp.finish("ok-" + req.getParameter("id", "0"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,58 +13,58 @@ import org.redkale.net.http.WebRequest;
|
||||
/** @author zhangjx */
|
||||
public class RequestCoderTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
RequestCoderTest test = new RequestCoderTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
RequestCoderTest test = new RequestCoderTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
test.run3();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
req1.addHeader("X-aaa", "aaa");
|
||||
req1.param("bean", "{}");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
req1.addHeader("X-aaa", "aaa");
|
||||
req1.param("bean", "{}");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run3() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
req1.addHeader("X-aaa", "aaa");
|
||||
req1.addHeader("X-bbb", "bbb1");
|
||||
req1.addHeader("X-bbb", "bbb2");
|
||||
req1.param("bean", "{}");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
@Test
|
||||
public void run3() throws Exception {
|
||||
WebRequest req1 = WebRequest.createPostPath("/aaa");
|
||||
req1.addHeader("X-aaa", "aaa");
|
||||
req1.addHeader("X-bbb", "bbb1");
|
||||
req1.addHeader("X-bbb", "bbb2");
|
||||
req1.param("bean", "{}");
|
||||
System.out.println("simpleRequest1: " + req1);
|
||||
byte[] bytes = WebRequestCoder.getInstance().encode(req1);
|
||||
WebRequest req2 = WebRequestCoder.getInstance().decode(bytes);
|
||||
Field timeFiedl = ClientRequest.class.getDeclaredField("createTime");
|
||||
timeFiedl.setAccessible(true);
|
||||
timeFiedl.set(req2, req1.getCreateTime());
|
||||
System.out.println("simpleRequest2: " + req2);
|
||||
Assertions.assertEquals(req1.toString(), req2.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,24 +11,24 @@ import org.redkale.util.Utility;
|
||||
@RestService(name = "test", autoMapping = true)
|
||||
public class RestSleepService extends AbstractService {
|
||||
|
||||
public String sleep200() {
|
||||
Utility.sleep(200);
|
||||
System.out.println("当前执行线程: " + Thread.currentThread().getName());
|
||||
return "ok200";
|
||||
}
|
||||
public String sleep200() {
|
||||
Utility.sleep(200);
|
||||
System.out.println("当前执行线程: " + Thread.currentThread().getName());
|
||||
return "ok200";
|
||||
}
|
||||
|
||||
public String sleep300() {
|
||||
Utility.sleep(300);
|
||||
return "ok300";
|
||||
}
|
||||
public String sleep300() {
|
||||
Utility.sleep(300);
|
||||
return "ok300";
|
||||
}
|
||||
|
||||
public String sleep400() {
|
||||
Utility.sleep(400);
|
||||
return "ok400";
|
||||
}
|
||||
public String sleep400() {
|
||||
Utility.sleep(400);
|
||||
return "ok400";
|
||||
}
|
||||
|
||||
public String sleep500() {
|
||||
Utility.sleep(500);
|
||||
return "ok500";
|
||||
}
|
||||
public String sleep500() {
|
||||
Utility.sleep(500);
|
||||
return "ok500";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,55 +18,55 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class RestSleepTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
RestSleepTest test = new RestSleepTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
RestSleepTest test = new RestSleepTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
System.out.println("------------------- 并发调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
System.out.println("------------------- 并发调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
RestSleepService service = Sncp.createSimpleLocalService(RestSleepService.class, resFactory);
|
||||
HttpServer server = new HttpServer(application, System.currentTimeMillis(), resFactory);
|
||||
server.getResourceFactory().register(application);
|
||||
System.out.println("servlet = " + server.addRestServlet(null, service, null, HttpServlet.class, ""));
|
||||
server.init(AnyValueWriter.create("port", 0));
|
||||
server.start();
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
RestSleepService service = Sncp.createSimpleLocalService(RestSleepService.class, resFactory);
|
||||
HttpServer server = new HttpServer(application, System.currentTimeMillis(), resFactory);
|
||||
server.getResourceFactory().register(application);
|
||||
System.out.println("servlet = " + server.addRestServlet(null, service, null, HttpServlet.class, ""));
|
||||
server.init(AnyValueWriter.create("port", 0));
|
||||
server.start();
|
||||
|
||||
int port = server.getSocketAddress().getPort();
|
||||
System.out.println("服务器启动端口: " + port);
|
||||
InetSocketAddress httpAddress = new InetSocketAddress("127.0.0.1", port);
|
||||
Socket socket = new Socket(httpAddress.getAddress(), port);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("GET /test/sleep200 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n"
|
||||
+ "GET /test/sleep300 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n"
|
||||
+ "GET /test/sleep500 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n")
|
||||
.getBytes());
|
||||
InputStream in = socket.getInputStream();
|
||||
byte[] bytes = new byte[8192];
|
||||
long s = System.currentTimeMillis();
|
||||
int pos = in.read(bytes);
|
||||
long e = System.currentTimeMillis() - s;
|
||||
System.out.println("返回结果: " + new String(bytes, 0, pos));
|
||||
System.out.println("耗时: " + e + " ms");
|
||||
server.shutdown();
|
||||
Assertions.assertTrue(e < 600);
|
||||
}
|
||||
int port = server.getSocketAddress().getPort();
|
||||
System.out.println("服务器启动端口: " + port);
|
||||
InetSocketAddress httpAddress = new InetSocketAddress("127.0.0.1", port);
|
||||
Socket socket = new Socket(httpAddress.getAddress(), port);
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("GET /test/sleep200 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n"
|
||||
+ "GET /test/sleep300 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n"
|
||||
+ "GET /test/sleep500 HTTP/1.1\r\n"
|
||||
+ "Connection: Keep-Alive\r\n"
|
||||
+ "\r\n")
|
||||
.getBytes());
|
||||
InputStream in = socket.getInputStream();
|
||||
byte[] bytes = new byte[8192];
|
||||
long s = System.currentTimeMillis();
|
||||
int pos = in.read(bytes);
|
||||
long e = System.currentTimeMillis() - s;
|
||||
System.out.println("返回结果: " + new String(bytes, 0, pos));
|
||||
System.out.println("耗时: " + e + " ms");
|
||||
server.shutdown();
|
||||
Assertions.assertTrue(e < 600);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,27 +10,27 @@ import java.net.Socket;
|
||||
/** @author zhangjx */
|
||||
public class SocketMain {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Socket socket = new Socket("127.0.0.1", 6060);
|
||||
socket.getOutputStream()
|
||||
.write(
|
||||
"GET /json1 HTTP/1.1\r\nAccpet: aaa\r\nConnection: keep-alive\r\n\r\nGET /json2 HTTP/1.1\r\nAccpet: a"
|
||||
.getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream().write("aa\r\nConnection: keep-alive\r\n\r".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream()
|
||||
.write("\nGET /json3 HTTP/1.1\r\nAccpet: aaa\r\nConnection: keep-alive\r\n\r".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream().write("\n".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
byte[] bs = new byte[10240];
|
||||
int rs = socket.getInputStream().read(bs);
|
||||
System.out.println(new String(bs, 0, rs));
|
||||
rs = socket.getInputStream().read(bs);
|
||||
System.out.println(new String(bs, 0, rs));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
Socket socket = new Socket("127.0.0.1", 6060);
|
||||
socket.getOutputStream()
|
||||
.write(
|
||||
"GET /json1 HTTP/1.1\r\nAccpet: aaa\r\nConnection: keep-alive\r\n\r\nGET /json2 HTTP/1.1\r\nAccpet: a"
|
||||
.getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream().write("aa\r\nConnection: keep-alive\r\n\r".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream()
|
||||
.write("\nGET /json3 HTTP/1.1\r\nAccpet: aaa\r\nConnection: keep-alive\r\n\r".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
Thread.sleep(1000);
|
||||
socket.getOutputStream().write("\n".getBytes());
|
||||
socket.getOutputStream().flush();
|
||||
byte[] bs = new byte[10240];
|
||||
int rs = socket.getInputStream().read(bs);
|
||||
System.out.println(new String(bs, 0, rs));
|
||||
rs = socket.getInputStream().read(bs);
|
||||
System.out.println(new String(bs, 0, rs));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,32 +12,32 @@ import org.redkale.net.http.*;
|
||||
// @WebServlet({"/uploadtest/form", "/uploadtest/send"})
|
||||
public class UploadTestServlet extends HttpServlet {
|
||||
|
||||
@Override
|
||||
public void execute(HttpRequest request, HttpResponse response) throws IOException {
|
||||
if (request.getRequestPath().contains("/uploadtest/send")) {
|
||||
send(request, response);
|
||||
} else {
|
||||
form(request, response);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void execute(HttpRequest request, HttpResponse response) throws IOException {
|
||||
if (request.getRequestPath().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("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/></head>"
|
||||
+ "<div style='margin-top:150px;margin-left:400px;'><form action=\"/pipes/uploadtest/send\" method=\"post\" enctype=\"multipart/form-data\">"
|
||||
+ "描述: <input name=\"desc1\"/> 文件1: <input type=\"file\" name=\"filepath1\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc2\"/> 文件2: <input type=\"file\" name=\"filepath2\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc3\"/> 文件3: <input type=\"file\" name=\"filepath3\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc4\"/> <br/><br/>"
|
||||
+ " <input type=\"submit\" value=\"Submit\"/></form></div>"
|
||||
+ "</html>");
|
||||
}
|
||||
public void form(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
resp.setContentType("text/html");
|
||||
resp.finish("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/></head>"
|
||||
+ "<div style='margin-top:150px;margin-left:400px;'><form action=\"/pipes/uploadtest/send\" method=\"post\" enctype=\"multipart/form-data\">"
|
||||
+ "描述: <input name=\"desc1\"/> 文件1: <input type=\"file\" name=\"filepath1\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc2\"/> 文件2: <input type=\"file\" name=\"filepath2\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc3\"/> 文件3: <input type=\"file\" name=\"filepath3\"/><br/><br/>"
|
||||
+ "描述: <input name=\"desc4\"/> <br/><br/>"
|
||||
+ " <input type=\"submit\" value=\"Submit\"/></form></div>"
|
||||
+ "</html>");
|
||||
}
|
||||
|
||||
public void send(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
for (MultiPart entry : req.multiParts()) {
|
||||
entry.skip();
|
||||
System.out.println(entry);
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
public void send(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
for (MultiPart entry : req.multiParts()) {
|
||||
entry.skip();
|
||||
System.out.println(entry);
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,181 +18,181 @@ import org.redkale.net.http.*;
|
||||
/** @author zhangjx */
|
||||
public interface WebSocketDesc<G, T> {
|
||||
|
||||
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Object message);
|
||||
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Object message);
|
||||
|
||||
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMap(Object... messages);
|
||||
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMap(Object... messages);
|
||||
|
||||
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Object message, boolean last);
|
||||
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Object message, boolean last);
|
||||
|
||||
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMap(boolean last, Object... messages);
|
||||
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMap(boolean last, Object... messages);
|
||||
|
||||
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Convert convert, Object message);
|
||||
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Convert convert, Object message);
|
||||
|
||||
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Convert convert, Object message, boolean last);
|
||||
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> send(Convert convert, Object message, boolean last);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, G... userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, G... userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, Stream<G> userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, Stream<G> userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, G... userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, G... userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, Stream<G> userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, Stream<G> userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, boolean last, G... userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, boolean last, G... userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, boolean last, Stream<G> userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Object message, boolean last, Stream<G> userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, boolean last, G... userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, boolean last, G... userids);
|
||||
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, boolean last, Stream<G> userids);
|
||||
// 给指定userid的WebSocket节点发送 二进制消息/文本消息/JavaBean对象消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendMessage(Convert convert, Object message, boolean last, Stream<G> userids);
|
||||
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Object message);
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Object message);
|
||||
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Convert convert, final Object message);
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Convert convert, final Object message);
|
||||
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final WebSocketRange wsrange, final Object message);
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final WebSocketRange wsrange, final Object message);
|
||||
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
final WebSocketRange wsrange, final Convert convert, final Object message);
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
final WebSocketRange wsrange, final Convert convert, final Object message);
|
||||
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Object message, boolean last);
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Object message, boolean last);
|
||||
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Convert convert, final Object message, boolean last);
|
||||
// 给所有人广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(final Convert convert, final Object message, boolean last);
|
||||
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
final WebSocketRange wsrange, final Object message, boolean last);
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
final WebSocketRange wsrange, final Object message, boolean last);
|
||||
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
WebSocketRange wsrange, Convert convert, final Object message, boolean last);
|
||||
// 给符合条件的人群广播消息, 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> broadcastMessage(
|
||||
WebSocketRange wsrange, Convert convert, final Object message, boolean last);
|
||||
|
||||
// 给指定userid的WebSocket节点发送操作
|
||||
public CompletableFuture<Integer> sendAction(final WebSocketAction action, Serializable... userids);
|
||||
// 给指定userid的WebSocket节点发送操作
|
||||
public CompletableFuture<Integer> sendAction(final WebSocketAction action, Serializable... userids);
|
||||
|
||||
// 广播操作, 给所有人发操作指令
|
||||
public CompletableFuture<Integer> broadcastAction(final WebSocketAction action);
|
||||
// 广播操作, 给所有人发操作指令
|
||||
public CompletableFuture<Integer> broadcastAction(final WebSocketAction action);
|
||||
|
||||
// 获取用户在线的SNCP节点地址列表,不是分布式则返回元素数量为1,且元素值为null的列表
|
||||
public CompletableFuture<Collection<InetSocketAddress>> getRpcNodeAddresses(final Serializable userid);
|
||||
// 获取用户在线的SNCP节点地址列表,不是分布式则返回元素数量为1,且元素值为null的列表
|
||||
public CompletableFuture<Collection<InetSocketAddress>> getRpcNodeAddresses(final Serializable userid);
|
||||
|
||||
// 获取在线用户的详细连接信息
|
||||
public CompletableFuture<Map<InetSocketAddress, List<String>>> getRpcNodeWebSocketAddresses(
|
||||
final Serializable userid);
|
||||
// 获取在线用户的详细连接信息
|
||||
public CompletableFuture<Map<InetSocketAddress, List<String>>> getRpcNodeWebSocketAddresses(
|
||||
final Serializable userid);
|
||||
|
||||
// 发送PING消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPing();
|
||||
// 发送PING消息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPing();
|
||||
|
||||
// 发送PING消息,附带其他信息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPing(byte[] data);
|
||||
// 发送PING消息,附带其他信息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPing(byte[] data);
|
||||
|
||||
// 发送PONG消息,附带其他信息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPong(byte[] data);
|
||||
// 发送PONG消息,附带其他信息 返回结果0表示成功,非0表示错误码
|
||||
public CompletableFuture<Integer> sendPong(byte[] data);
|
||||
|
||||
// 强制关闭用户的所有WebSocket
|
||||
public CompletableFuture<Integer> forceCloseWebSocket(Serializable userid);
|
||||
// 强制关闭用户的所有WebSocket
|
||||
public CompletableFuture<Integer> forceCloseWebSocket(Serializable userid);
|
||||
|
||||
// 更改本WebSocket的userid
|
||||
public CompletableFuture<Void> changeUserid(final G newuserid);
|
||||
// 更改本WebSocket的userid
|
||||
public CompletableFuture<Void> changeUserid(final G newuserid);
|
||||
|
||||
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户多连接模式
|
||||
/* protected */ Stream<WebSocket> getLocalWebSockets(G userid);
|
||||
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户多连接模式
|
||||
/* protected */ Stream<WebSocket> getLocalWebSockets(G userid);
|
||||
|
||||
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户单连接模式
|
||||
/* protected */ WebSocket findLocalWebSocket(G userid);
|
||||
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户单连接模式
|
||||
/* protected */ WebSocket findLocalWebSocket(G userid);
|
||||
|
||||
// 获取当前进程节点所有在线的WebSocket
|
||||
/* protected */ Collection<WebSocket> getLocalWebSockets();
|
||||
// 获取当前进程节点所有在线的WebSocket
|
||||
/* protected */ Collection<WebSocket> getLocalWebSockets();
|
||||
|
||||
// 获取ByteBuffer资源池
|
||||
/* protected */ Supplier<ByteBuffer> getByteBufferSupplier();
|
||||
// 获取ByteBuffer资源池
|
||||
/* protected */ Supplier<ByteBuffer> getByteBufferSupplier();
|
||||
|
||||
// 返回sessionid, null表示连接不合法或异常,默认实现是request.sessionid(true),通常需要重写该方法
|
||||
/* protected */ CompletableFuture<String> onOpen(final HttpRequest request);
|
||||
// 返回sessionid, null表示连接不合法或异常,默认实现是request.sessionid(true),通常需要重写该方法
|
||||
/* protected */ CompletableFuture<String> onOpen(final HttpRequest request);
|
||||
|
||||
// 创建userid, null表示异常, 必须实现该方法
|
||||
/* protected abstract */ CompletableFuture<G> createUserid();
|
||||
// 创建userid, null表示异常, 必须实现该方法
|
||||
/* protected abstract */ CompletableFuture<G> createUserid();
|
||||
|
||||
// WebSocket.broadcastMessage时的过滤条件
|
||||
/* protected */ boolean predicate(WebSocketRange wsrange);
|
||||
// WebSocket.broadcastMessage时的过滤条件
|
||||
/* protected */ boolean predicate(WebSocketRange wsrange);
|
||||
|
||||
// WebSokcet连接成功后的回调方法
|
||||
public void onConnected();
|
||||
// WebSokcet连接成功后的回调方法
|
||||
public void onConnected();
|
||||
|
||||
// ping后的回调方法
|
||||
public void onPing(byte[] bytes);
|
||||
// ping后的回调方法
|
||||
public void onPing(byte[] bytes);
|
||||
|
||||
// pong后的回调方法
|
||||
public void onPong(byte[] bytes);
|
||||
// pong后的回调方法
|
||||
public void onPong(byte[] bytes);
|
||||
|
||||
// 接收到消息的回调方法
|
||||
public void onMessage(T message, boolean last);
|
||||
// 接收到消息的回调方法
|
||||
public void onMessage(T message, boolean last);
|
||||
|
||||
// 接收到文本消息的回调方法
|
||||
public void onMessage(String message, boolean last);
|
||||
// 接收到文本消息的回调方法
|
||||
public void onMessage(String message, boolean last);
|
||||
|
||||
// 接收到二进制消息的回调方法
|
||||
public void onMessage(byte[] bytes, boolean last);
|
||||
// 接收到二进制消息的回调方法
|
||||
public void onMessage(byte[] bytes, boolean last);
|
||||
|
||||
// 关闭的回调方法,调用此方法时WebSocket已经被关闭
|
||||
public void onClose(int code, String reason);
|
||||
// 关闭的回调方法,调用此方法时WebSocket已经被关闭
|
||||
public void onClose(int code, String reason);
|
||||
|
||||
// 获取当前WebSocket下的属性
|
||||
public T getAttribute(String name);
|
||||
// 获取当前WebSocket下的属性
|
||||
public T getAttribute(String name);
|
||||
|
||||
// 移出当前WebSocket下的属性
|
||||
public T removeAttribute(String name);
|
||||
// 移出当前WebSocket下的属性
|
||||
public T removeAttribute(String name);
|
||||
|
||||
// 给当前WebSocket下的增加属性
|
||||
public void setAttribute(String name, Object value);
|
||||
// 给当前WebSocket下的增加属性
|
||||
public void setAttribute(String name, Object value);
|
||||
|
||||
// 获取当前WebSocket所属的userid
|
||||
public G getUserid();
|
||||
// 获取当前WebSocket所属的userid
|
||||
public G getUserid();
|
||||
|
||||
// 获取当前WebSocket的会话ID, 不会为null
|
||||
public Serializable getSessionid();
|
||||
// 获取当前WebSocket的会话ID, 不会为null
|
||||
public Serializable getSessionid();
|
||||
|
||||
// 获取客户端直接地址, 当WebSocket连接是由代理服务器转发的,则该值固定为代理服务器的IP地址
|
||||
public SocketAddress getRemoteAddress();
|
||||
// 获取客户端直接地址, 当WebSocket连接是由代理服务器转发的,则该值固定为代理服务器的IP地址
|
||||
public SocketAddress getRemoteAddress();
|
||||
|
||||
// 获取客户端真实地址 同 HttpRequest.getRemoteAddr()
|
||||
public String getRemoteAddr();
|
||||
// 获取客户端真实地址 同 HttpRequest.getRemoteAddr()
|
||||
public String getRemoteAddr();
|
||||
|
||||
// 获取WebSocket创建时间
|
||||
public long getCreatetime();
|
||||
// 获取WebSocket创建时间
|
||||
public long getCreatetime();
|
||||
|
||||
// 获取最后一次发送消息的时间
|
||||
public long getLastSendTime();
|
||||
// 获取最后一次发送消息的时间
|
||||
public long getLastSendTime();
|
||||
|
||||
// 获取最后一次读取消息的时间
|
||||
public long getLastReadTime();
|
||||
// 获取最后一次读取消息的时间
|
||||
public long getLastReadTime();
|
||||
|
||||
// 获取最后一次ping的时间
|
||||
public long getLastPingTime();
|
||||
// 获取最后一次ping的时间
|
||||
public long getLastPingTime();
|
||||
|
||||
// 显式地关闭WebSocket
|
||||
public void close();
|
||||
// 显式地关闭WebSocket
|
||||
public void close();
|
||||
|
||||
// WebSocket是否已关闭
|
||||
public boolean isClosed();
|
||||
// WebSocket是否已关闭
|
||||
public boolean isClosed();
|
||||
}
|
||||
|
||||
@@ -19,63 +19,63 @@ import org.redkale.inject.ResourceFactory;
|
||||
/** @author zhangjx */
|
||||
public class ResourceAnnotationTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceAnnotationTest test = new ResourceAnnotationTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceAnnotationTest test = new ResourceAnnotationTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new CustomConfProvider());
|
||||
InjectBean bean = new InjectBean();
|
||||
factory.inject(bean);
|
||||
if (!main) Assertions.assertEquals(new File("conf/test.xml").toString(), bean.conf.toString());
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new CustomConfProvider());
|
||||
InjectBean bean = new InjectBean();
|
||||
factory.inject(bean);
|
||||
if (!main) Assertions.assertEquals(new File("conf/test.xml").toString(), bean.conf.toString());
|
||||
}
|
||||
|
||||
public static class CustomConfProvider implements ResourceAnnotationLoader<CustomConf> {
|
||||
public static class CustomConfProvider implements ResourceAnnotationLoader<CustomConf> {
|
||||
|
||||
@Override
|
||||
public void load(
|
||||
ResourceFactory factory,
|
||||
String srcResourceName,
|
||||
Object srcObj,
|
||||
CustomConf annotation,
|
||||
Field field,
|
||||
Object attachment) {
|
||||
try {
|
||||
field.set(srcObj, new File(annotation.path()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("对象是 src =" + srcObj + ", path=" + annotation.path());
|
||||
}
|
||||
@Override
|
||||
public void load(
|
||||
ResourceFactory factory,
|
||||
String srcResourceName,
|
||||
Object srcObj,
|
||||
CustomConf annotation,
|
||||
Field field,
|
||||
Object attachment) {
|
||||
try {
|
||||
field.set(srcObj, new File(annotation.path()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("对象是 src =" + srcObj + ", path=" + annotation.path());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<CustomConf> annotationType() {
|
||||
return CustomConf.class;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public Class<CustomConf> annotationType() {
|
||||
return CustomConf.class;
|
||||
}
|
||||
}
|
||||
|
||||
public static class InjectBean {
|
||||
public static class InjectBean {
|
||||
|
||||
@CustomConf(path = "conf/test.xml")
|
||||
public File conf;
|
||||
@CustomConf(path = "conf/test.xml")
|
||||
public File conf;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@Documented
|
||||
@Target({FIELD})
|
||||
@Retention(RUNTIME)
|
||||
public static @interface CustomConf {
|
||||
@Documented
|
||||
@Target({FIELD})
|
||||
@Retention(RUNTIME)
|
||||
public static @interface CustomConf {
|
||||
|
||||
String path();
|
||||
}
|
||||
String path();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,52 +14,52 @@ import org.redkale.service.Service;
|
||||
/** @author zhangjx */
|
||||
public class ResourceInjectedTest {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceInjectedTest test = new ResourceInjectedTest();
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceInjectedTest test = new ResourceInjectedTest();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("res.id", "2345");
|
||||
factory.register("res.name", "my old name");
|
||||
ResourceService res = new ResourceService();
|
||||
factory.inject(res);
|
||||
factory.register("", res);
|
||||
RoomService serice = new RoomService();
|
||||
factory.inject(serice);
|
||||
Assertions.assertEquals(1, ResourceService.counter.get());
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("res.id", "2345");
|
||||
factory.register("res.name", "my old name");
|
||||
ResourceService res = new ResourceService();
|
||||
factory.inject(res);
|
||||
factory.register("", res);
|
||||
RoomService serice = new RoomService();
|
||||
factory.inject(serice);
|
||||
Assertions.assertEquals(1, ResourceService.counter.get());
|
||||
}
|
||||
|
||||
public static class RoomService implements Service {
|
||||
public static class RoomService implements Service {
|
||||
|
||||
@Resource
|
||||
private ResourceService resService;
|
||||
@Resource
|
||||
private ResourceService resService;
|
||||
|
||||
public void test() {
|
||||
resService.doing();
|
||||
}
|
||||
}
|
||||
public void test() {
|
||||
resService.doing();
|
||||
}
|
||||
}
|
||||
|
||||
public static class ResourceService implements Service {
|
||||
public static class ResourceService implements Service {
|
||||
|
||||
private static final AtomicInteger counter = new AtomicInteger();
|
||||
private static final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
@Resource(name = "res.id")
|
||||
private int id;
|
||||
@Resource(name = "res.id")
|
||||
private int id;
|
||||
|
||||
@Resource(name = "res.name")
|
||||
private String name;
|
||||
@Resource(name = "res.name")
|
||||
private String name;
|
||||
|
||||
@ResourceInjected
|
||||
private void onInjected(Object src, String fieldName) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println("资源被注入到对象(" + src + ")的字段(" + fieldName + ")上");
|
||||
}
|
||||
@ResourceInjected
|
||||
private void onInjected(Object src, String fieldName) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println("资源被注入到对象(" + src + ")的字段(" + fieldName + ")上");
|
||||
}
|
||||
|
||||
public void doing() {
|
||||
System.out.println("id = " + id + ", name = " + name);
|
||||
}
|
||||
}
|
||||
public void doing() {
|
||||
System.out.println("id = " + id + ", name = " + name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,127 +14,127 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class ResourceListenerTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceListenerTest test = new ResourceListenerTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceListenerTest test = new ResourceListenerTest();
|
||||
test.main = true;
|
||||
test.run1();
|
||||
test.run2();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Properties env = new Properties();
|
||||
env.put("property.id", "2345");
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new Environment(env));
|
||||
@Test
|
||||
public void run1() throws Exception {
|
||||
Properties env = new Properties();
|
||||
env.put("property.id", "2345");
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new Environment(env));
|
||||
|
||||
AService aservice = new AService();
|
||||
BService bservice = new BService();
|
||||
ABService abservice = new ABService();
|
||||
AService aservice = new AService();
|
||||
BService bservice = new BService();
|
||||
ABService abservice = new ABService();
|
||||
|
||||
factory.inject(aservice);
|
||||
factory.inject(bservice);
|
||||
factory.inject(abservice);
|
||||
factory.inject(aservice);
|
||||
factory.inject(bservice);
|
||||
factory.inject(abservice);
|
||||
|
||||
Properties prop = new Properties();
|
||||
prop.put("property.id", "7890");
|
||||
prop.put("property.name", "my name");
|
||||
factory.register(prop, "", Environment.class);
|
||||
Properties prop = new Properties();
|
||||
prop.put("property.id", "7890");
|
||||
prop.put("property.name", "my name");
|
||||
factory.register(prop, "", Environment.class);
|
||||
|
||||
Assertions.assertEquals("7890", aservice.id);
|
||||
Assertions.assertTrue(aservice.counter.get() == 1);
|
||||
Assertions.assertTrue(bservice.counter.get() == 2);
|
||||
Assertions.assertTrue(abservice.counter.get() == 2);
|
||||
Assertions.assertEquals("7890", aservice.id);
|
||||
Assertions.assertTrue(aservice.counter.get() == 1);
|
||||
Assertions.assertTrue(bservice.counter.get() == 2);
|
||||
Assertions.assertTrue(abservice.counter.get() == 2);
|
||||
|
||||
factory.register("property.id", "7777");
|
||||
factory.register("property.id", "7777");
|
||||
|
||||
Assertions.assertTrue(aservice.counter.get() == 2);
|
||||
Assertions.assertTrue(bservice.counter.get() == 2);
|
||||
Assertions.assertTrue(abservice.counter.get() == 3);
|
||||
}
|
||||
Assertions.assertTrue(aservice.counter.get() == 2);
|
||||
Assertions.assertTrue(bservice.counter.get() == 2);
|
||||
Assertions.assertTrue(abservice.counter.get() == 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
Properties env = new Properties();
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new Environment(env));
|
||||
AService aservice = new AService();
|
||||
factory.inject(aservice);
|
||||
Assertions.assertEquals("33", aservice.id);
|
||||
factory.register("property.id", "7777");
|
||||
Assertions.assertEquals("7777", aservice.id);
|
||||
}
|
||||
@Test
|
||||
public void run2() throws Exception {
|
||||
Properties env = new Properties();
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register(new Environment(env));
|
||||
AService aservice = new AService();
|
||||
factory.inject(aservice);
|
||||
Assertions.assertEquals("33", aservice.id);
|
||||
factory.register("property.id", "7777");
|
||||
Assertions.assertEquals("7777", aservice.id);
|
||||
}
|
||||
|
||||
class AService {
|
||||
class AService {
|
||||
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
@Resource(name = "${property.id:33}", required = false)
|
||||
private String id;
|
||||
@Resource(name = "${property.id:33}", required = false)
|
||||
private String id;
|
||||
|
||||
@Resource(name = "property.desc", required = false)
|
||||
private String desc;
|
||||
@Resource(name = "property.desc", required = false)
|
||||
private String desc;
|
||||
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
}
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
}
|
||||
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
class BService {
|
||||
class BService {
|
||||
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
@Resource
|
||||
private Environment env;
|
||||
@Resource
|
||||
private Environment env;
|
||||
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
System.out.println(getClass().getSimpleName() + " env = " + env);
|
||||
}
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
System.out.println(getClass().getSimpleName() + " env = " + env);
|
||||
}
|
||||
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
class ABService {
|
||||
class ABService {
|
||||
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
public final AtomicInteger counter = new AtomicInteger();
|
||||
|
||||
@Resource(name = "property.id", required = false)
|
||||
private String id;
|
||||
@Resource(name = "property.id", required = false)
|
||||
private String id;
|
||||
|
||||
@Resource
|
||||
private Environment env;
|
||||
@Resource
|
||||
private Environment env;
|
||||
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
System.out.println(getClass().getSimpleName() + " env = " + env);
|
||||
}
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
counter.incrementAndGet();
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
System.out.println(getClass().getSimpleName() + " env = " + env);
|
||||
}
|
||||
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
public String test() {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,52 +10,52 @@ import org.redkale.inject.ResourceFactory;
|
||||
/** @author zhangjx */
|
||||
public class ResourceLoaderTest {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceLoaderTest test = new ResourceLoaderTest();
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceLoaderTest test = new ResourceLoaderTest();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("a.id", 1234);
|
||||
factory.register("a.name", "my a name");
|
||||
factory.register("b.id", 4321);
|
||||
factory.register("b.name", "my b name");
|
||||
Bean bean = new Bean();
|
||||
factory.register("a", bean);
|
||||
factory.inject("a", bean);
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("a.id", 1234);
|
||||
factory.register("a.name", "my a name");
|
||||
factory.register("b.id", 4321);
|
||||
factory.register("b.name", "my b name");
|
||||
Bean bean = new Bean();
|
||||
factory.register("a", bean);
|
||||
factory.inject("a", bean);
|
||||
|
||||
ParentBean pb = new ParentBean();
|
||||
factory.inject(pb);
|
||||
Assertions.assertEquals(new Bean(1234, "my a name").toString(), pb.bean.toString());
|
||||
System.out.println(pb.bean);
|
||||
}
|
||||
ParentBean pb = new ParentBean();
|
||||
factory.inject(pb);
|
||||
Assertions.assertEquals(new Bean(1234, "my a name").toString(), pb.bean.toString());
|
||||
System.out.println(pb.bean);
|
||||
}
|
||||
|
||||
public static class ParentBean {
|
||||
public static class ParentBean {
|
||||
|
||||
@Resource(name = "a")
|
||||
public Bean bean;
|
||||
}
|
||||
@Resource(name = "a")
|
||||
public Bean bean;
|
||||
}
|
||||
|
||||
public static class Bean {
|
||||
public static class Bean {
|
||||
|
||||
@Resource(name = "@.id")
|
||||
public int id;
|
||||
@Resource(name = "@.id")
|
||||
public int id;
|
||||
|
||||
@Resource(name = "@.name")
|
||||
public String name;
|
||||
@Resource(name = "@.name")
|
||||
public String name;
|
||||
|
||||
public Bean() {}
|
||||
public Bean() {}
|
||||
|
||||
public Bean(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
public Bean(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,167 +15,167 @@ import org.redkale.inject.ResourceFactory;
|
||||
/** @author zhangjx */
|
||||
public class ResourceTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceTest test = new ResourceTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
ResourceTest test = new ResourceTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("id", "2345"); // 注入String类型的property.id
|
||||
AService aservice = new AService();
|
||||
BService bservice = new BService("eeeee");
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
factory.register("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.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.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("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("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}}}
|
||||
factory.register("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}}}
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("id", "5555");
|
||||
props.put("desc", "my desc");
|
||||
factory.register(props);
|
||||
Properties props = new Properties();
|
||||
props.put("id", "5555");
|
||||
props.put("desc", "my desc");
|
||||
factory.register(props);
|
||||
|
||||
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}}
|
||||
}
|
||||
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 = "${id}")
|
||||
private String id;
|
||||
@Resource(name = "${id}")
|
||||
private String id;
|
||||
|
||||
@Resource(name = "${desc}", required = false)
|
||||
private String desc;
|
||||
@Resource(name = "${desc}", required = false)
|
||||
private String desc;
|
||||
|
||||
@Resource
|
||||
private AService aservice;
|
||||
@Resource
|
||||
private AService aservice;
|
||||
|
||||
private String name = "";
|
||||
private String name = "";
|
||||
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
}
|
||||
@ResourceChanged
|
||||
private void changeResource(ResourceEvent[] events) {
|
||||
for (ResourceEvent event : events) {
|
||||
System.out.println(getClass().getSimpleName() + " @Resource = " + event.name() + " 资源变更: newVal = "
|
||||
+ event.newValue() + ", oldVal = " + event.oldValue());
|
||||
}
|
||||
}
|
||||
|
||||
@ConstructorParameters({"name"})
|
||||
public BService(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
@ConstructorParameters({"name"})
|
||||
public BService(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public AService getAservice() {
|
||||
return aservice;
|
||||
}
|
||||
public AService getAservice() {
|
||||
return aservice;
|
||||
}
|
||||
|
||||
public void setAservice(AService aservice) {
|
||||
this.aservice = aservice;
|
||||
}
|
||||
public void setAservice(AService aservice) {
|
||||
this.aservice = aservice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{name:\"" + name + "\", id: " + id + ", aserivce:" + aservice + "}";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{name:\"" + name + "\", id: " + id + ", aserivce:" + aservice + "}";
|
||||
}
|
||||
}
|
||||
|
||||
class AService {
|
||||
|
||||
@Resource(name = "${id}")
|
||||
private String id;
|
||||
@Resource(name = "${id}")
|
||||
private String id;
|
||||
|
||||
@Resource(name = "id") // property.开头的资源名允许String自动转换成primitive数值类型
|
||||
private int intid;
|
||||
@Resource(name = "id") // property.开头的资源名允许String自动转换成primitive数值类型
|
||||
private int intid;
|
||||
|
||||
@Resource(name = "bigint", required = false)
|
||||
private BigInteger bigint;
|
||||
@Resource(name = "bigint", required = false)
|
||||
private BigInteger bigint;
|
||||
|
||||
@Resource(name = "seqid", required = false)
|
||||
private int seqid;
|
||||
@Resource(name = "seqid", required = false)
|
||||
private int seqid;
|
||||
|
||||
@Resource
|
||||
private BService bservice;
|
||||
@Resource
|
||||
private BService bservice;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{id:\"" + id + "\", intid: " + intid + ", bigint:" + bigint + ", bservice:"
|
||||
+ (bservice == null ? null : ("{name:" + bservice.getName() + "}")) + "}";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{id:\"" + id + "\", intid: " + intid + ", bigint:" + bigint + ", bservice:"
|
||||
+ (bservice == null ? null : ("{name:" + bservice.getName() + "}")) + "}";
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getIntid() {
|
||||
return intid;
|
||||
}
|
||||
public int getIntid() {
|
||||
return intid;
|
||||
}
|
||||
|
||||
public void setIntid(int intid) {
|
||||
this.intid = intid;
|
||||
}
|
||||
public void setIntid(int intid) {
|
||||
this.intid = intid;
|
||||
}
|
||||
|
||||
public int getSeqid() {
|
||||
return seqid;
|
||||
}
|
||||
public int getSeqid() {
|
||||
return seqid;
|
||||
}
|
||||
|
||||
public void setSeqid(int seqid) {
|
||||
this.seqid = seqid;
|
||||
}
|
||||
public void setSeqid(int seqid) {
|
||||
this.seqid = seqid;
|
||||
}
|
||||
|
||||
public BigInteger getBigint() {
|
||||
return bigint;
|
||||
}
|
||||
public BigInteger getBigint() {
|
||||
return bigint;
|
||||
}
|
||||
|
||||
public void setBigint(BigInteger bigint) {
|
||||
this.bigint = bigint;
|
||||
}
|
||||
public void setBigint(BigInteger bigint) {
|
||||
this.bigint = bigint;
|
||||
}
|
||||
|
||||
public void setBservice(BService bservice) {
|
||||
this.bservice = bservice;
|
||||
}
|
||||
public void setBservice(BService bservice) {
|
||||
this.bservice = bservice;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,25 +15,25 @@ import org.redkale.convert.*;
|
||||
*/
|
||||
public class CreateTimeSimpleCoder<R extends Reader, W extends Writer> extends SimpledCoder<R, W, Long> {
|
||||
|
||||
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Override
|
||||
public void convertTo(W out, Long value) {
|
||||
if (value == null) {
|
||||
out.writeNull();
|
||||
} else {
|
||||
out.writeString(format.format(new java.util.Date(value)));
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void convertTo(W out, Long value) {
|
||||
if (value == null) {
|
||||
out.writeNull();
|
||||
} else {
|
||||
out.writeString(format.format(new java.util.Date(value)));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long convertFrom(R in) {
|
||||
String val = in.readString();
|
||||
if (val == null) return 0L;
|
||||
try {
|
||||
return format.parse(val).getTime();
|
||||
} catch (Exception e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public Long convertFrom(R in) {
|
||||
String val = in.readString();
|
||||
if (val == null) return 0L;
|
||||
try {
|
||||
return format.parse(val).getTime();
|
||||
} catch (Exception e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,14 @@ import java.nio.channels.CompletionHandler;
|
||||
/** @author zhangjx */
|
||||
public class HelloAsyncHandler implements CompletionHandler {
|
||||
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("-----HelloAsyncHandler--------result : " + result + ", attachment: " + attachment);
|
||||
}
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("-----HelloAsyncHandler--------result : " + result + ", attachment: " + attachment);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {
|
||||
throw new UnsupportedOperationException(
|
||||
"Not supported yet."); // To change body of generated methods, choose Tools | Templates.
|
||||
}
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {
|
||||
throw new UnsupportedOperationException(
|
||||
"Not supported yet."); // To change body of generated methods, choose Tools | Templates.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,63 +6,63 @@ import org.redkale.source.FilterBean;
|
||||
|
||||
public class HelloBean implements FilterBean {
|
||||
|
||||
private int helloid;
|
||||
private int helloid;
|
||||
|
||||
@RestHeader(name = "User-Agent")
|
||||
private String useragent; // 从Http Header中获取浏览器信息
|
||||
@RestHeader(name = "User-Agent")
|
||||
private String useragent; // 从Http Header中获取浏览器信息
|
||||
|
||||
@RestCookie(name = "hello-cookie")
|
||||
private String rescookie; // 从Cookie中获取名为hello-cookie的值
|
||||
@RestCookie(name = "hello-cookie")
|
||||
private String rescookie; // 从Cookie中获取名为hello-cookie的值
|
||||
|
||||
@RestAddress
|
||||
private String clientaddr; // 客户端请求IP
|
||||
@RestAddress
|
||||
private String clientaddr; // 客户端请求IP
|
||||
|
||||
@RestSessionid
|
||||
private String sessionid; // 用户Sessionid, 未登录时为null
|
||||
@RestSessionid
|
||||
private String sessionid; // 用户Sessionid, 未登录时为null
|
||||
|
||||
/** 以下省略getter setter方法 */
|
||||
public int getHelloid() {
|
||||
return helloid;
|
||||
}
|
||||
/** 以下省略getter setter方法 */
|
||||
public int getHelloid() {
|
||||
return helloid;
|
||||
}
|
||||
|
||||
public void setHelloid(int helloid) {
|
||||
this.helloid = helloid;
|
||||
}
|
||||
public void setHelloid(int helloid) {
|
||||
this.helloid = helloid;
|
||||
}
|
||||
|
||||
public String getUseragent() {
|
||||
return useragent;
|
||||
}
|
||||
public String getUseragent() {
|
||||
return useragent;
|
||||
}
|
||||
|
||||
public void setUseragent(String useragent) {
|
||||
this.useragent = useragent;
|
||||
}
|
||||
public void setUseragent(String useragent) {
|
||||
this.useragent = useragent;
|
||||
}
|
||||
|
||||
public String getRescookie() {
|
||||
return rescookie;
|
||||
}
|
||||
public String getRescookie() {
|
||||
return rescookie;
|
||||
}
|
||||
|
||||
public void setRescookie(String rescookie) {
|
||||
this.rescookie = rescookie;
|
||||
}
|
||||
public void setRescookie(String rescookie) {
|
||||
this.rescookie = rescookie;
|
||||
}
|
||||
|
||||
public String getClientaddr() {
|
||||
return clientaddr;
|
||||
}
|
||||
public String getClientaddr() {
|
||||
return clientaddr;
|
||||
}
|
||||
|
||||
public void setClientaddr(String clientaddr) {
|
||||
this.clientaddr = clientaddr;
|
||||
}
|
||||
public void setClientaddr(String clientaddr) {
|
||||
this.clientaddr = clientaddr;
|
||||
}
|
||||
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,143 +9,143 @@ import org.redkale.persistence.VirtualEntity;
|
||||
@VirtualEntity
|
||||
public class HelloEntity {
|
||||
|
||||
@Id
|
||||
private int helloid;
|
||||
@Id
|
||||
private int helloid;
|
||||
|
||||
private String helloname;
|
||||
private String helloname;
|
||||
|
||||
private int creator;
|
||||
private int creator;
|
||||
|
||||
private long updatetime;
|
||||
private long updatetime;
|
||||
|
||||
private long createtime;
|
||||
private long createtime;
|
||||
|
||||
@RestHeader(name = "hello-res")
|
||||
private String resname;
|
||||
@RestHeader(name = "hello-res")
|
||||
private String resname;
|
||||
|
||||
@RestBody
|
||||
private String bodystr;
|
||||
@RestBody
|
||||
private String bodystr;
|
||||
|
||||
@RestBody
|
||||
private byte[] bodys;
|
||||
@RestBody
|
||||
private byte[] bodys;
|
||||
|
||||
@RestUploadFile
|
||||
private byte[] uploads;
|
||||
@RestUploadFile
|
||||
private byte[] uploads;
|
||||
|
||||
@RestBody
|
||||
private Map<String, String> bodymap;
|
||||
@RestBody
|
||||
private Map<String, String> bodymap;
|
||||
|
||||
@RestAddress
|
||||
private String clientaddr;
|
||||
@RestAddress
|
||||
private String clientaddr;
|
||||
|
||||
@RestPath
|
||||
private String uri;
|
||||
@RestPath
|
||||
private String uri;
|
||||
|
||||
public HelloEntity() {}
|
||||
public HelloEntity() {}
|
||||
|
||||
public HelloEntity(int id) {
|
||||
this.helloid = id;
|
||||
}
|
||||
public HelloEntity(int id) {
|
||||
this.helloid = id;
|
||||
}
|
||||
|
||||
/** 以下省略getter setter方法 */
|
||||
public int getHelloid() {
|
||||
return helloid;
|
||||
}
|
||||
/** 以下省略getter setter方法 */
|
||||
public int getHelloid() {
|
||||
return helloid;
|
||||
}
|
||||
|
||||
public void setHelloid(int helloid) {
|
||||
this.helloid = helloid;
|
||||
}
|
||||
public void setHelloid(int helloid) {
|
||||
this.helloid = helloid;
|
||||
}
|
||||
|
||||
public String getHelloname() {
|
||||
return helloname;
|
||||
}
|
||||
public String getHelloname() {
|
||||
return helloname;
|
||||
}
|
||||
|
||||
public void setHelloname(String helloname) {
|
||||
this.helloname = helloname;
|
||||
}
|
||||
public void setHelloname(String helloname) {
|
||||
this.helloname = helloname;
|
||||
}
|
||||
|
||||
public long getUpdatetime() {
|
||||
return updatetime;
|
||||
}
|
||||
public long getUpdatetime() {
|
||||
return updatetime;
|
||||
}
|
||||
|
||||
public void setUpdatetime(long updatetime) {
|
||||
this.updatetime = updatetime;
|
||||
}
|
||||
public void setUpdatetime(long updatetime) {
|
||||
this.updatetime = updatetime;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
|
||||
public int getCreator() {
|
||||
return creator;
|
||||
}
|
||||
public int getCreator() {
|
||||
return creator;
|
||||
}
|
||||
|
||||
public void setCreator(int creator) {
|
||||
this.creator = creator;
|
||||
}
|
||||
public void setCreator(int creator) {
|
||||
this.creator = creator;
|
||||
}
|
||||
|
||||
public String getClientaddr() {
|
||||
return clientaddr;
|
||||
}
|
||||
public String getClientaddr() {
|
||||
return clientaddr;
|
||||
}
|
||||
|
||||
public void setClientaddr(String clientaddr) {
|
||||
this.clientaddr = clientaddr;
|
||||
}
|
||||
public void setClientaddr(String clientaddr) {
|
||||
this.clientaddr = clientaddr;
|
||||
}
|
||||
|
||||
public String getResname() {
|
||||
return resname;
|
||||
}
|
||||
public String getResname() {
|
||||
return resname;
|
||||
}
|
||||
|
||||
public void setResname(String resname) {
|
||||
this.resname = resname;
|
||||
}
|
||||
public void setResname(String resname) {
|
||||
this.resname = resname;
|
||||
}
|
||||
|
||||
public String getBodystr() {
|
||||
return bodystr;
|
||||
}
|
||||
public String getBodystr() {
|
||||
return bodystr;
|
||||
}
|
||||
|
||||
public void setBodystr(String bodystr) {
|
||||
this.bodystr = bodystr;
|
||||
}
|
||||
public void setBodystr(String bodystr) {
|
||||
this.bodystr = bodystr;
|
||||
}
|
||||
|
||||
public byte[] getBodys() {
|
||||
return bodys;
|
||||
}
|
||||
public byte[] getBodys() {
|
||||
return bodys;
|
||||
}
|
||||
|
||||
public void setBodys(byte[] bodys) {
|
||||
this.bodys = bodys;
|
||||
}
|
||||
public void setBodys(byte[] bodys) {
|
||||
this.bodys = bodys;
|
||||
}
|
||||
|
||||
public Map<String, String> getBodymap() {
|
||||
return bodymap;
|
||||
}
|
||||
public Map<String, String> getBodymap() {
|
||||
return bodymap;
|
||||
}
|
||||
|
||||
public void setBodymap(Map<String, String> bodymap) {
|
||||
this.bodymap = bodymap;
|
||||
}
|
||||
public void setBodymap(Map<String, String> bodymap) {
|
||||
this.bodymap = bodymap;
|
||||
}
|
||||
|
||||
public byte[] getUploads() {
|
||||
return uploads;
|
||||
}
|
||||
public byte[] getUploads() {
|
||||
return uploads;
|
||||
}
|
||||
|
||||
public void setUploads(byte[] uploads) {
|
||||
this.uploads = uploads;
|
||||
}
|
||||
public void setUploads(byte[] uploads) {
|
||||
this.uploads = uploads;
|
||||
}
|
||||
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
public String getUri() {
|
||||
return uri;
|
||||
}
|
||||
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
public void setUri(String uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,117 +14,117 @@ import org.redkale.util.*;
|
||||
@RestService(autoMapping = true)
|
||||
public class HelloService implements Service {
|
||||
|
||||
private int nodeid;
|
||||
private int nodeid;
|
||||
|
||||
@Resource
|
||||
private DataSource source;
|
||||
@Resource
|
||||
private DataSource source;
|
||||
|
||||
public HelloService() {}
|
||||
public HelloService() {}
|
||||
|
||||
public HelloService(int nodeid) {
|
||||
this.nodeid = nodeid;
|
||||
}
|
||||
public HelloService(int nodeid) {
|
||||
this.nodeid = nodeid;
|
||||
}
|
||||
|
||||
// 增加记录
|
||||
public RetResult<HelloEntity> createHello(UserInfo info, HelloEntity entity, @RestBody Map<String, String> body) {
|
||||
System.out.println("增加记录----------------" + nodeid + ": body =" + body + ", entity =" + entity);
|
||||
entity.setCreator(info == null ? 0 : info.getUserid()); // 设置当前用户ID
|
||||
entity.setCreatetime(System.currentTimeMillis());
|
||||
if (source != null) source.insert(entity);
|
||||
return new RetResult<>(entity);
|
||||
}
|
||||
// 增加记录
|
||||
public RetResult<HelloEntity> createHello(UserInfo info, HelloEntity entity, @RestBody Map<String, String> body) {
|
||||
System.out.println("增加记录----------------" + nodeid + ": body =" + body + ", entity =" + entity);
|
||||
entity.setCreator(info == null ? 0 : info.getUserid()); // 设置当前用户ID
|
||||
entity.setCreatetime(System.currentTimeMillis());
|
||||
if (source != null) source.insert(entity);
|
||||
return new RetResult<>(entity);
|
||||
}
|
||||
|
||||
//
|
||||
public HttpResult showHello(int id) {
|
||||
return new HttpResult("a");
|
||||
}
|
||||
//
|
||||
public HttpResult showHello(int id) {
|
||||
return new HttpResult("a");
|
||||
}
|
||||
|
||||
// 删除记录
|
||||
public void deleteHello(int id) { // 通过 /pipes/hello/delete/1234 删除对象
|
||||
source.delete(HelloEntity.class, id);
|
||||
}
|
||||
// 删除记录
|
||||
public void deleteHello(int id) { // 通过 /pipes/hello/delete/1234 删除对象
|
||||
source.delete(HelloEntity.class, id);
|
||||
}
|
||||
|
||||
// 修改记录
|
||||
public void updateHello(
|
||||
@RestAddress String clientAddr, HelloEntity entity) { // 通过 /pipes/hello/update?bean={...} 修改对象
|
||||
System.out.println("修改记录-" + nodeid + ": clientAddr = " + clientAddr + ", entity =" + entity);
|
||||
if (entity != null) entity.setUpdatetime(System.currentTimeMillis());
|
||||
if (source != null) source.update(entity);
|
||||
}
|
||||
// 修改记录
|
||||
public void updateHello(
|
||||
@RestAddress String clientAddr, HelloEntity entity) { // 通过 /pipes/hello/update?bean={...} 修改对象
|
||||
System.out.println("修改记录-" + nodeid + ": clientAddr = " + clientAddr + ", entity =" + entity);
|
||||
if (entity != null) entity.setUpdatetime(System.currentTimeMillis());
|
||||
if (source != null) source.update(entity);
|
||||
}
|
||||
|
||||
// 修改记录
|
||||
public void update2Hello(
|
||||
@RestAddress String clientAddr, @RestUploadFile byte[] fs) { // 通过 /pipes/hello/update2?bean={...} 修改对象
|
||||
System.out.println("修改记录2-" + nodeid + ": clientAddr = " + clientAddr + ", fs =" + fs);
|
||||
}
|
||||
// 修改记录
|
||||
public void update2Hello(
|
||||
@RestAddress String clientAddr, @RestUploadFile byte[] fs) { // 通过 /pipes/hello/update2?bean={...} 修改对象
|
||||
System.out.println("修改记录2-" + nodeid + ": clientAddr = " + clientAddr + ", fs =" + fs);
|
||||
}
|
||||
|
||||
// 修改记录
|
||||
@RestMapping(name = "partupdate")
|
||||
public void updateHello(
|
||||
HelloEntity entity,
|
||||
@RestParam(name = "cols") String[] columns) { // 通过 /pipes/hello/partupdate?bean={...}&cols=... 修改对象
|
||||
entity.setUpdatetime(System.currentTimeMillis());
|
||||
source.updateColumn(entity, columns);
|
||||
}
|
||||
// 修改记录
|
||||
@RestMapping(name = "partupdate")
|
||||
public void updateHello(
|
||||
HelloEntity entity,
|
||||
@RestParam(name = "cols") String[] columns) { // 通过 /pipes/hello/partupdate?bean={...}&cols=... 修改对象
|
||||
entity.setUpdatetime(System.currentTimeMillis());
|
||||
source.updateColumn(entity, columns);
|
||||
}
|
||||
|
||||
// 查询Sheet列表
|
||||
public Sheet<HelloEntity> queryHello(
|
||||
HelloBean bean, Flipper flipper) { // 通过 /pipes/hello/query/offset:0/limit:20?bean={...} 查询Sheet列表
|
||||
return source.querySheet(HelloEntity.class, flipper, bean);
|
||||
}
|
||||
// 查询Sheet列表
|
||||
public Sheet<HelloEntity> queryHello(
|
||||
HelloBean bean, Flipper flipper) { // 通过 /pipes/hello/query/offset:0/limit:20?bean={...} 查询Sheet列表
|
||||
return source.querySheet(HelloEntity.class, flipper, bean);
|
||||
}
|
||||
|
||||
// 查询List列表
|
||||
@RestMapping(name = "list")
|
||||
@RestConvert(
|
||||
type = HelloEntity.class,
|
||||
ignoreColumns = {"createtime"})
|
||||
public List<HelloEntity> queryHello(HelloBean bean) { // 通过 /pipes/hello/list?bean={...} 查询List列表
|
||||
return source.queryList(HelloEntity.class, bean);
|
||||
}
|
||||
// 查询List列表
|
||||
@RestMapping(name = "list")
|
||||
@RestConvert(
|
||||
type = HelloEntity.class,
|
||||
ignoreColumns = {"createtime"})
|
||||
public List<HelloEntity> queryHello(HelloBean bean) { // 通过 /pipes/hello/list?bean={...} 查询List列表
|
||||
return source.queryList(HelloEntity.class, bean);
|
||||
}
|
||||
|
||||
// 查询List列表
|
||||
@RestMapping(name = "listmap")
|
||||
public List<HelloEntity> queryHello(
|
||||
HelloBean bean,
|
||||
@RestParam(name = "map") Map<String, String> map) { // 通过 /pipes/hello/list?bean={...} 查询List列表
|
||||
System.out.println("map参数: " + map);
|
||||
if (source != null) return source.queryList(HelloEntity.class, bean);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
// 查询List列表
|
||||
@RestMapping(name = "listmap")
|
||||
public List<HelloEntity> queryHello(
|
||||
HelloBean bean,
|
||||
@RestParam(name = "map") Map<String, String> map) { // 通过 /pipes/hello/list?bean={...} 查询List列表
|
||||
System.out.println("map参数: " + map);
|
||||
if (source != null) return source.queryList(HelloEntity.class, bean);
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
// 查询单个
|
||||
@RestMapping(name = "find")
|
||||
public HelloEntity findHello(
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
return source.find(HelloEntity.class, id);
|
||||
}
|
||||
// 查询单个
|
||||
@RestMapping(name = "find")
|
||||
public HelloEntity findHello(
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
return source.find(HelloEntity.class, id);
|
||||
}
|
||||
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind")
|
||||
public CompletableFuture<HelloEntity> asyncFindHello(
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("------------进入asyncfind1-------");
|
||||
return CompletableFuture.completedFuture(new HelloEntity());
|
||||
}
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind")
|
||||
public CompletableFuture<HelloEntity> asyncFindHello(
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("------------进入asyncfind1-------");
|
||||
return CompletableFuture.completedFuture(new HelloEntity());
|
||||
}
|
||||
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind2")
|
||||
public void asyncFindHello(
|
||||
CompletionHandler hander,
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("-----------进入asyncfind2--------" + hander);
|
||||
hander.completed(new HelloEntity(id), id);
|
||||
}
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind2")
|
||||
public void asyncFindHello(
|
||||
CompletionHandler hander,
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("-----------进入asyncfind2--------" + hander);
|
||||
hander.completed(new HelloEntity(id), id);
|
||||
}
|
||||
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind3")
|
||||
public void asyncFindHello(
|
||||
HelloAsyncHandler hander,
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("-----------进入asyncfind3--------" + hander);
|
||||
hander.completed(new HelloEntity(id), id);
|
||||
}
|
||||
// 异步查询单个
|
||||
@RestMapping(name = "asyncfind3")
|
||||
public void asyncFindHello(
|
||||
HelloAsyncHandler hander,
|
||||
@RestParam(name = "#") int id) { // 通过 /pipes/hello/find/1234、/pipes/hello/jsfind/1234 查询对象
|
||||
if (source != null) source.findAsync(HelloEntity.class, id);
|
||||
System.out.println("-----------进入asyncfind3--------" + hander);
|
||||
hander.completed(new HelloEntity(id), id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,45 +15,45 @@ import org.redkale.util.Sheet;
|
||||
@RestService(name = "hello", moduleid = 0, autoMapping = true, repair = true, ignore = false, comment = "Hello服务模块")
|
||||
public class HelloService2 implements Service {
|
||||
|
||||
@Resource
|
||||
private DataSource source;
|
||||
@Resource
|
||||
private DataSource source;
|
||||
|
||||
// 增加记录
|
||||
@RestMapping(name = "create", auth = false, comment = "创建Hello对象")
|
||||
public RetResult<HelloEntity> createHello(
|
||||
UserInfo info, @RestParam(name = "bean", comment = "Hello对象") HelloEntity entity) {
|
||||
entity.setCreator(info == null ? 0 : info.getUserid()); // 设置当前用户ID
|
||||
entity.setCreatetime(System.currentTimeMillis());
|
||||
source.insert(entity);
|
||||
return new RetResult<>(entity);
|
||||
}
|
||||
// 增加记录
|
||||
@RestMapping(name = "create", auth = false, comment = "创建Hello对象")
|
||||
public RetResult<HelloEntity> createHello(
|
||||
UserInfo info, @RestParam(name = "bean", comment = "Hello对象") HelloEntity entity) {
|
||||
entity.setCreator(info == null ? 0 : info.getUserid()); // 设置当前用户ID
|
||||
entity.setCreatetime(System.currentTimeMillis());
|
||||
source.insert(entity);
|
||||
return new RetResult<>(entity);
|
||||
}
|
||||
|
||||
// 删除记录
|
||||
@RestMapping(name = "delete", auth = false, comment = "根据id删除Hello对象")
|
||||
public void deleteHello(@RestParam(name = "#", comment = "Hello对象id") int id) { // 通过 /hello/delete/1234 删除对象
|
||||
source.delete(HelloEntity.class, id);
|
||||
}
|
||||
// 删除记录
|
||||
@RestMapping(name = "delete", auth = false, comment = "根据id删除Hello对象")
|
||||
public void deleteHello(@RestParam(name = "#", comment = "Hello对象id") int id) { // 通过 /hello/delete/1234 删除对象
|
||||
source.delete(HelloEntity.class, id);
|
||||
}
|
||||
|
||||
// 修改记录
|
||||
@RestMapping(name = "update", auth = false, comment = "修改Hello对象")
|
||||
public void updateHello(
|
||||
@RestParam(name = "bean", comment = "Hello对象") HelloEntity entity) { // 通过 /hello/update?bean={...} 修改对象
|
||||
entity.setUpdatetime(System.currentTimeMillis());
|
||||
source.update(entity);
|
||||
}
|
||||
// 修改记录
|
||||
@RestMapping(name = "update", auth = false, comment = "修改Hello对象")
|
||||
public void updateHello(
|
||||
@RestParam(name = "bean", comment = "Hello对象") HelloEntity entity) { // 通过 /hello/update?bean={...} 修改对象
|
||||
entity.setUpdatetime(System.currentTimeMillis());
|
||||
source.update(entity);
|
||||
}
|
||||
|
||||
// 查询列表
|
||||
@RestConvertCoder(type = HelloEntity.class, field = "createtime", coder = CreateTimeSimpleCoder.class)
|
||||
@RestMapping(name = "query", auth = false, comment = "查询Hello对象列表")
|
||||
public Sheet<HelloEntity> queryHello(
|
||||
@RestParam(name = "bean", comment = "过滤条件") HelloBean bean,
|
||||
Flipper flipper) { // 通过 /hello/query/offset:0/limit:20?bean={...} 查询列表
|
||||
return source.querySheet(HelloEntity.class, flipper, bean);
|
||||
}
|
||||
// 查询列表
|
||||
@RestConvertCoder(type = HelloEntity.class, field = "createtime", coder = CreateTimeSimpleCoder.class)
|
||||
@RestMapping(name = "query", auth = false, comment = "查询Hello对象列表")
|
||||
public Sheet<HelloEntity> queryHello(
|
||||
@RestParam(name = "bean", comment = "过滤条件") HelloBean bean,
|
||||
Flipper flipper) { // 通过 /hello/query/offset:0/limit:20?bean={...} 查询列表
|
||||
return source.querySheet(HelloEntity.class, flipper, bean);
|
||||
}
|
||||
|
||||
// 查询单个
|
||||
@RestMapping(name = "find", auth = false, comment = "根据id查找单个Hello对象")
|
||||
public HelloEntity findHello(@RestParam(name = "#", comment = "Hello对象id") int id) { // 通过 /hello/find/1234 查询对象
|
||||
return source.find(HelloEntity.class, id);
|
||||
}
|
||||
// 查询单个
|
||||
@RestMapping(name = "find", auth = false, comment = "根据id查找单个Hello对象")
|
||||
public HelloEntity findHello(@RestParam(name = "#", comment = "Hello对象id") int id) { // 通过 /hello/find/1234 查询对象
|
||||
return source.find(HelloEntity.class, id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,30 +14,30 @@ import org.redkale.convert.json.JsonFactory;
|
||||
*/
|
||||
public class LoginBean {
|
||||
|
||||
// 账号
|
||||
private String account = "";
|
||||
// 账号
|
||||
private String account = "";
|
||||
|
||||
// 密码
|
||||
private String password = "";
|
||||
// 密码
|
||||
private String password = "";
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,146 +12,146 @@ import org.redkale.service.*;
|
||||
/** @author zhangjx */
|
||||
public abstract class RetCodes {
|
||||
|
||||
protected static final Map<Integer, String> rets = new HashMap<>();
|
||||
protected static final Map<Integer, String> rets = new HashMap<>();
|
||||
|
||||
protected RetCodes() {}
|
||||
// -----------------------------------------------------------------------------------------------------------
|
||||
protected RetCodes() {}
|
||||
// -----------------------------------------------------------------------------------------------------------
|
||||
|
||||
protected static void load(Class clazz) {
|
||||
for (Field field : clazz.getFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (field.getType() != int.class) continue;
|
||||
RetLabel info = field.getAnnotation(RetLabel.class);
|
||||
if (info == null) continue;
|
||||
int value;
|
||||
try {
|
||||
value = field.getInt(null);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
continue;
|
||||
}
|
||||
rets.put(value, info.value());
|
||||
}
|
||||
}
|
||||
protected static void load(Class clazz) {
|
||||
for (Field field : clazz.getFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (field.getType() != int.class) continue;
|
||||
RetLabel info = field.getAnnotation(RetLabel.class);
|
||||
if (info == null) continue;
|
||||
int value;
|
||||
try {
|
||||
value = field.getInt(null);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
continue;
|
||||
}
|
||||
rets.put(value, info.value());
|
||||
}
|
||||
}
|
||||
|
||||
public static RetResult retResult(int retcode) {
|
||||
if (retcode == 0) return RetResult.success();
|
||||
return new RetResult(retcode, retInfo(retcode));
|
||||
}
|
||||
public static RetResult retResult(int retcode) {
|
||||
if (retcode == 0) return RetResult.success();
|
||||
return new RetResult(retcode, retInfo(retcode));
|
||||
}
|
||||
|
||||
public static String retInfo(int retcode) {
|
||||
if (retcode == 0) return "成功";
|
||||
return rets.getOrDefault(retcode, "未知错误");
|
||||
}
|
||||
public static String retInfo(int retcode) {
|
||||
if (retcode == 0) return "成功";
|
||||
return rets.getOrDefault(retcode, "未知错误");
|
||||
}
|
||||
|
||||
// 2000_0001 - 2999_9999 预留给 Redkale的扩展包redkalex使用
|
||||
// 3000_0001 - 7999_9999 为平台系统使用
|
||||
// 8000_0001 - 9999_9999 为OSS系统使用
|
||||
// ------------------------------------- 通用模块 -----------------------------------------
|
||||
@RetLabel("参数无效")
|
||||
public static final int RET_PARAMS_ILLEGAL = 30010001;
|
||||
// 2000_0001 - 2999_9999 预留给 Redkale的扩展包redkalex使用
|
||||
// 3000_0001 - 7999_9999 为平台系统使用
|
||||
// 8000_0001 - 9999_9999 为OSS系统使用
|
||||
// ------------------------------------- 通用模块 -----------------------------------------
|
||||
@RetLabel("参数无效")
|
||||
public static final int RET_PARAMS_ILLEGAL = 30010001;
|
||||
|
||||
@RetLabel("无上传文件")
|
||||
public static final int RET_UPLOAD_NOFILE = 30010002;
|
||||
@RetLabel("无上传文件")
|
||||
public static final int RET_UPLOAD_NOFILE = 30010002;
|
||||
|
||||
@RetLabel("上传文件过大")
|
||||
public static final int RET_UPLOAD_FILETOOBIG = 30010003;
|
||||
@RetLabel("上传文件过大")
|
||||
public static final int RET_UPLOAD_FILETOOBIG = 30010003;
|
||||
|
||||
@RetLabel("上传文件不是图片")
|
||||
public static final int RET_UPLOAD_NOTIMAGE = 30010004;
|
||||
@RetLabel("上传文件不是图片")
|
||||
public static final int RET_UPLOAD_NOTIMAGE = 30010004;
|
||||
|
||||
// ------------------------------------- 用户模块 -----------------------------------------
|
||||
@RetLabel("未登录")
|
||||
public static final int RET_USER_UNLOGIN = 30020001;
|
||||
// ------------------------------------- 用户模块 -----------------------------------------
|
||||
@RetLabel("未登录")
|
||||
public static final int RET_USER_UNLOGIN = 30020001;
|
||||
|
||||
@RetLabel("用户登录失败")
|
||||
public static final int RET_USER_LOGIN_FAIL = 30020002;
|
||||
@RetLabel("用户登录失败")
|
||||
public static final int RET_USER_LOGIN_FAIL = 30020002;
|
||||
|
||||
@RetLabel("用户或密码错误")
|
||||
public static final int RET_USER_ACCOUNT_PWD_ILLEGAL = 30020003;
|
||||
@RetLabel("用户或密码错误")
|
||||
public static final int RET_USER_ACCOUNT_PWD_ILLEGAL = 30020003;
|
||||
|
||||
@RetLabel("密码设置无效")
|
||||
public static final int RET_USER_PASSWORD_ILLEGAL = 30020004;
|
||||
@RetLabel("密码设置无效")
|
||||
public static final int RET_USER_PASSWORD_ILLEGAL = 30020004;
|
||||
|
||||
@RetLabel("用户被禁用")
|
||||
public static final int RET_USER_FREEZED = 30020005;
|
||||
@RetLabel("用户被禁用")
|
||||
public static final int RET_USER_FREEZED = 30020005;
|
||||
|
||||
@RetLabel("用户权限不够")
|
||||
public static final int RET_USER_AUTH_ILLEGAL = 30020006;
|
||||
@RetLabel("用户权限不够")
|
||||
public static final int RET_USER_AUTH_ILLEGAL = 30020006;
|
||||
|
||||
@RetLabel("用户不存在")
|
||||
public static final int RET_USER_NOTEXISTS = 30020007;
|
||||
@RetLabel("用户不存在")
|
||||
public static final int RET_USER_NOTEXISTS = 30020007;
|
||||
|
||||
@RetLabel("用户状态异常")
|
||||
public static final int RET_USER_STATUS_ILLEGAL = 30020008;
|
||||
@RetLabel("用户状态异常")
|
||||
public static final int RET_USER_STATUS_ILLEGAL = 30020008;
|
||||
|
||||
@RetLabel("用户注册参数无效")
|
||||
public static final int RET_USER_SIGNUP_ILLEGAL = 30020009;
|
||||
@RetLabel("用户注册参数无效")
|
||||
public static final int RET_USER_SIGNUP_ILLEGAL = 30020009;
|
||||
|
||||
@RetLabel("用户性别参数无效")
|
||||
public static final int RET_USER_GENDER_ILLEGAL = 30020010;
|
||||
@RetLabel("用户性别参数无效")
|
||||
public static final int RET_USER_GENDER_ILLEGAL = 30020010;
|
||||
|
||||
@RetLabel("用户名无效")
|
||||
public static final int RET_USER_USERNAME_ILLEGAL = 30020011;
|
||||
@RetLabel("用户名无效")
|
||||
public static final int RET_USER_USERNAME_ILLEGAL = 30020011;
|
||||
|
||||
@RetLabel("用户账号无效")
|
||||
public static final int RET_USER_ACCOUNT_ILLEGAL = 30020012;
|
||||
@RetLabel("用户账号无效")
|
||||
public static final int RET_USER_ACCOUNT_ILLEGAL = 30020012;
|
||||
|
||||
@RetLabel("用户账号已存在")
|
||||
public static final int RET_USER_ACCOUNT_EXISTS = 30020013;
|
||||
@RetLabel("用户账号已存在")
|
||||
public static final int RET_USER_ACCOUNT_EXISTS = 30020013;
|
||||
|
||||
@RetLabel("手机号码无效")
|
||||
public static final int RET_USER_MOBILE_ILLEGAL = 30020014;
|
||||
@RetLabel("手机号码无效")
|
||||
public static final int RET_USER_MOBILE_ILLEGAL = 30020014;
|
||||
|
||||
@RetLabel("手机号码已存在")
|
||||
public static final int RET_USER_MOBILE_EXISTS = 30020015;
|
||||
@RetLabel("手机号码已存在")
|
||||
public static final int RET_USER_MOBILE_EXISTS = 30020015;
|
||||
|
||||
@RetLabel("手机验证码发送过于频繁")
|
||||
public static final int RET_USER_MOBILE_SMSFREQUENT = 30020016;
|
||||
@RetLabel("手机验证码发送过于频繁")
|
||||
public static final int RET_USER_MOBILE_SMSFREQUENT = 30020016;
|
||||
|
||||
@RetLabel("邮箱地址无效")
|
||||
public static final int RET_USER_EMAIL_ILLEGAL = 30020017;
|
||||
@RetLabel("邮箱地址无效")
|
||||
public static final int RET_USER_EMAIL_ILLEGAL = 30020017;
|
||||
|
||||
@RetLabel("邮箱地址已存在")
|
||||
public static final int RET_USER_EMAIL_EXISTS = 30020018;
|
||||
@RetLabel("邮箱地址已存在")
|
||||
public static final int RET_USER_EMAIL_EXISTS = 30020018;
|
||||
|
||||
@RetLabel("微信绑定号无效")
|
||||
public static final int RET_USER_WXID_ILLEGAL = 30020019;
|
||||
@RetLabel("微信绑定号无效")
|
||||
public static final int RET_USER_WXID_ILLEGAL = 30020019;
|
||||
|
||||
@RetLabel("微信绑定号已存在")
|
||||
public static final int RET_USER_WXID_EXISTS = 30020020;
|
||||
@RetLabel("微信绑定号已存在")
|
||||
public static final int RET_USER_WXID_EXISTS = 30020020;
|
||||
|
||||
@RetLabel("绑定微信号失败")
|
||||
public static final int RET_USER_WXID_BIND_FAIL = 30020021;
|
||||
@RetLabel("绑定微信号失败")
|
||||
public static final int RET_USER_WXID_BIND_FAIL = 30020021;
|
||||
|
||||
@RetLabel("QQ绑定号无效")
|
||||
public static final int RET_USER_QQID_ILLEGAL = 30020022;
|
||||
@RetLabel("QQ绑定号无效")
|
||||
public static final int RET_USER_QQID_ILLEGAL = 30020022;
|
||||
|
||||
@RetLabel("QQ绑定号已存在")
|
||||
public static final int RET_USER_QQID_EXISTS = 30020023;
|
||||
@RetLabel("QQ绑定号已存在")
|
||||
public static final int RET_USER_QQID_EXISTS = 30020023;
|
||||
|
||||
@RetLabel("绑定QQ号失败")
|
||||
public static final int RET_USER_QQID_BIND_FAIL = 30020024;
|
||||
@RetLabel("绑定QQ号失败")
|
||||
public static final int RET_USER_QQID_BIND_FAIL = 30020024;
|
||||
|
||||
@RetLabel("获取绑定QQ信息失败")
|
||||
public static final int RET_USER_QQID_INFO_FAIL = 30020025;
|
||||
@RetLabel("获取绑定QQ信息失败")
|
||||
public static final int RET_USER_QQID_INFO_FAIL = 30020025;
|
||||
|
||||
@RetLabel("验证码无效")
|
||||
public static final int RET_USER_RANDCODE_ILLEGAL = 30020026; // 邮件或者短信验证码
|
||||
@RetLabel("验证码无效")
|
||||
public static final int RET_USER_RANDCODE_ILLEGAL = 30020026; // 邮件或者短信验证码
|
||||
|
||||
@RetLabel("验证码已过期")
|
||||
public static final int RET_USER_RANDCODE_EXPIRED = 30020027; // 邮件或者短信验证码
|
||||
@RetLabel("验证码已过期")
|
||||
public static final int RET_USER_RANDCODE_EXPIRED = 30020027; // 邮件或者短信验证码
|
||||
|
||||
@RetLabel("验证码错误或失效")
|
||||
public static final int RET_USER_CAPTCHA_ILLEGAL = 30020028; // 图片验证码
|
||||
@RetLabel("验证码错误或失效")
|
||||
public static final int RET_USER_CAPTCHA_ILLEGAL = 30020028; // 图片验证码
|
||||
|
||||
@RetLabel("用户类型无效")
|
||||
public static final int RET_USER_TYPE_ILLEGAL = 30020029;
|
||||
@RetLabel("用户类型无效")
|
||||
public static final int RET_USER_TYPE_ILLEGAL = 30020029;
|
||||
|
||||
@RetLabel("用户设备ID无效")
|
||||
public static final int RET_USER_APPTOKEN_ILLEGAL = 30020030;
|
||||
@RetLabel("用户设备ID无效")
|
||||
public static final int RET_USER_APPTOKEN_ILLEGAL = 30020030;
|
||||
|
||||
static {
|
||||
load(RetCodes.class);
|
||||
}
|
||||
static {
|
||||
load(RetCodes.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,31 +7,31 @@ import org.redkale.service.RetResult;
|
||||
|
||||
public class SimpleRestServlet extends HttpServlet {
|
||||
|
||||
protected static final RetResult RET_UNLOGIN = RetCodes.retResult(RetCodes.RET_USER_UNLOGIN);
|
||||
protected static final RetResult RET_UNLOGIN = RetCodes.retResult(RetCodes.RET_USER_UNLOGIN);
|
||||
|
||||
protected static final RetResult RET_AUTHILLEGAL = RetCodes.retResult(RetCodes.RET_USER_AUTH_ILLEGAL);
|
||||
protected static final RetResult RET_AUTHILLEGAL = RetCodes.retResult(RetCodes.RET_USER_AUTH_ILLEGAL);
|
||||
|
||||
@Resource
|
||||
private UserService userService = new UserService();
|
||||
@Resource
|
||||
private UserService userService = new UserService();
|
||||
|
||||
@Override
|
||||
public void preExecute(HttpRequest request, HttpResponse response) throws IOException {
|
||||
final String sessionid = request.getSessionid(true);
|
||||
if (sessionid != null) {
|
||||
UserInfo user = userService.current(sessionid);
|
||||
if (user != null) request.setCurrentUserid(user.getUserid());
|
||||
}
|
||||
response.nextEvent();
|
||||
}
|
||||
@Override
|
||||
public void preExecute(HttpRequest request, HttpResponse response) throws IOException {
|
||||
final String sessionid = request.getSessionid(true);
|
||||
if (sessionid != null) {
|
||||
UserInfo user = userService.current(sessionid);
|
||||
if (user != null) request.setCurrentUserid(user.getUserid());
|
||||
}
|
||||
response.nextEvent();
|
||||
}
|
||||
|
||||
// 普通鉴权
|
||||
@Override
|
||||
public void authenticate(HttpRequest request, HttpResponse response) throws IOException {
|
||||
int userid = request.currentUserid(int.class);
|
||||
if (userid < 1) {
|
||||
response.finishJson(RET_UNLOGIN);
|
||||
return;
|
||||
}
|
||||
response.nextEvent();
|
||||
}
|
||||
// 普通鉴权
|
||||
@Override
|
||||
public void authenticate(HttpRequest request, HttpResponse response) throws IOException {
|
||||
int userid = request.currentUserid(int.class);
|
||||
if (userid < 1) {
|
||||
response.finishJson(RET_UNLOGIN);
|
||||
return;
|
||||
}
|
||||
response.nextEvent();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,35 +10,35 @@ import org.redkale.persistence.Id;
|
||||
*/
|
||||
public class UserInfo {
|
||||
|
||||
@Id
|
||||
private int userid;
|
||||
@Id
|
||||
private int userid;
|
||||
|
||||
private String username = "";
|
||||
private String username = "";
|
||||
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public boolean checkAuth(int moduleid, int actionid) {
|
||||
if (moduleid == 0 || actionid == 0) return true;
|
||||
// 权限判断
|
||||
return true;
|
||||
}
|
||||
public boolean checkAuth(int moduleid, int actionid) {
|
||||
if (moduleid == 0 || actionid == 0) return true;
|
||||
// 权限判断
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonFactory.root().getConvert().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,17 +14,17 @@ import org.redkale.service.*;
|
||||
*/
|
||||
public class UserService implements Service {
|
||||
|
||||
/**
|
||||
* 根据登录态获取当前用户信息
|
||||
*
|
||||
* @param sessionid
|
||||
* @return
|
||||
*/
|
||||
public UserInfo current(String sessionid) {
|
||||
return new UserInfo();
|
||||
}
|
||||
/**
|
||||
* 根据登录态获取当前用户信息
|
||||
*
|
||||
* @param sessionid
|
||||
* @return
|
||||
*/
|
||||
public UserInfo current(String sessionid) {
|
||||
return new UserInfo();
|
||||
}
|
||||
|
||||
public RetResult<UserInfo> login(LoginBean bean) {
|
||||
return new RetResult<>(new UserInfo());
|
||||
}
|
||||
public RetResult<UserInfo> login(LoginBean bean) {
|
||||
return new RetResult<>(new UserInfo());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,168 +10,168 @@ import org.redkale.source.Flipper;
|
||||
import org.redkale.util.*;
|
||||
|
||||
@WebServlet(
|
||||
value = {"/hello/*"},
|
||||
repair = true)
|
||||
value = {"/hello/*"},
|
||||
repair = true)
|
||||
public class _DynHelloRestServlet1 extends SimpleRestServlet {
|
||||
|
||||
@Resource
|
||||
private HelloService _redkale_service;
|
||||
@Resource
|
||||
private HelloService _redkale_service;
|
||||
|
||||
@Resource
|
||||
private Map<String, HelloService> _redkale_servicemap;
|
||||
@Resource
|
||||
private Map<String, HelloService> _redkale_servicemap;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
final int port = 8888;
|
||||
HelloService service = new HelloService();
|
||||
HttpServer server = new HttpServer();
|
||||
public static void main(String[] args) throws Throwable {
|
||||
final int port = 8888;
|
||||
HelloService service = new HelloService();
|
||||
HttpServer server = new HttpServer();
|
||||
|
||||
System.out.println(server.addRestServlet(null, service, null, SimpleRestServlet.class, "/pipes"));
|
||||
System.out.println(server.addRestServlet(null, new HelloService(3), null, SimpleRestServlet.class, "/pipes"));
|
||||
System.out.println(server.addRestServlet(null, service, null, SimpleRestServlet.class, "/pipes"));
|
||||
System.out.println(server.addRestServlet(null, new HelloService(3), null, SimpleRestServlet.class, "/pipes"));
|
||||
|
||||
AnyValueWriter conf = AnyValueWriter.create("port", "" + port);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
Utility.sleep(100);
|
||||
AnyValueWriter conf = AnyValueWriter.create("port", "" + port);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
Utility.sleep(100);
|
||||
|
||||
HelloEntity entity = new HelloEntity();
|
||||
entity.setHelloname("my name");
|
||||
Map<String, Serializable> headers = new HashMap<>();
|
||||
headers.put("hello-res", "my res");
|
||||
// headers.put(Rest.REST_HEADER_RESNAME, "my-res");
|
||||
String url = "http://127.0.0.1:" + port + "/pipes/hello/update?entity={}&bean2={}";
|
||||
System.out.println(Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/update2?entity={}&bean2={}";
|
||||
System.out.println(Utility.postHttpContent(url, headers, null));
|
||||
HelloEntity entity = new HelloEntity();
|
||||
entity.setHelloname("my name");
|
||||
Map<String, Serializable> headers = new HashMap<>();
|
||||
headers.put("hello-res", "my res");
|
||||
// headers.put(Rest.REST_HEADER_RESNAME, "my-res");
|
||||
String url = "http://127.0.0.1:" + port + "/pipes/hello/update?entity={}&bean2={}";
|
||||
System.out.println(Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/update2?entity={}&bean2={}";
|
||||
System.out.println(Utility.postHttpContent(url, headers, null));
|
||||
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind/1234";
|
||||
System.out.println("异步查找: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind/1234";
|
||||
System.out.println("异步查找: " + Utility.postHttpContent(url, headers, null));
|
||||
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/listmap?map={'a':5}";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/listmap?map={'a':5}";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/create?entity={}";
|
||||
System.out.println("增加记录: " + Utility.postHttpContent(url, headers, "{'a':2,'b':3}"));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/create?entity={}";
|
||||
System.out.println("增加记录: " + Utility.postHttpContent(url, headers, "{'a':2,'b':3}"));
|
||||
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind/111111";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind2/22222";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind3/333333";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
}
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind/111111";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind2/22222";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
url = "http://127.0.0.1:" + port + "/pipes/hello/asyncfind3/333333";
|
||||
System.out.println("listmap: " + Utility.postHttpContent(url, headers, null));
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/create", auth = false)
|
||||
public void create(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
UserInfo user = new UserInfo();
|
||||
RetResult<HelloEntity> result = service.createHello(user, bean, req.getBodyJson(Map.class));
|
||||
resp.finishJson(result);
|
||||
}
|
||||
@HttpMapping(url = "/hello/create", auth = false)
|
||||
public void create(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
UserInfo user = new UserInfo();
|
||||
RetResult<HelloEntity> result = service.createHello(user, bean, req.getBodyJson(Map.class));
|
||||
resp.finishJson(result);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/delete/", auth = false)
|
||||
public void delete(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.deleteHello(id);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
@HttpMapping(url = "/hello/delete/", auth = false)
|
||||
public void delete(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.deleteHello(id);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/update", auth = false)
|
||||
public void update(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
String clientaddr = req.getRemoteAddr();
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
service.updateHello(clientaddr, bean);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
@HttpMapping(url = "/hello/update", auth = false)
|
||||
public void update(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
String clientaddr = req.getRemoteAddr();
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
service.updateHello(clientaddr, bean);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/partupdate", auth = false)
|
||||
public void partupdate(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
String[] cols = req.getJsonParameter(String[].class, "cols");
|
||||
service.updateHello(bean, cols);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
@HttpMapping(url = "/hello/partupdate", auth = false)
|
||||
public void partupdate(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
String[] cols = req.getJsonParameter(String[].class, "cols");
|
||||
service.updateHello(bean, cols);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/query", auth = false)
|
||||
public void query(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
Flipper flipper = req.getFlipper();
|
||||
Sheet<HelloEntity> result = service.queryHello(bean, flipper);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
@HttpMapping(url = "/hello/query", auth = false)
|
||||
public void query(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
Flipper flipper = req.getFlipper();
|
||||
Sheet<HelloEntity> result = service.queryHello(bean, flipper);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/list", auth = false)
|
||||
public void list(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
List<HelloEntity> result = service.queryHello(bean);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
@HttpMapping(url = "/hello/list", auth = false)
|
||||
public void list(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
List<HelloEntity> result = service.queryHello(bean);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/find/", auth = false)
|
||||
public void find(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
HelloEntity bean = service.findHello(id);
|
||||
resp.finishJson(bean);
|
||||
}
|
||||
@HttpMapping(url = "/hello/find/", auth = false)
|
||||
public void find(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
HelloEntity bean = service.findHello(id);
|
||||
resp.finishJson(bean);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/asyncfind/", auth = false)
|
||||
public void asyncfind(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
resp.finishJson(service.asyncFindHello(id));
|
||||
}
|
||||
@HttpMapping(url = "/hello/asyncfind/", auth = false)
|
||||
public void asyncfind(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
resp.finishJson(service.asyncFindHello(id));
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/asyncfind2/", auth = false)
|
||||
public void asyncfind2(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.asyncFindHello(resp.createAsyncHandler(), id);
|
||||
}
|
||||
@HttpMapping(url = "/hello/asyncfind2/", auth = false)
|
||||
public void asyncfind2(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.asyncFindHello(resp.createAsyncHandler(), id);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/asyncfind3/", auth = false)
|
||||
public void asyncfind3(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.asyncFindHello(resp.createAsyncHandler(HelloAsyncHandler.class), id);
|
||||
}
|
||||
@HttpMapping(url = "/hello/asyncfind3/", auth = false)
|
||||
public void asyncfind3(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.asyncFindHello(resp.createAsyncHandler(HelloAsyncHandler.class), id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,82 +15,82 @@ import org.redkale.util.*;
|
||||
|
||||
/** @author zhangjx */
|
||||
@WebServlet(
|
||||
value = {"/hello/*"},
|
||||
repair = true)
|
||||
value = {"/hello/*"},
|
||||
repair = true)
|
||||
public class _DynHelloRestServlet2 extends SimpleRestServlet {
|
||||
|
||||
@Resource
|
||||
private HelloService2 _redkale_service;
|
||||
@Resource
|
||||
private HelloService2 _redkale_service;
|
||||
|
||||
@Resource
|
||||
private Map<String, HelloService2> _redkale_servicemap;
|
||||
@Resource
|
||||
private Map<String, HelloService2> _redkale_servicemap;
|
||||
|
||||
@HttpMapping(url = "/hello/create", auth = false, comment = "创建Hello对象")
|
||||
@HttpParam(name = "bean", type = HelloEntity.class, comment = "Hello对象")
|
||||
public void create(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
bean.setBodys(req.getBody());
|
||||
bean.setBodystr(req.getBodyUTF8());
|
||||
UserInfo user = new UserInfo();
|
||||
RetResult<HelloEntity> result = service.createHello(user, bean);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
@HttpMapping(url = "/hello/create", auth = false, comment = "创建Hello对象")
|
||||
@HttpParam(name = "bean", type = HelloEntity.class, comment = "Hello对象")
|
||||
public void create(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
bean.setBodys(req.getBody());
|
||||
bean.setBodystr(req.getBodyUTF8());
|
||||
UserInfo user = new UserInfo();
|
||||
RetResult<HelloEntity> result = service.createHello(user, bean);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/delete/", auth = false, comment = "根据id删除Hello对象")
|
||||
@HttpParam(name = "#", type = int.class, comment = "Hello对象id")
|
||||
public void delete(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.deleteHello(id);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
@HttpMapping(url = "/hello/delete/", auth = false, comment = "根据id删除Hello对象")
|
||||
@HttpParam(name = "#", type = int.class, comment = "Hello对象id")
|
||||
public void delete(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
service.deleteHello(id);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/update", auth = false, comment = "修改Hello对象")
|
||||
@HttpParam(name = "bean", type = HelloEntity.class, comment = "Hello对象")
|
||||
public void update(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
bean.setBodys(req.getBody());
|
||||
bean.setBodystr(req.getBodyUTF8());
|
||||
service.updateHello(bean);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
@HttpMapping(url = "/hello/update", auth = false, comment = "修改Hello对象")
|
||||
@HttpParam(name = "bean", type = HelloEntity.class, comment = "Hello对象")
|
||||
public void update(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloEntity bean = req.getJsonParameter(HelloEntity.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setResname(req.getHeader("hello-res"));
|
||||
bean.setBodys(req.getBody());
|
||||
bean.setBodystr(req.getBodyUTF8());
|
||||
service.updateHello(bean);
|
||||
resp.finishJson(RetResult.success());
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/query", auth = false, comment = "查询Hello对象列表")
|
||||
@HttpParam(name = "bean", type = HelloBean.class, comment = "过滤条件")
|
||||
public void query(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
Flipper flipper = req.getFlipper();
|
||||
Sheet<HelloEntity> result = service.queryHello(bean, flipper);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
@HttpMapping(url = "/hello/query", auth = false, comment = "查询Hello对象列表")
|
||||
@HttpParam(name = "bean", type = HelloBean.class, comment = "过滤条件")
|
||||
public void query(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
HelloBean bean = req.getJsonParameter(HelloBean.class, "bean");
|
||||
bean.setClientaddr(req.getRemoteAddr());
|
||||
bean.setUseragent(req.getHeader("User-Agent"));
|
||||
bean.setRescookie(req.getCookie("hello-cookie"));
|
||||
bean.setSessionid(req.getSessionid(false));
|
||||
Flipper flipper = req.getFlipper();
|
||||
Sheet<HelloEntity> result = service.queryHello(bean, flipper);
|
||||
resp.finishJson(result);
|
||||
}
|
||||
|
||||
@HttpMapping(url = "/hello/find/", auth = false, comment = "根据id删除Hello对象")
|
||||
@HttpParam(name = "#", type = int.class, comment = "Hello对象id")
|
||||
public void find(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
HelloEntity bean = service.findHello(id);
|
||||
resp.finishJson(bean);
|
||||
}
|
||||
@HttpMapping(url = "/hello/find/", auth = false, comment = "根据id删除Hello对象")
|
||||
@HttpParam(name = "#", type = int.class, comment = "Hello对象id")
|
||||
public void find(HttpRequest req, HttpResponse resp) throws IOException {
|
||||
HelloService2 service = _redkale_servicemap == null
|
||||
? _redkale_service
|
||||
: _redkale_servicemap.get(req.getHeader(Rest.REST_HEADER_RESNAME, ""));
|
||||
int id = Integer.parseInt(req.getPathLastParam());
|
||||
HelloEntity bean = service.findHello(id);
|
||||
resp.finishJson(bean);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,19 +10,19 @@ import org.redkale.util.Times;
|
||||
/** @author zhangjx */
|
||||
public class ScheduleService implements Service {
|
||||
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
public void task1() {
|
||||
System.out.println(Times.nowMillis() + "每秒-----------执行task1");
|
||||
}
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
public void task1() {
|
||||
System.out.println(Times.nowMillis() + "每秒-----------执行task1");
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
public String task2() {
|
||||
System.out.println(Times.nowMillis() + "每秒*****执行task2");
|
||||
return "";
|
||||
}
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
public String task2() {
|
||||
System.out.println(Times.nowMillis() + "每秒*****执行task2");
|
||||
return "";
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
private void task3() {
|
||||
System.out.println(Times.nowMillis() + "每秒执行task3");
|
||||
}
|
||||
@Scheduled(cron = "0/1 * * * * ?")
|
||||
private void task3() {
|
||||
System.out.println(Times.nowMillis() + "每秒执行task3");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,19 +10,19 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class SchedulingTest {
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SchedulingTest test = new SchedulingTest();
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SchedulingTest test = new SchedulingTest();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ScheduleManagerService manager = ScheduleManagerService.create(null);
|
||||
manager.init(null);
|
||||
ScheduleService service = new ScheduleService();
|
||||
manager.schedule(service);
|
||||
Utility.sleep(3000);
|
||||
manager.unschedule(service);
|
||||
manager.destroy(null);
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
ScheduleManagerService manager = ScheduleManagerService.create(null);
|
||||
manager.init(null);
|
||||
ScheduleService service = new ScheduleService();
|
||||
manager.schedule(service);
|
||||
Utility.sleep(3000);
|
||||
manager.unschedule(service);
|
||||
manager.destroy(null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,221 +29,221 @@ import org.redkale.util.*;
|
||||
@RestService(name = "abmain")
|
||||
public class ABMainService implements Service {
|
||||
|
||||
private static final int abport = 8866;
|
||||
private static final int abport = 8866;
|
||||
|
||||
@Resource
|
||||
private BCService bcService;
|
||||
@Resource
|
||||
private BCService bcService;
|
||||
|
||||
public static void remote(String[] args) throws Throwable {
|
||||
System.out.println("------------------- 远程模式调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", abport);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
rpcGroups.computeIfAbsent("g77", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5577));
|
||||
rpcGroups.computeIfAbsent("g88", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5588));
|
||||
rpcGroups.computeIfAbsent("g99", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5599));
|
||||
public static void remote(String[] args) throws Throwable {
|
||||
System.out.println("------------------- 远程模式调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", abport);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
rpcGroups.computeIfAbsent("g77", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5577));
|
||||
rpcGroups.computeIfAbsent("g88", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5588));
|
||||
rpcGroups.computeIfAbsent("g99", "TCP").putAddress(new InetSocketAddress("127.0.0.1", 5599));
|
||||
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
CService cservice = Sncp.createSimpleLocalService(CService.class, resFactory);
|
||||
SncpServer cserver = new SncpServer();
|
||||
cserver.getResourceFactory().register(application);
|
||||
// cserver.getLogger().setLevel(Level.WARNING);
|
||||
cserver.addSncpServlet(cservice);
|
||||
cserver.init(AnyValueWriter.create("port", 5577));
|
||||
cserver.start();
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
CService cservice = Sncp.createSimpleLocalService(CService.class, resFactory);
|
||||
SncpServer cserver = new SncpServer();
|
||||
cserver.getResourceFactory().register(application);
|
||||
// cserver.getLogger().setLevel(Level.WARNING);
|
||||
cserver.addSncpServlet(cservice);
|
||||
cserver.init(AnyValueWriter.create("port", 5577));
|
||||
cserver.start();
|
||||
|
||||
// ------------------------ 初始化 BCService ------------------------------------
|
||||
BCService bcservice = Sncp.createSimpleLocalService(BCService.class, resFactory);
|
||||
CService remoteCService = Sncp.createSimpleRemoteService(CService.class, resFactory, rpcGroups, client, "g77");
|
||||
if (remoteCService != null) {
|
||||
resFactory.inject(remoteCService);
|
||||
resFactory.register("", remoteCService);
|
||||
}
|
||||
SncpServer bcserver = new SncpServer();
|
||||
bcserver.getResourceFactory().register(application);
|
||||
// bcserver.getLogger().setLevel(Level.WARNING);
|
||||
bcserver.addSncpServlet(bcservice);
|
||||
bcserver.init(AnyValueWriter.create("port", 5588));
|
||||
bcserver.start();
|
||||
// ------------------------ 初始化 BCService ------------------------------------
|
||||
BCService bcservice = Sncp.createSimpleLocalService(BCService.class, resFactory);
|
||||
CService remoteCService = Sncp.createSimpleRemoteService(CService.class, resFactory, rpcGroups, client, "g77");
|
||||
if (remoteCService != null) {
|
||||
resFactory.inject(remoteCService);
|
||||
resFactory.register("", remoteCService);
|
||||
}
|
||||
SncpServer bcserver = new SncpServer();
|
||||
bcserver.getResourceFactory().register(application);
|
||||
// bcserver.getLogger().setLevel(Level.WARNING);
|
||||
bcserver.addSncpServlet(bcservice);
|
||||
bcserver.init(AnyValueWriter.create("port", 5588));
|
||||
bcserver.start();
|
||||
|
||||
// ------------------------ 初始化 ABMainService ------------------------------------
|
||||
ABMainService service = Sncp.createSimpleLocalService(ABMainService.class, resFactory);
|
||||
BCService remoteBCService =
|
||||
Sncp.createSimpleRemoteService(BCService.class, resFactory, rpcGroups, client, "g88");
|
||||
if (remoteBCService != null) {
|
||||
resFactory.inject(remoteBCService);
|
||||
resFactory.register("", remoteBCService);
|
||||
}
|
||||
// ------------------------ 初始化 ABMainService ------------------------------------
|
||||
ABMainService service = Sncp.createSimpleLocalService(ABMainService.class, resFactory);
|
||||
BCService remoteBCService =
|
||||
Sncp.createSimpleRemoteService(BCService.class, resFactory, rpcGroups, client, "g88");
|
||||
if (remoteBCService != null) {
|
||||
resFactory.inject(remoteBCService);
|
||||
resFactory.register("", remoteBCService);
|
||||
}
|
||||
|
||||
resFactory.inject(cservice);
|
||||
resFactory.inject(bcservice);
|
||||
resFactory.inject(service);
|
||||
resFactory.inject(cservice);
|
||||
resFactory.inject(bcservice);
|
||||
resFactory.inject(service);
|
||||
|
||||
HttpServer server = new HttpServer();
|
||||
server.getResourceFactory().register(application);
|
||||
// server.getLogger().setLevel(Level.WARNING);
|
||||
HttpServer server = new HttpServer();
|
||||
server.getResourceFactory().register(application);
|
||||
// server.getLogger().setLevel(Level.WARNING);
|
||||
|
||||
server.init(AnyValueWriter.create("port", abport));
|
||||
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
|
||||
server.start();
|
||||
Utility.sleep(100);
|
||||
System.out.println("开始请求");
|
||||
server.init(AnyValueWriter.create("port", abport));
|
||||
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
|
||||
server.start();
|
||||
Utility.sleep(100);
|
||||
System.out.println("开始请求");
|
||||
|
||||
// 不声明一个新的HttpClient会导致Utility.postHttpContent操作
|
||||
// 同一url在Utility里的httpClient会缓存导致调用是吧,应该是httpClient的bug
|
||||
java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
|
||||
System.out.println("httpclient类: " + httpClient.getClass().getName());
|
||||
// 同步方法
|
||||
String url = "http://127.0.0.1:" + abport + "/pipes/abmain/sab/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
// 不声明一个新的HttpClient会导致Utility.postHttpContent操作
|
||||
// 同一url在Utility里的httpClient会缓存导致调用是吧,应该是httpClient的bug
|
||||
java.net.http.HttpClient httpClient = java.net.http.HttpClient.newHttpClient();
|
||||
System.out.println("httpclient类: " + httpClient.getClass().getName());
|
||||
// 同步方法
|
||||
String url = "http://127.0.0.1:" + abport + "/pipes/abmain/sab/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc2/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc2/张先生";
|
||||
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
|
||||
.join());
|
||||
|
||||
server.shutdown();
|
||||
bcserver.shutdown();
|
||||
cserver.shutdown();
|
||||
}
|
||||
server.shutdown();
|
||||
bcserver.shutdown();
|
||||
cserver.shutdown();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoggingBaseHandler.initDebugLogConfig();
|
||||
System.out.println("------------------- 本地模式调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoggingBaseHandler.initDebugLogConfig();
|
||||
System.out.println("------------------- 本地模式调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
ResourceFactory factory = ResourceFactory.create();
|
||||
|
||||
ABMainService service = new ABMainService();
|
||||
ABMainService service = new ABMainService();
|
||||
|
||||
BCService bcservice = new BCService();
|
||||
factory.register("", bcservice);
|
||||
factory.register("", new CService());
|
||||
factory.inject(bcservice);
|
||||
factory.inject(service);
|
||||
System.out.println("bcservice.name = " + bcservice.serviceName());
|
||||
System.out.println("bcservice.type = " + bcservice.serviceType());
|
||||
BCService bcservice = new BCService();
|
||||
factory.register("", bcservice);
|
||||
factory.register("", new CService());
|
||||
factory.inject(bcservice);
|
||||
factory.inject(service);
|
||||
System.out.println("bcservice.name = " + bcservice.serviceName());
|
||||
System.out.println("bcservice.type = " + bcservice.serviceType());
|
||||
|
||||
HttpServer server = new HttpServer();
|
||||
server.getResourceFactory().register(application);
|
||||
server.getLogger().setLevel(Level.WARNING);
|
||||
HttpServer server = new HttpServer();
|
||||
server.getResourceFactory().register(application);
|
||||
server.getLogger().setLevel(Level.WARNING);
|
||||
|
||||
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
|
||||
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
|
||||
|
||||
server.init(AnyValueWriter.create("port", "" + abport));
|
||||
server.start();
|
||||
Thread.sleep(100);
|
||||
server.init(AnyValueWriter.create("port", "" + abport));
|
||||
server.start();
|
||||
Thread.sleep(100);
|
||||
|
||||
System.out.println("开始请求");
|
||||
// 同步方法
|
||||
String url = "http://127.0.0.1:" + abport + "/pipes/abmain/sab/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
System.out.println("开始请求");
|
||||
// 同步方法
|
||||
String url = "http://127.0.0.1:" + abport + "/pipes/abmain/sab/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc2/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
// 异步方法
|
||||
url = "http://127.0.0.1:" + abport + "/pipes/abmain/abc2/张先生";
|
||||
System.out.println(Utility.postHttpContent(url));
|
||||
|
||||
server.shutdown();
|
||||
// 远程模式
|
||||
remote(args);
|
||||
}
|
||||
server.shutdown();
|
||||
// 远程模式
|
||||
remote(args);
|
||||
}
|
||||
|
||||
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 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<ByteBuffer> newBufferPool() {
|
||||
return ObjectPool.createSafePool(
|
||||
new LongAdder(),
|
||||
new LongAdder(),
|
||||
16,
|
||||
(Object... params) -> ByteBuffer.allocateDirect(8192),
|
||||
null,
|
||||
(e) -> {
|
||||
if (e == null || e.isReadOnly() || e.capacity() != 8192) {
|
||||
return false;
|
||||
}
|
||||
e.clear();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
public static ObjectPool<ByteBuffer> newBufferPool() {
|
||||
return ObjectPool.createSafePool(
|
||||
new LongAdder(),
|
||||
new LongAdder(),
|
||||
16,
|
||||
(Object... params) -> ByteBuffer.allocateDirect(8192),
|
||||
null,
|
||||
(e) -> {
|
||||
if (e == null || e.isReadOnly() || e.capacity() != 8192) {
|
||||
return false;
|
||||
}
|
||||
e.clear();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@RestMapping(name = "sab")
|
||||
public String abCurrentTime(@RestParam(name = "#") final String name) {
|
||||
System.out.println("准备执行ABMainService.sab方法");
|
||||
String rs = "同步abCurrentTime: " + bcService.bcCurrentTime1(name);
|
||||
System.out.println("执行了 ABMainService.abCurrentTime++++同步方法");
|
||||
return rs;
|
||||
}
|
||||
@RestMapping(name = "sab")
|
||||
public String abCurrentTime(@RestParam(name = "#") final String name) {
|
||||
System.out.println("准备执行ABMainService.sab方法");
|
||||
String rs = "同步abCurrentTime: " + bcService.bcCurrentTime1(name);
|
||||
System.out.println("执行了 ABMainService.abCurrentTime++++同步方法");
|
||||
return rs;
|
||||
}
|
||||
|
||||
@RestMapping(name = "abc")
|
||||
public void abCurrentTime(final CompletionHandler<String, Void> handler, @RestParam(name = "#") final String name) {
|
||||
bcService.bcCurrentTime2(
|
||||
Utility.createAsyncHandler(
|
||||
(v, a) -> {
|
||||
System.out.println("执行了 ABMainService.abCurrentTime----异步方法");
|
||||
String rs = "异步abCurrentTime: " + v;
|
||||
if (handler != null) {
|
||||
handler.completed(rs, a);
|
||||
}
|
||||
},
|
||||
(t, a) -> {
|
||||
if (handler != null) {
|
||||
handler.failed(t, a);
|
||||
}
|
||||
}),
|
||||
name);
|
||||
}
|
||||
@RestMapping(name = "abc")
|
||||
public void abCurrentTime(final CompletionHandler<String, Void> handler, @RestParam(name = "#") final String name) {
|
||||
bcService.bcCurrentTime2(
|
||||
Utility.createAsyncHandler(
|
||||
(v, a) -> {
|
||||
System.out.println("执行了 ABMainService.abCurrentTime----异步方法");
|
||||
String rs = "异步abCurrentTime: " + v;
|
||||
if (handler != null) {
|
||||
handler.completed(rs, a);
|
||||
}
|
||||
},
|
||||
(t, a) -> {
|
||||
if (handler != null) {
|
||||
handler.failed(t, a);
|
||||
}
|
||||
}),
|
||||
name);
|
||||
}
|
||||
|
||||
@RestMapping(name = "abc2")
|
||||
public void abCurrentTime(final MyAsyncHandler<String, Void> handler, @RestParam(name = "#") final String name) {
|
||||
bcService.bcCurrentTime3(
|
||||
new MyAsyncHandler<String, Void>() {
|
||||
@Override
|
||||
public int id() {
|
||||
return 1;
|
||||
}
|
||||
@RestMapping(name = "abc2")
|
||||
public void abCurrentTime(final MyAsyncHandler<String, Void> handler, @RestParam(name = "#") final String name) {
|
||||
bcService.bcCurrentTime3(
|
||||
new MyAsyncHandler<String, Void>() {
|
||||
@Override
|
||||
public int id() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void completed(String v, Void a) {
|
||||
System.out.println("执行了 ABMainService.abCurrentTime----异步方法2");
|
||||
String rs = "异步abCurrentTime: " + v;
|
||||
if (handler != null) {
|
||||
handler.completed(rs, a);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void completed(String v, Void a) {
|
||||
System.out.println("执行了 ABMainService.abCurrentTime----异步方法2");
|
||||
String rs = "异步abCurrentTime: " + v;
|
||||
if (handler != null) {
|
||||
handler.completed(rs, a);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Void attachment) {}
|
||||
@Override
|
||||
public void failed(Throwable exc, Void attachment) {}
|
||||
|
||||
@Override
|
||||
public int id2() {
|
||||
return 2;
|
||||
}
|
||||
},
|
||||
name);
|
||||
}
|
||||
@Override
|
||||
public int id2() {
|
||||
return 2;
|
||||
}
|
||||
},
|
||||
name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,73 +13,73 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class BCService implements Service {
|
||||
|
||||
@Resource
|
||||
private CService cService;
|
||||
@Resource
|
||||
private CService cService;
|
||||
|
||||
@Resource(name = "@name")
|
||||
private String serviceName;
|
||||
@Resource(name = "@name")
|
||||
private String serviceName;
|
||||
|
||||
@Resource(name = "@type")
|
||||
private Class serviceType;
|
||||
@Resource(name = "@type")
|
||||
private Class serviceType;
|
||||
|
||||
public String serviceName() {
|
||||
return serviceName;
|
||||
}
|
||||
public String serviceName() {
|
||||
return serviceName;
|
||||
}
|
||||
|
||||
public Class serviceType() {
|
||||
return serviceType;
|
||||
}
|
||||
public Class serviceType() {
|
||||
return serviceType;
|
||||
}
|
||||
|
||||
public String bcCurrentTime1(final String name) {
|
||||
System.out.println("准备执行BCService.bcCurrentTime1方法");
|
||||
String rs = "同步bcCurrentTime1: " + cService.ccCurrentTime1(name).getResult();
|
||||
System.out.println("执行了 BCService.bcCurrentTime1++++同步方法1");
|
||||
return rs;
|
||||
}
|
||||
public String bcCurrentTime1(final String name) {
|
||||
System.out.println("准备执行BCService.bcCurrentTime1方法");
|
||||
String rs = "同步bcCurrentTime1: " + cService.ccCurrentTime1(name).getResult();
|
||||
System.out.println("执行了 BCService.bcCurrentTime1++++同步方法1");
|
||||
return rs;
|
||||
}
|
||||
|
||||
public void bcCurrentTime2(final CompletionHandler<String, Void> handler, final String name) {
|
||||
cService.ccCurrentTime2(
|
||||
Utility.createAsyncHandler(
|
||||
(v, a) -> {
|
||||
System.out.println("执行了 BCService.bcCurrentTime2----异步方法2");
|
||||
String rs = "异步bcCurrentTime2: " + (v == null ? null : v.getResult());
|
||||
if (handler != null) {
|
||||
handler.completed(rs, null);
|
||||
}
|
||||
},
|
||||
(t, a) -> {
|
||||
if (handler != null) {
|
||||
handler.failed(t, a);
|
||||
}
|
||||
}),
|
||||
name);
|
||||
}
|
||||
public void bcCurrentTime2(final CompletionHandler<String, Void> handler, final String name) {
|
||||
cService.ccCurrentTime2(
|
||||
Utility.createAsyncHandler(
|
||||
(v, a) -> {
|
||||
System.out.println("执行了 BCService.bcCurrentTime2----异步方法2");
|
||||
String rs = "异步bcCurrentTime2: " + (v == null ? null : v.getResult());
|
||||
if (handler != null) {
|
||||
handler.completed(rs, null);
|
||||
}
|
||||
},
|
||||
(t, a) -> {
|
||||
if (handler != null) {
|
||||
handler.failed(t, a);
|
||||
}
|
||||
}),
|
||||
name);
|
||||
}
|
||||
|
||||
public void bcCurrentTime3(final MyAsyncHandler<String, Void> handler, final String name) {
|
||||
cService.mcCurrentTime3(
|
||||
new MyAsyncHandler<RetResult<String>, Void>() {
|
||||
@Override
|
||||
public int id() {
|
||||
return 1;
|
||||
}
|
||||
public void bcCurrentTime3(final MyAsyncHandler<String, Void> handler, final String name) {
|
||||
cService.mcCurrentTime3(
|
||||
new MyAsyncHandler<RetResult<String>, Void>() {
|
||||
@Override
|
||||
public int id() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void completed(RetResult<String> v, Void a) {
|
||||
System.out.println("执行了 BCService.bcCurrentTime3----异步方法3");
|
||||
String rs = "异步bcCurrentTime3: " + (v == null ? null : v.getResult());
|
||||
if (handler != null) {
|
||||
handler.completed(rs, null);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public void completed(RetResult<String> v, Void a) {
|
||||
System.out.println("执行了 BCService.bcCurrentTime3----异步方法3");
|
||||
String rs = "异步bcCurrentTime3: " + (v == null ? null : v.getResult());
|
||||
if (handler != null) {
|
||||
handler.completed(rs, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Void attachment) {}
|
||||
@Override
|
||||
public void failed(Throwable exc, Void attachment) {}
|
||||
|
||||
@Override
|
||||
public int id2() {
|
||||
return 2;
|
||||
}
|
||||
},
|
||||
name);
|
||||
}
|
||||
@Override
|
||||
public int id2() {
|
||||
return 2;
|
||||
}
|
||||
},
|
||||
name);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,35 +13,35 @@ import org.redkale.util.Times;
|
||||
/** @author zhangjx */
|
||||
public class CService implements Service {
|
||||
|
||||
@Resource(name = "@name")
|
||||
private String serviceName;
|
||||
@Resource(name = "@name")
|
||||
private String serviceName;
|
||||
|
||||
@Resource(name = "@type")
|
||||
private Class serviceType;
|
||||
@Resource(name = "@type")
|
||||
private Class serviceType;
|
||||
|
||||
public String serviceName() {
|
||||
return serviceName;
|
||||
}
|
||||
public String serviceName() {
|
||||
return serviceName;
|
||||
}
|
||||
|
||||
public Class serviceType() {
|
||||
return serviceType;
|
||||
}
|
||||
public Class serviceType() {
|
||||
return serviceType;
|
||||
}
|
||||
|
||||
public RetResult<String> ccCurrentTime1(final String name) {
|
||||
String rs = "同步ccCurrentTime1: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.ccCurrentTime1++++同步方法1");
|
||||
return new RetResult(rs);
|
||||
}
|
||||
public RetResult<String> ccCurrentTime1(final String name) {
|
||||
String rs = "同步ccCurrentTime1: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.ccCurrentTime1++++同步方法1");
|
||||
return new RetResult(rs);
|
||||
}
|
||||
|
||||
public void ccCurrentTime2(final CompletionHandler<RetResult<String>, Void> handler, final String name) {
|
||||
String rs = "异步ccCurrentTime2: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.ccCurrentTime2----异步方法2");
|
||||
if (handler != null) handler.completed(new RetResult(rs), null);
|
||||
}
|
||||
public void ccCurrentTime2(final CompletionHandler<RetResult<String>, Void> handler, final String name) {
|
||||
String rs = "异步ccCurrentTime2: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.ccCurrentTime2----异步方法2");
|
||||
if (handler != null) handler.completed(new RetResult(rs), null);
|
||||
}
|
||||
|
||||
public void mcCurrentTime3(final MyAsyncHandler<RetResult<String>, Void> handler, final String name) {
|
||||
String rs = "异步mcCurrentTime3: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.mcCurrentTime3----异步方法3");
|
||||
if (handler != null) handler.completed(new RetResult(rs), null);
|
||||
}
|
||||
public void mcCurrentTime3(final MyAsyncHandler<RetResult<String>, Void> handler, final String name) {
|
||||
String rs = "异步mcCurrentTime3: " + name + ": " + Times.formatTime(System.currentTimeMillis());
|
||||
System.out.println("执行了 CService.mcCurrentTime3----异步方法3");
|
||||
if (handler != null) handler.completed(new RetResult(rs), null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,5 +12,5 @@ package org.redkale.test.service;
|
||||
*/
|
||||
public abstract class MyAsyncHandler<V, A> extends MyAsyncInnerHandler<V, A> {
|
||||
|
||||
public abstract int id();
|
||||
public abstract int id();
|
||||
}
|
||||
|
||||
@@ -10,5 +10,5 @@ import java.nio.channels.CompletionHandler;
|
||||
/** @author zhangjx */
|
||||
public abstract class MyAsyncInnerHandler<V, A> implements CompletionHandler<V, A> {
|
||||
|
||||
protected abstract int id2();
|
||||
protected abstract int id2();
|
||||
}
|
||||
|
||||
@@ -4,28 +4,28 @@ import java.io.Serializable;
|
||||
|
||||
public class Person implements Serializable {
|
||||
|
||||
private byte[] b = new byte[1024 * 2];
|
||||
private byte[] b = new byte[1024 * 2];
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{name=" + name + ", b =" + (b == null ? "null" : "[length=" + b.length + "]") + "}";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{name=" + name + ", b =" + (b == null ? "null" : "[length=" + b.length + "]") + "}";
|
||||
}
|
||||
|
||||
public byte[] getB() {
|
||||
return b;
|
||||
}
|
||||
public byte[] getB() {
|
||||
return b;
|
||||
}
|
||||
|
||||
public void setB(byte[] b) {
|
||||
this.b = b;
|
||||
}
|
||||
public void setB(byte[] b) {
|
||||
this.b = b;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,16 +14,16 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class TestService implements Service {
|
||||
|
||||
// public boolean change(TestBean bean, String name, int id) {
|
||||
// return false;
|
||||
// }
|
||||
public void change(CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id) {}
|
||||
// public boolean change(TestBean bean, String name, int id) {
|
||||
// return false;
|
||||
// }
|
||||
public void change(CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id) {}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
final Application application = Application.create(true);
|
||||
SncpServer cserver = new SncpServer();
|
||||
cserver.getResourceFactory().register(application);
|
||||
cserver.addSncpServlet(new TestService());
|
||||
cserver.init(AnyValueWriter.create("port", 5577));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
final Application application = Application.create(true);
|
||||
SncpServer cserver = new SncpServer();
|
||||
cserver.getResourceFactory().register(application);
|
||||
cserver.addSncpServlet(new TestService());
|
||||
cserver.init(AnyValueWriter.create("port", 5577));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,79 +16,79 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class SncpClientCodecTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpClientCodecTest test = new SncpClientCodecTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpClientCodecTest test = new SncpClientCodecTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 3389);
|
||||
InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 3344);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
SncpClient client = new SncpClient(
|
||||
"test", asyncGroup, "0", sncpAddress, new ClientAddress(remoteAddress), "TCP", Utility.cpus(), 16);
|
||||
SncpClientConnection conn = client.createClientConnection(asyncGroup.newTCPClientConnection());
|
||||
SncpClientCodec codec = new SncpClientCodec(conn);
|
||||
List respResults = new ArrayList();
|
||||
try {
|
||||
Field respResultsField = ClientCodec.class.getDeclaredField("respResults");
|
||||
respResultsField.setAccessible(true);
|
||||
respResults = (List) respResultsField.get(codec);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ByteBuffer realBuf;
|
||||
// ----------------------------------------------
|
||||
respResults.clear();
|
||||
{
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest request = new SncpClientRequest();
|
||||
ByteArray writeArray1 = new ByteArray();
|
||||
request.prepare(header, 1, "aa", new byte[20]);
|
||||
request.writeTo(conn, writeArray1);
|
||||
System.out.println("request.1 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray1.getBytes().length);
|
||||
ByteArray writeArray2 = new ByteArray();
|
||||
request.prepare(header, 2, "bb", new byte[25]);
|
||||
request.writeTo(conn, writeArray2);
|
||||
System.out.println("request.2 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray2.getBytes().length);
|
||||
writeArray1.put(writeArray2);
|
||||
realBuf = ByteBuffer.wrap(writeArray1.getBytes());
|
||||
}
|
||||
System.out.println("sncp.realBuf = " + realBuf.remaining());
|
||||
codec.decodeMessages(realBuf, new ByteArray());
|
||||
System.out.println("respResults.size = " + respResults.size());
|
||||
Assertions.assertEquals(2, respResults.size());
|
||||
// ----------------------------------------------
|
||||
respResults.clear();
|
||||
{
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest request = new SncpClientRequest();
|
||||
ByteArray writeArray1 = new ByteArray();
|
||||
request.prepare(header, 1, "", new byte[20]);
|
||||
request.writeTo(conn, writeArray1);
|
||||
System.out.println("request.1 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray1.getBytes().length);
|
||||
ByteArray writeArray2 = new ByteArray();
|
||||
request.prepare(header, 2, "", new byte[25]);
|
||||
request.writeTo(conn, writeArray2);
|
||||
System.out.println("request.2 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray2.getBytes().length);
|
||||
writeArray1.put(writeArray2);
|
||||
realBuf = ByteBuffer.wrap(writeArray1.getBytes());
|
||||
}
|
||||
System.out.println("sncp.realBuf = " + realBuf.remaining());
|
||||
codec.decodeMessages(realBuf, new ByteArray());
|
||||
System.out.println("respResults.size = " + respResults.size());
|
||||
Assertions.assertEquals(2, respResults.size());
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 3389);
|
||||
InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 3344);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
SncpClient client = new SncpClient(
|
||||
"test", asyncGroup, "0", sncpAddress, new ClientAddress(remoteAddress), "TCP", Utility.cpus(), 16);
|
||||
SncpClientConnection conn = client.createClientConnection(asyncGroup.newTCPClientConnection());
|
||||
SncpClientCodec codec = new SncpClientCodec(conn);
|
||||
List respResults = new ArrayList();
|
||||
try {
|
||||
Field respResultsField = ClientCodec.class.getDeclaredField("respResults");
|
||||
respResultsField.setAccessible(true);
|
||||
respResults = (List) respResultsField.get(codec);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
ByteBuffer realBuf;
|
||||
// ----------------------------------------------
|
||||
respResults.clear();
|
||||
{
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest request = new SncpClientRequest();
|
||||
ByteArray writeArray1 = new ByteArray();
|
||||
request.prepare(header, 1, "aa", new byte[20]);
|
||||
request.writeTo(conn, writeArray1);
|
||||
System.out.println("request.1 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray1.getBytes().length);
|
||||
ByteArray writeArray2 = new ByteArray();
|
||||
request.prepare(header, 2, "bb", new byte[25]);
|
||||
request.writeTo(conn, writeArray2);
|
||||
System.out.println("request.2 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray2.getBytes().length);
|
||||
writeArray1.put(writeArray2);
|
||||
realBuf = ByteBuffer.wrap(writeArray1.getBytes());
|
||||
}
|
||||
System.out.println("sncp.realBuf = " + realBuf.remaining());
|
||||
codec.decodeMessages(realBuf, new ByteArray());
|
||||
System.out.println("respResults.size = " + respResults.size());
|
||||
Assertions.assertEquals(2, respResults.size());
|
||||
// ----------------------------------------------
|
||||
respResults.clear();
|
||||
{
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest request = new SncpClientRequest();
|
||||
ByteArray writeArray1 = new ByteArray();
|
||||
request.prepare(header, 1, "", new byte[20]);
|
||||
request.writeTo(conn, writeArray1);
|
||||
System.out.println("request.1 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray1.getBytes().length);
|
||||
ByteArray writeArray2 = new ByteArray();
|
||||
request.prepare(header, 2, "", new byte[25]);
|
||||
request.writeTo(conn, writeArray2);
|
||||
System.out.println("request.2 = " + request);
|
||||
System.out.println("headerSize = " + SncpHeader.calcHeaderSize(request) + ", arraySzie = "
|
||||
+ writeArray2.getBytes().length);
|
||||
writeArray1.put(writeArray2);
|
||||
realBuf = ByteBuffer.wrap(writeArray1.getBytes());
|
||||
}
|
||||
System.out.println("sncp.realBuf = " + realBuf.remaining());
|
||||
codec.decodeMessages(realBuf, new ByteArray());
|
||||
System.out.println("respResults.size = " + respResults.size());
|
||||
Assertions.assertEquals(2, respResults.size());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,75 +12,75 @@ import org.redkale.net.sncp.SncpAsyncHandler;
|
||||
/** @author zhangjx */
|
||||
public class SncpHandlerTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpHandlerTest test = new SncpHandlerTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpHandlerTest test = new SncpHandlerTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
SncpAsyncHandler.createHandler(CompletionHandler.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
if (main) {
|
||||
System.out.println("handler result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
}
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
SncpAsyncHandler.createHandler(CompletionHandler.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
if (main) {
|
||||
System.out.println("handler result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed(1, 2);
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed(1, 2);
|
||||
|
||||
SncpAsyncHandler.createHandler(ITestHandler1.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler1 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
SncpAsyncHandler.createHandler(ITestHandler1.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler1 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("name", "/user/");
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("name", "/user/");
|
||||
|
||||
SncpAsyncHandler.createHandler(ITestHandler2.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler2 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
SncpAsyncHandler.createHandler(ITestHandler2.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler2 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("aaa", "bbb");
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("aaa", "bbb");
|
||||
|
||||
SncpAsyncHandler.createHandler(ITestHandler3.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler3 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
SncpAsyncHandler.createHandler(ITestHandler3.class, new CompletionHandler() {
|
||||
@Override
|
||||
public void completed(Object result, Object attachment) {
|
||||
System.out.println("handler3 result: " + result + ", attachment: " + attachment);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("key1", "val1");
|
||||
}
|
||||
@Override
|
||||
public void failed(Throwable exc, Object attachment) {}
|
||||
})
|
||||
.completed("key1", "val1");
|
||||
}
|
||||
|
||||
public abstract static class ITestHandler1 implements CompletionHandler<String, File> {
|
||||
public abstract static class ITestHandler1 implements CompletionHandler<String, File> {
|
||||
|
||||
@Override
|
||||
public abstract void completed(String result, File attachment);
|
||||
}
|
||||
@Override
|
||||
public abstract void completed(String result, File attachment);
|
||||
}
|
||||
|
||||
public static interface IClose<T> {
|
||||
public static interface IClose<T> {
|
||||
|
||||
public void close(T val);
|
||||
}
|
||||
public void close(T val);
|
||||
}
|
||||
|
||||
public static interface ITestHandler2 extends CompletionHandler<String, String>, IClose<File> {}
|
||||
public static interface ITestHandler2 extends CompletionHandler<String, String>, IClose<File> {}
|
||||
|
||||
public static interface ITestHandler3 extends CompletionHandler<String, String>, Map<String, String> {}
|
||||
public static interface ITestHandler3 extends CompletionHandler<String, String>, Map<String, String> {}
|
||||
}
|
||||
|
||||
@@ -16,68 +16,68 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class SncpRequestParseTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpRequestParseTest test = new SncpRequestParseTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpRequestParseTest test = new SncpRequestParseTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 3389);
|
||||
InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 3344);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
SncpClient client = new SncpClient(
|
||||
"test", asyncGroup, "0", sncpAddress, new ClientAddress(remoteAddress), "TCP", Utility.cpus(), 16);
|
||||
SncpClientConnection conn = client.createClientConnection(asyncGroup.newTCPClientConnection());
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 3389);
|
||||
InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 3344);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
SncpClient client = new SncpClient(
|
||||
"test", asyncGroup, "0", sncpAddress, new ClientAddress(remoteAddress), "TCP", Utility.cpus(), 16);
|
||||
SncpClientConnection conn = client.createClientConnection(asyncGroup.newTCPClientConnection());
|
||||
|
||||
SncpContext.SncpContextConfig config = new SncpContext.SncpContextConfig();
|
||||
config.logger = Logger.getLogger(SncpRequestParseTest.class.getSimpleName());
|
||||
config.serverAddress = sncpAddress;
|
||||
config.maxBody = 1024 * 1024 * 1024;
|
||||
SncpContext context = new SncpContext(config);
|
||||
SncpContext.SncpContextConfig config = new SncpContext.SncpContextConfig();
|
||||
config.logger = Logger.getLogger(SncpRequestParseTest.class.getSimpleName());
|
||||
config.serverAddress = sncpAddress;
|
||||
config.maxBody = 1024 * 1024 * 1024;
|
||||
SncpContext context = new SncpContext(config);
|
||||
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest clientRequest = new SncpClientRequest();
|
||||
ByteArray writeArray = new ByteArray();
|
||||
clientRequest.prepare(header, 1, "aa", new byte[20]);
|
||||
clientRequest.writeTo(conn, writeArray);
|
||||
byte[] bs = writeArray.getBytes();
|
||||
int headerSize = SncpHeader.calcHeaderSize(clientRequest);
|
||||
System.out.println("整个sncp请求长度: " + bs.length + "." + Arrays.toString(bs));
|
||||
System.out.println(" " + Arrays.toString(Arrays.copyOfRange(bs, 2, bs.length)));
|
||||
SncpHeader header = SncpHeader.create(sncpAddress, Uint128.ZERO, "", Uint128.ZERO, "");
|
||||
SncpClientRequest clientRequest = new SncpClientRequest();
|
||||
ByteArray writeArray = new ByteArray();
|
||||
clientRequest.prepare(header, 1, "aa", new byte[20]);
|
||||
clientRequest.writeTo(conn, writeArray);
|
||||
byte[] bs = writeArray.getBytes();
|
||||
int headerSize = SncpHeader.calcHeaderSize(clientRequest);
|
||||
System.out.println("整个sncp请求长度: " + bs.length + "." + Arrays.toString(bs));
|
||||
System.out.println(" " + Arrays.toString(Arrays.copyOfRange(bs, 2, bs.length)));
|
||||
|
||||
SncpRequestTest request = new SncpRequestTest(context);
|
||||
Assertions.assertEquals(1, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 0, 1)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - 2, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 1, 2)), null));
|
||||
Assertions.assertEquals(0, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 2, bs.length)), null));
|
||||
Assertions.assertEquals("aa", request.getHeader().getTraceid());
|
||||
SncpRequestTest request = new SncpRequestTest(context);
|
||||
Assertions.assertEquals(1, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 0, 1)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - 2, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 1, 2)), null));
|
||||
Assertions.assertEquals(0, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 2, bs.length)), null));
|
||||
Assertions.assertEquals("aa", request.getHeader().getTraceid());
|
||||
|
||||
System.out.println("测试第二段");
|
||||
request = new SncpRequestTest(context);
|
||||
Assertions.assertEquals(1, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 0, 1)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - 2, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 1, 2)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - headerSize / 2,
|
||||
request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 2, headerSize / 2)), null));
|
||||
Assertions.assertEquals(
|
||||
0, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, headerSize / 2, bs.length)), null));
|
||||
Assertions.assertEquals("aa", request.getHeader().getTraceid());
|
||||
}
|
||||
System.out.println("测试第二段");
|
||||
request = new SncpRequestTest(context);
|
||||
Assertions.assertEquals(1, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 0, 1)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - 2, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 1, 2)), null));
|
||||
Assertions.assertEquals(
|
||||
headerSize - headerSize / 2,
|
||||
request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, 2, headerSize / 2)), null));
|
||||
Assertions.assertEquals(
|
||||
0, request.readHeader(ByteBuffer.wrap(Arrays.copyOfRange(bs, headerSize / 2, bs.length)), null));
|
||||
Assertions.assertEquals("aa", request.getHeader().getTraceid());
|
||||
}
|
||||
|
||||
public static class SncpRequestTest extends SncpRequest {
|
||||
public static class SncpRequestTest extends SncpRequest {
|
||||
|
||||
protected SncpRequestTest(SncpContext context) {
|
||||
super(context);
|
||||
}
|
||||
protected SncpRequestTest(SncpContext context) {
|
||||
super(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int readHeader(ByteBuffer buffer, Request last) {
|
||||
return super.readHeader(buffer, last);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
protected int readHeader(ByteBuffer buffer, Request last) {
|
||||
return super.readHeader(buffer, last);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,39 +11,39 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class SncpSleepService extends AbstractService {
|
||||
|
||||
public CompletableFuture<String> sleep200() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep200");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(200);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep200");
|
||||
return "ok200";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
public CompletableFuture<String> sleep200() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep200");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(200);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep200");
|
||||
return "ok200";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
|
||||
public CompletableFuture<String> sleep300() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep300");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(300);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep300");
|
||||
return "ok300";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
public CompletableFuture<String> sleep300() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep300");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(300);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep300");
|
||||
return "ok300";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
|
||||
public CompletableFuture<String> sleep500() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep500");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(500);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep500");
|
||||
return "ok500";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
public CompletableFuture<String> sleep500() {
|
||||
System.out.println(Times.nowMillis() + " " + Thread.currentThread().getName() + " 接收sleep500");
|
||||
return CompletableFuture.supplyAsync(
|
||||
() -> {
|
||||
Utility.sleep(500);
|
||||
System.out.println(
|
||||
Times.nowMillis() + " " + Thread.currentThread().getName() + " 执行完sleep500");
|
||||
return "ok500";
|
||||
},
|
||||
getExecutor());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,53 +17,53 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class SncpSleepTest {
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpSleepTest test = new SncpSleepTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpSleepTest test = new SncpSleepTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
System.out.println("------------------- 并发调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final ExecutorService workExecutor = WorkThread.createWorkExecutor(10, "Thread-Work-%s");
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup("Redkale-TestClient-IOThread-%s", workExecutor, 8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(Application.RESNAME_APP_EXECUTOR, ExecutorService.class, workExecutor);
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
System.out.println("------------------- 并发调用 -----------------------------------");
|
||||
final Application application = Application.create(true);
|
||||
final ExecutorService workExecutor = WorkThread.createWorkExecutor(10, "Thread-Work-%s");
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup("Redkale-TestClient-IOThread-%s", workExecutor, 8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory resFactory = ResourceFactory.create();
|
||||
resFactory.register(Application.RESNAME_APP_EXECUTOR, ExecutorService.class, workExecutor);
|
||||
resFactory.register(JsonConvert.root());
|
||||
resFactory.register(BsonConvert.root());
|
||||
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
SncpSleepService service = Sncp.createSimpleLocalService(SncpSleepService.class, resFactory);
|
||||
resFactory.inject(service);
|
||||
SncpServer server = new SncpServer(application, System.currentTimeMillis(), null, resFactory);
|
||||
server.getResourceFactory().register(application);
|
||||
server.addSncpServlet(service);
|
||||
server.init(AnyValueWriter.create("port", 0));
|
||||
server.start();
|
||||
// ------------------------ 初始化 CService ------------------------------------
|
||||
SncpSleepService service = Sncp.createSimpleLocalService(SncpSleepService.class, resFactory);
|
||||
resFactory.inject(service);
|
||||
SncpServer server = new SncpServer(application, System.currentTimeMillis(), null, resFactory);
|
||||
server.getResourceFactory().register(application);
|
||||
server.addSncpServlet(service);
|
||||
server.init(AnyValueWriter.create("port", 0));
|
||||
server.start();
|
||||
|
||||
int port = server.getSocketAddress().getPort();
|
||||
System.out.println("SNCP服务器启动端口: " + port);
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", port);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
rpcGroups.computeIfAbsent("cs", "TCP").putAddress(sncpAddress);
|
||||
SncpSleepService remoteCService =
|
||||
Sncp.createSimpleRemoteService(SncpSleepService.class, resFactory, rpcGroups, client, "cs");
|
||||
long s = System.currentTimeMillis();
|
||||
CompletableFuture[] futures =
|
||||
new CompletableFuture[] {remoteCService.sleep200(), remoteCService.sleep300(), remoteCService.sleep500()
|
||||
};
|
||||
CompletableFuture.allOf(futures).join();
|
||||
long e = System.currentTimeMillis() - s;
|
||||
System.out.println("耗时: " + e + " ms");
|
||||
server.shutdown();
|
||||
workExecutor.shutdown();
|
||||
Assertions.assertTrue(e < 600);
|
||||
}
|
||||
int port = server.getSocketAddress().getPort();
|
||||
System.out.println("SNCP服务器启动端口: " + port);
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", port);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
rpcGroups.computeIfAbsent("cs", "TCP").putAddress(sncpAddress);
|
||||
SncpSleepService remoteCService =
|
||||
Sncp.createSimpleRemoteService(SncpSleepService.class, resFactory, rpcGroups, client, "cs");
|
||||
long s = System.currentTimeMillis();
|
||||
CompletableFuture[] futures =
|
||||
new CompletableFuture[] {remoteCService.sleep200(), remoteCService.sleep300(), remoteCService.sleep500()
|
||||
};
|
||||
CompletableFuture.allOf(futures).join();
|
||||
long e = System.currentTimeMillis() - s;
|
||||
System.out.println("耗时: " + e + " ms");
|
||||
server.shutdown();
|
||||
workExecutor.shutdown();
|
||||
Assertions.assertTrue(e < 600);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,238 +21,238 @@ import org.redkale.util.*;
|
||||
/** @author zhangjx */
|
||||
public class SncpTest {
|
||||
|
||||
private static final String myhost = "127.0.0.1";
|
||||
private static final String myhost = "127.0.0.1";
|
||||
|
||||
private static int port = 0;
|
||||
private static int port = 0;
|
||||
|
||||
private static int port2 = 1;
|
||||
private static int port2 = 1;
|
||||
|
||||
private static final String protocol = "SNCP.TCP"; // TCP UDP
|
||||
private static final String protocol = "SNCP.TCP"; // TCP UDP
|
||||
|
||||
private static final int clientCapacity = protocol.endsWith(".UDP") ? AsyncGroup.UDP_BUFFER_CAPACITY : 8192;
|
||||
private static final int clientCapacity = protocol.endsWith(".UDP") ? AsyncGroup.UDP_BUFFER_CAPACITY : 8192;
|
||||
|
||||
private static ResourceFactory factory;
|
||||
private static ResourceFactory factory;
|
||||
|
||||
private static Application application;
|
||||
private static Application application;
|
||||
|
||||
private static SncpRpcGroups rpcGroups;
|
||||
private static SncpRpcGroups rpcGroups;
|
||||
|
||||
private boolean main;
|
||||
private boolean main;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpTest test = new SncpTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
SncpTest test = new SncpTest();
|
||||
test.main = true;
|
||||
test.run();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
LoggingBaseHandler.initDebugLogConfig();
|
||||
application = Application.create(true);
|
||||
rpcGroups = application.getSncpRpcGroups();
|
||||
factory = application.getResourceFactory();
|
||||
factory.register("", BsonConvert.class, BsonFactory.root().getConvert());
|
||||
factory.register("", Application.class, application);
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
LoggingBaseHandler.initDebugLogConfig();
|
||||
application = Application.create(true);
|
||||
rpcGroups = application.getSncpRpcGroups();
|
||||
factory = application.getResourceFactory();
|
||||
factory.register("", BsonConvert.class, BsonFactory.root().getConvert());
|
||||
factory.register("", Application.class, application);
|
||||
|
||||
if (System.getProperty("client") == null) {
|
||||
runServer();
|
||||
if (port2 > 0) {
|
||||
runServer2();
|
||||
}
|
||||
}
|
||||
if (System.getProperty("server") == null) {
|
||||
runClient();
|
||||
}
|
||||
if (System.getProperty("server") != null) {
|
||||
System.in.read();
|
||||
}
|
||||
}
|
||||
if (System.getProperty("client") == null) {
|
||||
runServer();
|
||||
if (port2 > 0) {
|
||||
runServer2();
|
||||
}
|
||||
}
|
||||
if (System.getProperty("server") == null) {
|
||||
runClient();
|
||||
}
|
||||
if (System.getProperty("server") != null) {
|
||||
System.in.read();
|
||||
}
|
||||
}
|
||||
|
||||
private void runClient() throws Exception {
|
||||
InetSocketAddress addr = new InetSocketAddress(myhost, port);
|
||||
rpcGroups
|
||||
.computeIfAbsent("client", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(addr);
|
||||
if (port2 > 0) {
|
||||
rpcGroups
|
||||
.computeIfAbsent("client", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port2));
|
||||
}
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(clientCapacity, 16);
|
||||
asyncGroup.start();
|
||||
private void runClient() throws Exception {
|
||||
InetSocketAddress addr = new InetSocketAddress(myhost, port);
|
||||
rpcGroups
|
||||
.computeIfAbsent("client", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(addr);
|
||||
if (port2 > 0) {
|
||||
rpcGroups
|
||||
.computeIfAbsent("client", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port2));
|
||||
}
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(clientCapacity, 16);
|
||||
asyncGroup.start();
|
||||
|
||||
InetSocketAddress sncpAddress = addr;
|
||||
final SncpClient client = new SncpClient(
|
||||
"",
|
||||
asyncGroup,
|
||||
"0",
|
||||
sncpAddress,
|
||||
new ClientAddress(sncpAddress),
|
||||
protocol.endsWith(".UDP") ? "UDP" : "TCP",
|
||||
16,
|
||||
100);
|
||||
InetSocketAddress sncpAddress = addr;
|
||||
final SncpClient client = new SncpClient(
|
||||
"",
|
||||
asyncGroup,
|
||||
"0",
|
||||
sncpAddress,
|
||||
new ClientAddress(sncpAddress),
|
||||
protocol.endsWith(".UDP") ? "UDP" : "TCP",
|
||||
16,
|
||||
100);
|
||||
|
||||
final SncpTestIService service = Sncp.createSimpleRemoteService(
|
||||
SncpTestIService.class,
|
||||
factory,
|
||||
rpcGroups,
|
||||
client,
|
||||
"client"); // Sncp.createSimpleRemoteService(SncpTestIService.class, null, transFactory, addr,
|
||||
// "client");
|
||||
factory.inject(service);
|
||||
final SncpTestIService service = Sncp.createSimpleRemoteService(
|
||||
SncpTestIService.class,
|
||||
factory,
|
||||
rpcGroups,
|
||||
client,
|
||||
"client"); // Sncp.createSimpleRemoteService(SncpTestIService.class, null, transFactory, addr,
|
||||
// "client");
|
||||
factory.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.queryLongResult("f", 3, 33L);
|
||||
// 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.queryLongResult("f", 3, 33L);
|
||||
|
||||
callbean = service.insert(callbean);
|
||||
System.out.println("bean: " + callbean);
|
||||
System.out.println("\r\n\r\n\r\n\r\n---------------------------------------------------");
|
||||
Utility.sleep(200);
|
||||
final int count = main ? 40 : 11;
|
||||
final CountDownLatch cld = new CountDownLatch(count);
|
||||
final AtomicInteger ai = new AtomicInteger();
|
||||
long s = System.currentTimeMillis();
|
||||
for (int i = 10; i < count + 10; 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);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(k).append("--------");
|
||||
for (int j = 0; j < 1000; j++) {
|
||||
sb.append("_").append(j % 10).append("_").append(k).append("7890_0123456789");
|
||||
}
|
||||
bean.setContent(sb.toString());
|
||||
callbean = service.insert(callbean);
|
||||
System.out.println("bean: " + callbean);
|
||||
System.out.println("\r\n\r\n\r\n\r\n---------------------------------------------------");
|
||||
Utility.sleep(200);
|
||||
final int count = main ? 40 : 11;
|
||||
final CountDownLatch cld = new CountDownLatch(count);
|
||||
final AtomicInteger ai = new AtomicInteger();
|
||||
long s = System.currentTimeMillis();
|
||||
for (int i = 10; i < count + 10; 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);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(k).append("--------");
|
||||
for (int j = 0; j < 1000; j++) {
|
||||
sb.append("_").append(j % 10).append("_").append(k).append("7890_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("---并发" + count + "次耗时: " + (System.currentTimeMillis() - s) / 1000.0 + "s");
|
||||
if (count == 1) {
|
||||
if (main) {
|
||||
System.exit(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Utility.sleep(200);
|
||||
final CountDownLatch cld2 = new CountDownLatch(1);
|
||||
long s2 = System.currentTimeMillis();
|
||||
final CompletableFuture<String> future = service.queryResultAsync(callbean);
|
||||
future.whenComplete((v, e) -> {
|
||||
System.out.println(
|
||||
"异步执行结果: " + v + ", 异常为: " + e + ", 耗时: " + (System.currentTimeMillis() - s2) / 1000.0 + "s");
|
||||
cld2.countDown();
|
||||
});
|
||||
cld2.await();
|
||||
System.out.println("---全部运行完毕---");
|
||||
}
|
||||
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("---并发" + count + "次耗时: " + (System.currentTimeMillis() - s) / 1000.0 + "s");
|
||||
if (count == 1) {
|
||||
if (main) {
|
||||
System.exit(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Utility.sleep(200);
|
||||
final CountDownLatch cld2 = new CountDownLatch(1);
|
||||
long s2 = System.currentTimeMillis();
|
||||
final CompletableFuture<String> future = service.queryResultAsync(callbean);
|
||||
future.whenComplete((v, e) -> {
|
||||
System.out.println(
|
||||
"异步执行结果: " + v + ", 异常为: " + e + ", 耗时: " + (System.currentTimeMillis() - s2) / 1000.0 + "s");
|
||||
cld2.countDown();
|
||||
});
|
||||
cld2.await();
|
||||
System.out.println("---全部运行完毕---");
|
||||
}
|
||||
|
||||
private static void runServer() throws Exception {
|
||||
InetSocketAddress addr = new InetSocketAddress(myhost, port);
|
||||
final CountDownLatch cdl = new CountDownLatch(1);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-01");
|
||||
}
|
||||
private static void runServer() throws Exception {
|
||||
InetSocketAddress addr = new InetSocketAddress(myhost, port);
|
||||
final CountDownLatch cdl = new CountDownLatch(1);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-01");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + port);
|
||||
conf.addValue("protocol", protocol);
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
SncpServer server = new SncpServer(null, System.currentTimeMillis(), conf, factory);
|
||||
if (port2 > 0) {
|
||||
rpcGroups
|
||||
.computeIfAbsent("server", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port2));
|
||||
}
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + port);
|
||||
conf.addValue("protocol", protocol);
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
SncpServer server = new SncpServer(null, System.currentTimeMillis(), conf, factory);
|
||||
if (port2 > 0) {
|
||||
rpcGroups
|
||||
.computeIfAbsent("server", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port2));
|
||||
}
|
||||
|
||||
SncpTestIService service = Sncp.createSimpleLocalService(
|
||||
SncpTestServiceImpl.class,
|
||||
factory); // Sncp.createSimpleLocalService(SncpTestServiceImpl.class, null, factory,
|
||||
// transFactory, addr, "server");
|
||||
factory.inject(service);
|
||||
server.addSncpServlet(service);
|
||||
System.out.println(service);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
port = server.getSocketAddress().getPort();
|
||||
cdl.countDown();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
cdl.await();
|
||||
}
|
||||
SncpTestIService service = Sncp.createSimpleLocalService(
|
||||
SncpTestServiceImpl.class,
|
||||
factory); // Sncp.createSimpleLocalService(SncpTestServiceImpl.class, null, factory,
|
||||
// transFactory, addr, "server");
|
||||
factory.inject(service);
|
||||
server.addSncpServlet(service);
|
||||
System.out.println(service);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
port = server.getSocketAddress().getPort();
|
||||
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);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8196, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-02");
|
||||
}
|
||||
private static void runServer2() throws Exception {
|
||||
InetSocketAddress addr = new InetSocketAddress(myhost, port2);
|
||||
final CountDownLatch cdl = new CountDownLatch(1);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8196, 16);
|
||||
asyncGroup.start();
|
||||
new Thread() {
|
||||
{
|
||||
setName("Thread-Server-02");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + (port2 < 10 ? 0 : port2));
|
||||
conf.addValue("protocol", protocol);
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
SncpServer server = new SncpServer(null, System.currentTimeMillis(), conf, factory);
|
||||
rpcGroups
|
||||
.computeIfAbsent("server", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port));
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
AnyValueWriter conf = new AnyValueWriter();
|
||||
conf.addValue("host", "0.0.0.0");
|
||||
conf.addValue("port", "" + (port2 < 10 ? 0 : port2));
|
||||
conf.addValue("protocol", protocol);
|
||||
conf.addValue("maxbody", "" + (100 * 1024 * 1024));
|
||||
SncpServer server = new SncpServer(null, System.currentTimeMillis(), conf, factory);
|
||||
rpcGroups
|
||||
.computeIfAbsent("server", protocol.endsWith(".UDP") ? "UDP" : "TCP")
|
||||
.putAddress(new InetSocketAddress(myhost, port));
|
||||
|
||||
Service service = Sncp.createSimpleLocalService(
|
||||
SncpTestServiceImpl.class,
|
||||
factory); // Sncp.createSimpleLocalService(SncpTestServiceImpl.class, null, factory,
|
||||
// transFactory, addr, "server");
|
||||
server.addSncpServlet(service);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
port2 = server.getSocketAddress().getPort();
|
||||
cdl.countDown();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
cdl.await();
|
||||
}
|
||||
Service service = Sncp.createSimpleLocalService(
|
||||
SncpTestServiceImpl.class,
|
||||
factory); // Sncp.createSimpleLocalService(SncpTestServiceImpl.class, null, factory,
|
||||
// transFactory, addr, "server");
|
||||
server.addSncpServlet(service);
|
||||
server.init(conf);
|
||||
server.start();
|
||||
port2 = server.getSocketAddress().getPort();
|
||||
cdl.countDown();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
cdl.await();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,41 +14,41 @@ import org.redkale.util.Utility;
|
||||
/** @author zhangjx */
|
||||
public class SncpTestBean implements FilterBean {
|
||||
|
||||
@Id
|
||||
private long id;
|
||||
@Id
|
||||
private long id;
|
||||
|
||||
private String content;
|
||||
private String content;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
String json = "{\"content\":\"数据: 01\",\"id\":1}";
|
||||
SncpTestBean bean = JsonConvert.root().convertFrom(SncpTestBean.class, json);
|
||||
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());
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
String json = "{\"content\":\"数据: 01\",\"id\":1}";
|
||||
SncpTestBean bean = JsonConvert.root().convertFrom(SncpTestBean.class, json);
|
||||
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);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
public void setId(long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,15 +11,15 @@ import org.redkale.service.Service;
|
||||
/** @author zhangjx */
|
||||
public interface SncpTestIService extends Service {
|
||||
|
||||
public String queryResult(SncpTestBean bean);
|
||||
public String queryResult(SncpTestBean bean);
|
||||
|
||||
public double queryDoubleResult(String a, int b, double value);
|
||||
public double queryDoubleResult(String a, int b, double value);
|
||||
|
||||
public long queryLongResult(String a, int b, long value);
|
||||
public long queryLongResult(String a, int b, long value);
|
||||
|
||||
public CompletableFuture<String> queryResultAsync(SncpTestBean bean);
|
||||
public CompletableFuture<String> queryResultAsync(SncpTestBean bean);
|
||||
|
||||
public SncpTestBean insert(SncpTestBean bean);
|
||||
public SncpTestBean insert(SncpTestBean bean);
|
||||
|
||||
public String updateBean(SncpTestBean bean);
|
||||
public String updateBean(SncpTestBean bean);
|
||||
}
|
||||
|
||||
@@ -22,105 +22,105 @@ import org.redkale.util.Utility;
|
||||
@ResourceType(SncpTestIService.class)
|
||||
public class SncpTestServiceImpl implements SncpTestIService {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> queryResultAsync(SncpTestBean bean) {
|
||||
final CompletableFuture<String> future = new CompletableFuture<>();
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Utility.sleep(200);
|
||||
System.out.println(
|
||||
Thread.currentThread().getName() + " sleep 200ms后运行了异步方法-----------queryResultAsync方法");
|
||||
future.complete("异步 result: " + bean);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
return future;
|
||||
}
|
||||
@Override
|
||||
public CompletableFuture<String> queryResultAsync(SncpTestBean bean) {
|
||||
final CompletableFuture<String> future = new CompletableFuture<>();
|
||||
new Thread() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Utility.sleep(200);
|
||||
System.out.println(
|
||||
Thread.currentThread().getName() + " sleep 200ms后运行了异步方法-----------queryResultAsync方法");
|
||||
future.complete("异步 result: " + bean);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}.start();
|
||||
return future;
|
||||
}
|
||||
|
||||
@Override
|
||||
public long queryLongResult(String a, int b, long value) {
|
||||
return value + 1;
|
||||
}
|
||||
@Override
|
||||
public long queryLongResult(String a, int b, long value) {
|
||||
return value + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double queryDoubleResult(String a, int b, double value) {
|
||||
return value + 1;
|
||||
}
|
||||
@Override
|
||||
public double queryDoubleResult(String a, int b, double value) {
|
||||
return value + 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SncpTestBean insert(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
return bean;
|
||||
}
|
||||
@Override
|
||||
public SncpTestBean insert(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
return bean;
|
||||
}
|
||||
|
||||
public SncpTestBean expand(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
return bean;
|
||||
}
|
||||
public SncpTestBean expand(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String queryResult(SncpTestBean bean) {
|
||||
System.out.println(Thread.currentThread().getName() + " 运行了queryResult方法 content-length: "
|
||||
+ bean.getContent().length());
|
||||
return "result-content: " + bean.getContent();
|
||||
}
|
||||
@Override
|
||||
public String queryResult(SncpTestBean bean) {
|
||||
System.out.println(Thread.currentThread().getName() + " 运行了queryResult方法 content-length: "
|
||||
+ bean.getContent().length());
|
||||
return "result-content: " + bean.getContent();
|
||||
}
|
||||
|
||||
public void queryResult(CompletionHandler<String, SncpTestBean> handler, @RpcAttachment SncpTestBean bean) {
|
||||
System.out.println(Thread.currentThread().getName() + " handler 运行了queryResult方法");
|
||||
if (handler != null) {
|
||||
handler.completed("result: " + bean.getId(), bean);
|
||||
}
|
||||
}
|
||||
public void queryResult(CompletionHandler<String, SncpTestBean> handler, @RpcAttachment SncpTestBean bean) {
|
||||
System.out.println(Thread.currentThread().getName() + " handler 运行了queryResult方法");
|
||||
if (handler != null) {
|
||||
handler.completed("result: " + bean.getId(), bean);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateBean(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
System.out.println(Thread.currentThread().getName() + " 运行了updateBean方法");
|
||||
return "result: " + bean;
|
||||
}
|
||||
@Override
|
||||
public String updateBean(SncpTestBean bean) {
|
||||
bean.setId(System.currentTimeMillis());
|
||||
System.out.println(Thread.currentThread().getName() + " 运行了updateBean方法");
|
||||
return "result: " + bean;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory factory = ResourceFactory.create();
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 7070);
|
||||
rpcGroups.computeIfAbsent("g70", "TCP").putAddress(sncpAddress);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
final Application application = Application.create(true);
|
||||
final AsyncIOGroup asyncGroup = new AsyncIOGroup(8192, 16);
|
||||
asyncGroup.start();
|
||||
final ResourceFactory factory = ResourceFactory.create();
|
||||
final SncpRpcGroups rpcGroups = application.getSncpRpcGroups();
|
||||
InetSocketAddress sncpAddress = new InetSocketAddress("127.0.0.1", 7070);
|
||||
rpcGroups.computeIfAbsent("g70", "TCP").putAddress(sncpAddress);
|
||||
final SncpClient client =
|
||||
new SncpClient("", asyncGroup, "0", sncpAddress, new ClientAddress(sncpAddress), "TCP", 16, 100);
|
||||
|
||||
Service service = Sncp.createSimpleLocalService(SncpTestServiceImpl.class, factory);
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
service = Sncp.createSimpleRemoteService(SncpTestServiceImpl.class, factory, rpcGroups, client, "g70");
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
service = Sncp.createSimpleRemoteService(SncpTestIService.class, factory, rpcGroups, client, "g70");
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
}
|
||||
Service service = Sncp.createSimpleLocalService(SncpTestServiceImpl.class, factory);
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
service = Sncp.createSimpleRemoteService(SncpTestServiceImpl.class, factory, rpcGroups, client, "g70");
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
service = Sncp.createSimpleRemoteService(SncpTestIService.class, factory, rpcGroups, client, "g70");
|
||||
for (Method method : service.getClass().getDeclaredMethods()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
for (Method method : Sncp.loadRemoteMethodActions(service.getClass()).values()) {
|
||||
System.out.println(method);
|
||||
}
|
||||
System.out.println("-----------------------------------");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,150 +17,150 @@ import org.redkale.util.Uint128;
|
||||
/** @author zhangjx */
|
||||
public interface TestService extends Service {
|
||||
|
||||
public boolean change(TestBean bean, String name, int id);
|
||||
public boolean change(TestBean bean, String name, int id);
|
||||
|
||||
public void insert(BooleanHandler handler, TestBean bean, String name, int id);
|
||||
public void insert(BooleanHandler handler, TestBean bean, String name, int id);
|
||||
|
||||
public void update(
|
||||
long show, short v2, CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id);
|
||||
public void update(
|
||||
long show, short v2, CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id);
|
||||
|
||||
public CompletableFuture<String> changeName(TestBean bean, String name, int id);
|
||||
public CompletableFuture<String> changeName(TestBean bean, String name, int id);
|
||||
}
|
||||
|
||||
@ResourceType(TestService.class)
|
||||
class TestServiceImpl implements TestService {
|
||||
|
||||
@Override
|
||||
public boolean change(TestBean bean, String name, int id) {
|
||||
return false;
|
||||
}
|
||||
@Override
|
||||
public boolean change(TestBean bean, String name, int id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
public void delete(TestBean bean) {}
|
||||
public void delete(TestBean bean) {}
|
||||
|
||||
@Override
|
||||
public void insert(BooleanHandler handler, TestBean bean, String name, int id) {}
|
||||
@Override
|
||||
public void insert(BooleanHandler handler, TestBean bean, String name, int id) {}
|
||||
|
||||
@Override
|
||||
public void update(
|
||||
long show, short v2, CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id) {}
|
||||
@Override
|
||||
public void update(
|
||||
long show, short v2, CompletionHandler<Boolean, TestBean> handler, TestBean bean, String name, int id) {}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<String> changeName(TestBean bean, String name, int id) {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
public CompletableFuture<String> changeName(TestBean bean, String name, int id) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class BooleanHandler implements CompletionHandler<Boolean, TestBean> {
|
||||
|
||||
@Override
|
||||
public void completed(Boolean result, TestBean attachment) {}
|
||||
@Override
|
||||
public void completed(Boolean result, TestBean attachment) {}
|
||||
|
||||
@Override
|
||||
public void failed(Throwable exc, TestBean attachment) {}
|
||||
@Override
|
||||
public void failed(Throwable exc, TestBean attachment) {}
|
||||
}
|
||||
|
||||
class DynActionTestService_change extends SncpActionServlet {
|
||||
|
||||
public DynActionTestService_change(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
public DynActionTestService_change(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[1], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[2], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[3], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
Object rs = serviceObj.change(arg1, arg2, arg3);
|
||||
response.finish(boolean.class, rs);
|
||||
}
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[1], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[2], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[3], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
Object rs = serviceObj.change(arg1, arg2, arg3);
|
||||
response.finish(boolean.class, rs);
|
||||
}
|
||||
}
|
||||
|
||||
class DynActionTestService_insert extends SncpActionServlet {
|
||||
|
||||
public DynActionTestService_insert(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
public DynActionTestService_insert(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
BooleanHandler arg0 = response.getParamAsyncHandler();
|
||||
convert.convertFrom(CompletionHandler.class, in);
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[2], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[3], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[4], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
serviceObj.insert(arg0, arg1, arg2, arg3);
|
||||
response.finishVoid();
|
||||
}
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
BooleanHandler arg0 = response.getParamAsyncHandler();
|
||||
convert.convertFrom(CompletionHandler.class, in);
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[2], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[3], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[4], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
serviceObj.insert(arg0, arg1, arg2, arg3);
|
||||
response.finishVoid();
|
||||
}
|
||||
}
|
||||
|
||||
class DynActionTestService_update extends SncpActionServlet {
|
||||
|
||||
public DynActionTestService_update(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
public DynActionTestService_update(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
long a1 = convert.convertFrom(paramTypes[1], in);
|
||||
short a2 = convert.convertFrom(paramTypes[2], in);
|
||||
CompletionHandler a3 = response.getParamAsyncHandler();
|
||||
convert.convertFrom(CompletionHandler.class, in);
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[4], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[5], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[6], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
serviceObj.update(a1, a2, a3, arg1, arg2, arg3);
|
||||
response.finishVoid();
|
||||
}
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
long a1 = convert.convertFrom(paramTypes[1], in);
|
||||
short a2 = convert.convertFrom(paramTypes[2], in);
|
||||
CompletionHandler a3 = response.getParamAsyncHandler();
|
||||
convert.convertFrom(CompletionHandler.class, in);
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[4], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[5], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[6], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
serviceObj.update(a1, a2, a3, arg1, arg2, arg3);
|
||||
response.finishVoid();
|
||||
}
|
||||
}
|
||||
|
||||
class DynActionTestService_changeName extends SncpActionServlet {
|
||||
|
||||
public DynActionTestService_changeName(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
public DynActionTestService_changeName(
|
||||
String resourceName,
|
||||
Class resourceType,
|
||||
Service service,
|
||||
Uint128 serviceid,
|
||||
Uint128 actionid,
|
||||
final Method method) {
|
||||
super(resourceName, resourceType, service, serviceid, actionid, method);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[1], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[2], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[3], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
CompletableFuture future = serviceObj.changeName(arg1, arg2, arg3);
|
||||
response.finishFuture(paramHandlerResultType, future);
|
||||
}
|
||||
@Override
|
||||
public void action(SncpRequest request, SncpResponse response) throws Throwable {
|
||||
Convert<Reader, Writer> convert = request.getConvert();
|
||||
Reader in = request.getReader();
|
||||
TestBean arg1 = convert.convertFrom(paramTypes[1], in);
|
||||
String arg2 = convert.convertFrom(paramTypes[2], in);
|
||||
int arg3 = convert.convertFrom(paramTypes[3], in);
|
||||
TestService serviceObj = (TestService) service();
|
||||
CompletableFuture future = serviceObj.changeName(arg1, arg2, arg3);
|
||||
response.finishFuture(paramHandlerResultType, future);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ import org.redkale.convert.json.*;
|
||||
/** @author zhangjx */
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,84 +18,84 @@ import org.redkale.source.*;
|
||||
@VirtualEntity(loader = CacheTestBean.DefaultBeanLoader.class)
|
||||
public class CacheTestBean {
|
||||
|
||||
@Id
|
||||
private long pkgid;
|
||||
@Id
|
||||
private long pkgid;
|
||||
|
||||
private String name;
|
||||
private String name;
|
||||
|
||||
private long price;
|
||||
private long price;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<CacheTestBean> info = (EntityInfo<CacheTestBean>) method.invoke(
|
||||
null, CacheTestBean.class, true, new Properties(), null, new CacheTestBean.DefaultBeanLoader());
|
||||
EntityCache<CacheTestBean> cache = new EntityCache(info, null);
|
||||
cache.fullLoadAsync();
|
||||
public static void main(String[] args) throws Exception {
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<CacheTestBean> info = (EntityInfo<CacheTestBean>) method.invoke(
|
||||
null, CacheTestBean.class, true, new Properties(), null, new CacheTestBean.DefaultBeanLoader());
|
||||
EntityCache<CacheTestBean> cache = new EntityCache(info, null);
|
||||
cache.fullLoadAsync();
|
||||
|
||||
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));
|
||||
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));
|
||||
|
||||
System.out.println(cache.find(null, FilterNodes.eq("name", "BB")));
|
||||
System.out.println(cache.find(null, FilterNodes.igEq("name", "BB")));
|
||||
System.out.println(cache.querySheet(null, null, FilterNodes.igNotLike("name", "B")));
|
||||
System.out.println(cache.find(null, FilterNodes.eq(CacheTestBean::getName, "BB")));
|
||||
System.out.println(cache.find(null, FilterNodes.igEq(CacheTestBean::getName, "BB")));
|
||||
System.out.println(cache.querySheet(null, null, FilterNodes.igNotLike(CacheTestBean::getName, "B")));
|
||||
}
|
||||
System.out.println(cache.find(null, FilterNodes.eq("name", "BB")));
|
||||
System.out.println(cache.find(null, FilterNodes.igEq("name", "BB")));
|
||||
System.out.println(cache.querySheet(null, null, FilterNodes.igNotLike("name", "B")));
|
||||
System.out.println(cache.find(null, FilterNodes.eq(CacheTestBean::getName, "BB")));
|
||||
System.out.println(cache.find(null, FilterNodes.igEq(CacheTestBean::getName, "BB")));
|
||||
System.out.println(cache.querySheet(null, null, FilterNodes.igNotLike(CacheTestBean::getName, "B")));
|
||||
}
|
||||
|
||||
public CacheTestBean() {}
|
||||
public CacheTestBean() {}
|
||||
|
||||
public CacheTestBean(long pkgid, String name, long price) {
|
||||
this.pkgid = pkgid;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
public CacheTestBean(long pkgid, String name, long price) {
|
||||
this.pkgid = pkgid;
|
||||
this.name = name;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public long getPkgid() {
|
||||
return pkgid;
|
||||
}
|
||||
public long getPkgid() {
|
||||
return pkgid;
|
||||
}
|
||||
|
||||
public void setPkgid(long pkgid) {
|
||||
this.pkgid = pkgid;
|
||||
}
|
||||
public void setPkgid(long pkgid) {
|
||||
this.pkgid = pkgid;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getPrice() {
|
||||
return price;
|
||||
}
|
||||
public long getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(long price) {
|
||||
this.price = price;
|
||||
}
|
||||
public void setPrice(long price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public static class DefaultBeanLoader implements BiFunction<DataSource, EntityInfo, CompletableFuture<List>> {
|
||||
public static class DefaultBeanLoader implements BiFunction<DataSource, EntityInfo, CompletableFuture<List>> {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<List> apply(DataSource t, EntityInfo u) {
|
||||
final List<CacheTestBean> 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));
|
||||
return CompletableFuture.completedFuture(list);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public CompletableFuture<List> apply(DataSource t, EntityInfo u) {
|
||||
final List<CacheTestBean> 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));
|
||||
return CompletableFuture.completedFuture(list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,419 +22,419 @@ import org.redkale.source.*;
|
||||
/** @author zhangjx */
|
||||
public class FilterNodeTest {
|
||||
|
||||
private static Function<Class, EntityInfo> func;
|
||||
|
||||
private static EntityInfo<CarTestTable> carEntity;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
FilterNodeTest test = new FilterNodeTest();
|
||||
test.init();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
final Properties props = new Properties();
|
||||
final BiFunction<DataSource, EntityInfo, CompletableFuture<List>> fullloader =
|
||||
(s, t) -> CompletableFuture.completedFuture(new ArrayList());
|
||||
func = (Class t) -> loadEntityInfo(t, false, props, null, fullloader);
|
||||
carEntity = loadEntityInfo(
|
||||
CarTestTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(CarTestTable.createList()));
|
||||
final EntityInfo<UserTestTable> userEntity = loadEntityInfo(
|
||||
UserTestTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(UserTestTable.createList()));
|
||||
final EntityInfo<CarTypeTable> typeEntity = loadEntityInfo(
|
||||
CarTypeTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(CarTypeTable.createList()));
|
||||
}
|
||||
|
||||
private static <T> EntityInfo<T> loadEntityInfo(
|
||||
Class<T> clazz,
|
||||
final boolean cacheForbidden,
|
||||
final Properties conf,
|
||||
DataSource source,
|
||||
BiFunction<DataSource, EntityInfo, CompletableFuture<List>> fullloader) {
|
||||
try {
|
||||
Method loadMethod = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
loadMethod.setAccessible(true);
|
||||
return (EntityInfo) loadMethod.invoke(null, clazz, cacheForbidden, conf, source, fullloader);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<Class, String> getJoinTabalis(FilterNode node) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("getJoinTabalis");
|
||||
method.setAccessible(true);
|
||||
return (Map) method.invoke(node);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> CharSequence createSQLJoin(
|
||||
FilterNode node,
|
||||
Function<Class, EntityInfo> func,
|
||||
final boolean update,
|
||||
final Map<Class, String> joinTabalis,
|
||||
final Set<String> haset,
|
||||
final EntityInfo<T> info) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod(
|
||||
"createSQLJoin", Function.class, boolean.class, Map.class, Set.class, EntityInfo.class);
|
||||
method.setAccessible(true);
|
||||
return (CharSequence) method.invoke(node, func, update, joinTabalis, haset, info);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> CharSequence createSQLExpress(
|
||||
FilterNode node,
|
||||
AbstractDataSqlSource source,
|
||||
final EntityInfo<T> info,
|
||||
final Map<Class, String> joinTabalis) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod(
|
||||
"createSQLExpress", AbstractDataSqlSource.class, EntityInfo.class, Map.class);
|
||||
method.setAccessible(true);
|
||||
return (CharSequence) method.invoke(node, source, info, joinTabalis);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> boolean isCacheUseable(FilterNode node, final Function<Class, EntityInfo> entityApplyer) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("isCacheUseable", Function.class);
|
||||
method.setAccessible(true);
|
||||
return (Boolean) method.invoke(node, entityApplyer);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Predicate<T> createPredicate(FilterNode node, final EntityCache<T> cache) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("createPredicate", EntityCache.class);
|
||||
method.setAccessible(true);
|
||||
return (Predicate) method.invoke(node, cache);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final CarTestBean bean = CarTestBean.create();
|
||||
FilterNode joinNode1 = FilterNodes.joinInner(
|
||||
UserTestTable.class, new String[] {"userid", "username"}, "username", LIKE, bean.username)
|
||||
.or(FilterNodes.joinInner(
|
||||
UserTestTable.class, new String[] {"userid", "username"}, "createtime", GT, bean.createtime));
|
||||
FilterNode joinNode2 = FilterNodes.joinInner(CarTypeTable.class, "cartype", "typename", LIKE, bean.typename);
|
||||
final FilterNode node = CarTestBean.caridTransient()
|
||||
? (joinNode2.or(joinNode1))
|
||||
: FilterNodes.gt("carid", bean.carid).and(joinNode1).or(joinNode2);
|
||||
final FilterNode beanNode = FilterNodeBean.createFilterNode(bean);
|
||||
System.out.println("node.string = " + node);
|
||||
System.out.println("bean.string = " + beanNode);
|
||||
Assertions.assertEquals(
|
||||
"(CarTypeTable.typename LIKE '%法拉利%' OR (UserTestTable.username LIKE '%用户1%' OR UserTestTable.createtime > 500))",
|
||||
node.toString());
|
||||
Assertions.assertEquals(node.toString(), beanNode.toString());
|
||||
Map<Class, String> nodeJoinTabalis = getJoinTabalis(node);
|
||||
Map<Class, String> beanJoinTabalis = getJoinTabalis(beanNode);
|
||||
System.out.println("nodeJoinTabalis: " + nodeJoinTabalis);
|
||||
System.out.println("beanJoinTabalis: " + beanJoinTabalis);
|
||||
CharSequence nodeJoinsql = createSQLJoin(node, func, false, nodeJoinTabalis, new HashSet<>(), carEntity);
|
||||
CharSequence beanJoinsql = createSQLJoin(beanNode, func, false, beanJoinTabalis, new HashSet<>(), carEntity);
|
||||
CharSequence nodeWhere = createSQLExpress(node, null, carEntity, nodeJoinTabalis);
|
||||
CharSequence beanWhere = createSQLExpress(beanNode, null, carEntity, beanJoinTabalis);
|
||||
String expect =
|
||||
"SELECT a.* FROM cartesttable a INNER JOIN cartypetable ctt ON a.cartype = ctt.cartype INNER JOIN usertesttable utt ON a.userid = utt.userid AND a.username = utt.username WHERE (ctt.typename LIKE '%法拉利%' OR (utt.username LIKE '%用户1%' OR utt.createtime > 500))";
|
||||
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);
|
||||
boolean r1 = isCacheUseable(node, func);
|
||||
Assertions.assertTrue(r1);
|
||||
if (!r1) {
|
||||
System.err.println("node.isCacheUseable 应该是true");
|
||||
}
|
||||
boolean r2 = isCacheUseable(beanNode, func);
|
||||
Assertions.assertTrue(r2);
|
||||
|
||||
System.out.println("node.Predicate = " + createPredicate(node, carEntity.getCache()));
|
||||
System.out.println("bean.Predicate = " + createPredicate(beanNode, 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 = GT)
|
||||
@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 = GT)
|
||||
@FilterJoinColumn(
|
||||
table = UserTestTable.class,
|
||||
columns = {"userid", "username"})
|
||||
public long createtime;
|
||||
|
||||
@FilterGroup("[OR]")
|
||||
@FilterColumn(express = LIKE)
|
||||
@FilterJoinColumn(
|
||||
table = CarTypeTable.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;
|
||||
}
|
||||
}
|
||||
|
||||
public static CarTestBean create() {
|
||||
final CarTestBean bean = new CarTestBean();
|
||||
bean.carid = 70002;
|
||||
bean.username = "用户1";
|
||||
bean.createtime = 500;
|
||||
bean.typename = "法拉利";
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
|
||||
@AutoLoad
|
||||
@Entity(cacheable = true)
|
||||
public static class CarTestTable {
|
||||
|
||||
public static List<CarTestTable> createList() {
|
||||
List<CarTestTable> 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
|
||||
@Entity(cacheable = true)
|
||||
public static class CarTypeTable {
|
||||
|
||||
public static List<CarTypeTable> createList() {
|
||||
List<CarTypeTable> list = new ArrayList<>();
|
||||
list.add(new CarTypeTable(101, "奥迪A1"));
|
||||
list.add(new CarTypeTable(102, "奥迪A2"));
|
||||
list.add(new CarTypeTable(103, "奥迪A3"));
|
||||
list.add(new CarTypeTable(104, "奥迪A4"));
|
||||
list.add(new CarTypeTable(105, "奥迪A5"));
|
||||
list.add(new CarTypeTable(201, "奔驰S1"));
|
||||
list.add(new CarTypeTable(202, "奔驰S2"));
|
||||
list.add(new CarTypeTable(203, "奔驰S3"));
|
||||
list.add(new CarTypeTable(204, "奔驰S4"));
|
||||
list.add(new CarTypeTable(205, "奔驰S5"));
|
||||
list.add(new CarTypeTable(301, "法拉利"));
|
||||
return list;
|
||||
}
|
||||
|
||||
@Id
|
||||
private int cartype;
|
||||
|
||||
private String typename;
|
||||
|
||||
public CarTypeTable() {}
|
||||
|
||||
public CarTypeTable(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
|
||||
@Entity(cacheable = true)
|
||||
public static class UserTestTable {
|
||||
|
||||
public static List<UserTestTable> createList() {
|
||||
List<UserTestTable> 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;
|
||||
}
|
||||
}
|
||||
private static Function<Class, EntityInfo> func;
|
||||
|
||||
private static EntityInfo<CarTestTable> carEntity;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
FilterNodeTest test = new FilterNodeTest();
|
||||
test.init();
|
||||
test.run();
|
||||
}
|
||||
|
||||
@BeforeAll
|
||||
public static void init() throws Exception {
|
||||
final Properties props = new Properties();
|
||||
final BiFunction<DataSource, EntityInfo, CompletableFuture<List>> fullloader =
|
||||
(s, t) -> CompletableFuture.completedFuture(new ArrayList());
|
||||
func = (Class t) -> loadEntityInfo(t, false, props, null, fullloader);
|
||||
carEntity = loadEntityInfo(
|
||||
CarTestTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(CarTestTable.createList()));
|
||||
final EntityInfo<UserTestTable> userEntity = loadEntityInfo(
|
||||
UserTestTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(UserTestTable.createList()));
|
||||
final EntityInfo<CarTypeTable> typeEntity = loadEntityInfo(
|
||||
CarTypeTable.class,
|
||||
false,
|
||||
props,
|
||||
null,
|
||||
(s, t) -> CompletableFuture.completedFuture(CarTypeTable.createList()));
|
||||
}
|
||||
|
||||
private static <T> EntityInfo<T> loadEntityInfo(
|
||||
Class<T> clazz,
|
||||
final boolean cacheForbidden,
|
||||
final Properties conf,
|
||||
DataSource source,
|
||||
BiFunction<DataSource, EntityInfo, CompletableFuture<List>> fullloader) {
|
||||
try {
|
||||
Method loadMethod = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
loadMethod.setAccessible(true);
|
||||
return (EntityInfo) loadMethod.invoke(null, clazz, cacheForbidden, conf, source, fullloader);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<Class, String> getJoinTabalis(FilterNode node) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("getJoinTabalis");
|
||||
method.setAccessible(true);
|
||||
return (Map) method.invoke(node);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> CharSequence createSQLJoin(
|
||||
FilterNode node,
|
||||
Function<Class, EntityInfo> func,
|
||||
final boolean update,
|
||||
final Map<Class, String> joinTabalis,
|
||||
final Set<String> haset,
|
||||
final EntityInfo<T> info) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod(
|
||||
"createSQLJoin", Function.class, boolean.class, Map.class, Set.class, EntityInfo.class);
|
||||
method.setAccessible(true);
|
||||
return (CharSequence) method.invoke(node, func, update, joinTabalis, haset, info);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> CharSequence createSQLExpress(
|
||||
FilterNode node,
|
||||
AbstractDataSqlSource source,
|
||||
final EntityInfo<T> info,
|
||||
final Map<Class, String> joinTabalis) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod(
|
||||
"createSQLExpress", AbstractDataSqlSource.class, EntityInfo.class, Map.class);
|
||||
method.setAccessible(true);
|
||||
return (CharSequence) method.invoke(node, source, info, joinTabalis);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> boolean isCacheUseable(FilterNode node, final Function<Class, EntityInfo> entityApplyer) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("isCacheUseable", Function.class);
|
||||
method.setAccessible(true);
|
||||
return (Boolean) method.invoke(node, entityApplyer);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Predicate<T> createPredicate(FilterNode node, final EntityCache<T> cache) {
|
||||
try {
|
||||
Method method = FilterNode.class.getDeclaredMethod("createPredicate", EntityCache.class);
|
||||
method.setAccessible(true);
|
||||
return (Predicate) method.invoke(node, cache);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void run() throws Exception {
|
||||
final CarTestBean bean = CarTestBean.create();
|
||||
FilterNode joinNode1 = FilterNodes.joinInner(
|
||||
UserTestTable.class, new String[] {"userid", "username"}, "username", LIKE, bean.username)
|
||||
.or(FilterNodes.joinInner(
|
||||
UserTestTable.class, new String[] {"userid", "username"}, "createtime", GT, bean.createtime));
|
||||
FilterNode joinNode2 = FilterNodes.joinInner(CarTypeTable.class, "cartype", "typename", LIKE, bean.typename);
|
||||
final FilterNode node = CarTestBean.caridTransient()
|
||||
? (joinNode2.or(joinNode1))
|
||||
: FilterNodes.gt("carid", bean.carid).and(joinNode1).or(joinNode2);
|
||||
final FilterNode beanNode = FilterNodeBean.createFilterNode(bean);
|
||||
System.out.println("node.string = " + node);
|
||||
System.out.println("bean.string = " + beanNode);
|
||||
Assertions.assertEquals(
|
||||
"(CarTypeTable.typename LIKE '%法拉利%' OR (UserTestTable.username LIKE '%用户1%' OR UserTestTable.createtime > 500))",
|
||||
node.toString());
|
||||
Assertions.assertEquals(node.toString(), beanNode.toString());
|
||||
Map<Class, String> nodeJoinTabalis = getJoinTabalis(node);
|
||||
Map<Class, String> beanJoinTabalis = getJoinTabalis(beanNode);
|
||||
System.out.println("nodeJoinTabalis: " + nodeJoinTabalis);
|
||||
System.out.println("beanJoinTabalis: " + beanJoinTabalis);
|
||||
CharSequence nodeJoinsql = createSQLJoin(node, func, false, nodeJoinTabalis, new HashSet<>(), carEntity);
|
||||
CharSequence beanJoinsql = createSQLJoin(beanNode, func, false, beanJoinTabalis, new HashSet<>(), carEntity);
|
||||
CharSequence nodeWhere = createSQLExpress(node, null, carEntity, nodeJoinTabalis);
|
||||
CharSequence beanWhere = createSQLExpress(beanNode, null, carEntity, beanJoinTabalis);
|
||||
String expect =
|
||||
"SELECT a.* FROM cartesttable a INNER JOIN cartypetable ctt ON a.cartype = ctt.cartype INNER JOIN usertesttable utt ON a.userid = utt.userid AND a.username = utt.username WHERE (ctt.typename LIKE '%法拉利%' OR (utt.username LIKE '%用户1%' OR utt.createtime > 500))";
|
||||
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);
|
||||
boolean r1 = isCacheUseable(node, func);
|
||||
Assertions.assertTrue(r1);
|
||||
if (!r1) {
|
||||
System.err.println("node.isCacheUseable 应该是true");
|
||||
}
|
||||
boolean r2 = isCacheUseable(beanNode, func);
|
||||
Assertions.assertTrue(r2);
|
||||
|
||||
System.out.println("node.Predicate = " + createPredicate(node, carEntity.getCache()));
|
||||
System.out.println("bean.Predicate = " + createPredicate(beanNode, 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 = GT)
|
||||
@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 = GT)
|
||||
@FilterJoinColumn(
|
||||
table = UserTestTable.class,
|
||||
columns = {"userid", "username"})
|
||||
public long createtime;
|
||||
|
||||
@FilterGroup("[OR]")
|
||||
@FilterColumn(express = LIKE)
|
||||
@FilterJoinColumn(
|
||||
table = CarTypeTable.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;
|
||||
}
|
||||
}
|
||||
|
||||
public static CarTestBean create() {
|
||||
final CarTestBean bean = new CarTestBean();
|
||||
bean.carid = 70002;
|
||||
bean.username = "用户1";
|
||||
bean.createtime = 500;
|
||||
bean.typename = "法拉利";
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
|
||||
@AutoLoad
|
||||
@Entity(cacheable = true)
|
||||
public static class CarTestTable {
|
||||
|
||||
public static List<CarTestTable> createList() {
|
||||
List<CarTestTable> 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
|
||||
@Entity(cacheable = true)
|
||||
public static class CarTypeTable {
|
||||
|
||||
public static List<CarTypeTable> createList() {
|
||||
List<CarTypeTable> list = new ArrayList<>();
|
||||
list.add(new CarTypeTable(101, "奥迪A1"));
|
||||
list.add(new CarTypeTable(102, "奥迪A2"));
|
||||
list.add(new CarTypeTable(103, "奥迪A3"));
|
||||
list.add(new CarTypeTable(104, "奥迪A4"));
|
||||
list.add(new CarTypeTable(105, "奥迪A5"));
|
||||
list.add(new CarTypeTable(201, "奔驰S1"));
|
||||
list.add(new CarTypeTable(202, "奔驰S2"));
|
||||
list.add(new CarTypeTable(203, "奔驰S3"));
|
||||
list.add(new CarTypeTable(204, "奔驰S4"));
|
||||
list.add(new CarTypeTable(205, "奔驰S5"));
|
||||
list.add(new CarTypeTable(301, "法拉利"));
|
||||
return list;
|
||||
}
|
||||
|
||||
@Id
|
||||
private int cartype;
|
||||
|
||||
private String typename;
|
||||
|
||||
public CarTypeTable() {}
|
||||
|
||||
public CarTypeTable(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
|
||||
@Entity(cacheable = true)
|
||||
public static class UserTestTable {
|
||||
|
||||
public static List<UserTestTable> createList() {
|
||||
List<UserTestTable> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,109 +17,109 @@ import org.redkale.util.AnyValueWriter;
|
||||
// @Cacheable
|
||||
public class JsonRecord {
|
||||
|
||||
@SourceConvert
|
||||
private static JsonConvert createConvert() {
|
||||
return JsonConvert.root();
|
||||
}
|
||||
@SourceConvert
|
||||
private static JsonConvert createConvert() {
|
||||
return JsonConvert.root();
|
||||
}
|
||||
|
||||
@Id
|
||||
@Column(comment = "主键ID;")
|
||||
private long recordid;
|
||||
@Id
|
||||
@Column(comment = "主键ID;")
|
||||
private long recordid;
|
||||
|
||||
@Column(comment = ";")
|
||||
private String recordname = "";
|
||||
@Column(comment = ";")
|
||||
private String recordname = "";
|
||||
|
||||
@Column(comment = ";")
|
||||
private Map<String, Integer> rmap;
|
||||
@Column(comment = ";")
|
||||
private Map<String, Integer> rmap;
|
||||
|
||||
@Column(comment = ";")
|
||||
private List<String> rlist;
|
||||
@Column(comment = ";")
|
||||
private List<String> rlist;
|
||||
|
||||
@Column(comment = ";")
|
||||
private Set<String> rset;
|
||||
@Column(comment = ";")
|
||||
private Set<String> rset;
|
||||
|
||||
public static JsonRecord create() {
|
||||
JsonRecord record = new JsonRecord();
|
||||
record.setRecordid(System.currentTimeMillis());
|
||||
record.setRecordname("my name");
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
map.put("str111", 10000);
|
||||
map.put("str222", 20000);
|
||||
record.setRmap(map);
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("item11");
|
||||
list.add("item22");
|
||||
list.add("item11");
|
||||
record.setRlist(list);
|
||||
Set<String> set = new HashSet<>();
|
||||
set.add("r1");
|
||||
set.add("r2");
|
||||
record.setRset(set);
|
||||
return record;
|
||||
}
|
||||
public static JsonRecord create() {
|
||||
JsonRecord record = new JsonRecord();
|
||||
record.setRecordid(System.currentTimeMillis());
|
||||
record.setRecordname("my name");
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
map.put("str111", 10000);
|
||||
map.put("str222", 20000);
|
||||
record.setRmap(map);
|
||||
List<String> list = new ArrayList<>();
|
||||
list.add("item11");
|
||||
list.add("item22");
|
||||
list.add("item11");
|
||||
record.setRlist(list);
|
||||
Set<String> set = new HashSet<>();
|
||||
set.add("r1");
|
||||
set.add("r2");
|
||||
record.setRset(set);
|
||||
return record;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
AnyValueWriter conf = AnyValueWriter.create();
|
||||
conf.addValue("name", "");
|
||||
conf.addValue(
|
||||
"url",
|
||||
"jdbc:mysql://localhost:3306/center?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true");
|
||||
conf.addValue("user", "root");
|
||||
conf.addValue("password", "");
|
||||
DataJdbcSource source = new DataJdbcSource();
|
||||
source.init(conf);
|
||||
JsonRecord record = JsonRecord.create();
|
||||
source.insert(record);
|
||||
source.updateColumn(JsonRecord.class, record.getRecordid(), ColumnValue.set("recordname", "my name 2"));
|
||||
record.getRmap().put("haha", 2222);
|
||||
source.updateColumn(JsonRecord.class, record.getRecordid(), ColumnValue.set("rmap", (Serializable)
|
||||
(Object) record.getRmap()));
|
||||
System.out.println(source.find(JsonRecord.class, record.getRecordid()));
|
||||
System.out.println(source.findColumn(JsonRecord.class, "rmap", record.getRecordid()));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
AnyValueWriter conf = AnyValueWriter.create();
|
||||
conf.addValue("name", "");
|
||||
conf.addValue(
|
||||
"url",
|
||||
"jdbc:mysql://localhost:3306/center?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true");
|
||||
conf.addValue("user", "root");
|
||||
conf.addValue("password", "");
|
||||
DataJdbcSource source = new DataJdbcSource();
|
||||
source.init(conf);
|
||||
JsonRecord record = JsonRecord.create();
|
||||
source.insert(record);
|
||||
source.updateColumn(JsonRecord.class, record.getRecordid(), ColumnValue.set("recordname", "my name 2"));
|
||||
record.getRmap().put("haha", 2222);
|
||||
source.updateColumn(JsonRecord.class, record.getRecordid(), ColumnValue.set("rmap", (Serializable)
|
||||
(Object) record.getRmap()));
|
||||
System.out.println(source.find(JsonRecord.class, record.getRecordid()));
|
||||
System.out.println(source.findColumn(JsonRecord.class, "rmap", record.getRecordid()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public long getRecordid() {
|
||||
return recordid;
|
||||
}
|
||||
public long getRecordid() {
|
||||
return recordid;
|
||||
}
|
||||
|
||||
public void setRecordid(long recordid) {
|
||||
this.recordid = recordid;
|
||||
}
|
||||
public void setRecordid(long recordid) {
|
||||
this.recordid = recordid;
|
||||
}
|
||||
|
||||
public String getRecordname() {
|
||||
return recordname;
|
||||
}
|
||||
public String getRecordname() {
|
||||
return recordname;
|
||||
}
|
||||
|
||||
public void setRecordname(String recordname) {
|
||||
this.recordname = recordname;
|
||||
}
|
||||
public void setRecordname(String recordname) {
|
||||
this.recordname = recordname;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getRmap() {
|
||||
return rmap;
|
||||
}
|
||||
public Map<String, Integer> getRmap() {
|
||||
return rmap;
|
||||
}
|
||||
|
||||
public void setRmap(Map<String, Integer> rmap) {
|
||||
this.rmap = rmap;
|
||||
}
|
||||
public void setRmap(Map<String, Integer> rmap) {
|
||||
this.rmap = rmap;
|
||||
}
|
||||
|
||||
public List<String> getRlist() {
|
||||
return rlist;
|
||||
}
|
||||
public List<String> getRlist() {
|
||||
return rlist;
|
||||
}
|
||||
|
||||
public void setRlist(List<String> rlist) {
|
||||
this.rlist = rlist;
|
||||
}
|
||||
public void setRlist(List<String> rlist) {
|
||||
this.rlist = rlist;
|
||||
}
|
||||
|
||||
public Set<String> getRset() {
|
||||
return rset;
|
||||
}
|
||||
public Set<String> getRset() {
|
||||
return rset;
|
||||
}
|
||||
|
||||
public void setRset(Set<String> rset) {
|
||||
this.rset = rset;
|
||||
}
|
||||
public void setRset(Set<String> rset) {
|
||||
this.rset = rset;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,147 +15,147 @@ import org.redkale.util.Utility;
|
||||
@DistributeTable(strategy = LoginRecord.TableStrategy.class)
|
||||
public class LoginRecord extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@Column(comment = "主键ID; 值=create36time(9位)+'-'+UUID(32位)")
|
||||
private String loginid = ""; // 主键ID; 值=create36time(9位)+'-'+UUID(32位)
|
||||
@Id
|
||||
@Column(comment = "主键ID; 值=create36time(9位)+'-'+UUID(32位)")
|
||||
private String loginid = ""; // 主键ID; 值=create36time(9位)+'-'+UUID(32位)
|
||||
|
||||
@Column(updatable = false, comment = "C端用户ID")
|
||||
private long userid; // C端用户ID
|
||||
@Column(updatable = false, comment = "C端用户ID")
|
||||
private long userid; // C端用户ID
|
||||
|
||||
@Column(updatable = false, comment = "登录网络类型; wifi/4g/3g")
|
||||
private String netmode = ""; // 登录网络类型; wifi/4g/3g
|
||||
@Column(updatable = false, comment = "登录网络类型; wifi/4g/3g")
|
||||
private String netmode = ""; // 登录网络类型; wifi/4g/3g
|
||||
|
||||
@Column(updatable = false, comment = "APP版本信息")
|
||||
private String appversion = ""; // APP版本信息
|
||||
@Column(updatable = false, comment = "APP版本信息")
|
||||
private String appversion = ""; // APP版本信息
|
||||
|
||||
@Column(updatable = false, comment = "APP操作系统信息")
|
||||
private String appos = ""; // APP操作系统信息
|
||||
@Column(updatable = false, comment = "APP操作系统信息")
|
||||
private String appos = ""; // APP操作系统信息
|
||||
|
||||
@Column(updatable = false, comment = "登录时客户端信息")
|
||||
private String loginagent = ""; // 登录时客户端信息
|
||||
@Column(updatable = false, comment = "登录时客户端信息")
|
||||
private String loginagent = ""; // 登录时客户端信息
|
||||
|
||||
@Column(updatable = false, comment = "登录时的IP")
|
||||
private String loginaddr = ""; // 登录时的IP
|
||||
@Column(updatable = false, comment = "登录时的IP")
|
||||
private String loginaddr = ""; // 登录时的IP
|
||||
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
|
||||
/** 以下省略getter setter方法 */
|
||||
//
|
||||
public void setLoginid(String loginid) {
|
||||
this.loginid = loginid;
|
||||
}
|
||||
/** 以下省略getter setter方法 */
|
||||
//
|
||||
public void setLoginid(String loginid) {
|
||||
this.loginid = loginid;
|
||||
}
|
||||
|
||||
public String getLoginid() {
|
||||
return this.loginid;
|
||||
}
|
||||
public String getLoginid() {
|
||||
return this.loginid;
|
||||
}
|
||||
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public long getUserid() {
|
||||
return this.userid;
|
||||
}
|
||||
public long getUserid() {
|
||||
return this.userid;
|
||||
}
|
||||
|
||||
public void setNetmode(String netmode) {
|
||||
this.netmode = netmode;
|
||||
}
|
||||
public void setNetmode(String netmode) {
|
||||
this.netmode = netmode;
|
||||
}
|
||||
|
||||
public String getNetmode() {
|
||||
return this.netmode;
|
||||
}
|
||||
public String getNetmode() {
|
||||
return this.netmode;
|
||||
}
|
||||
|
||||
public String getAppversion() {
|
||||
return appversion;
|
||||
}
|
||||
public String getAppversion() {
|
||||
return appversion;
|
||||
}
|
||||
|
||||
public void setAppversion(String appversion) {
|
||||
this.appversion = appversion;
|
||||
}
|
||||
public void setAppversion(String appversion) {
|
||||
this.appversion = appversion;
|
||||
}
|
||||
|
||||
public String getAppos() {
|
||||
return appos;
|
||||
}
|
||||
public String getAppos() {
|
||||
return appos;
|
||||
}
|
||||
|
||||
public void setAppos(String appos) {
|
||||
this.appos = appos;
|
||||
}
|
||||
public void setAppos(String appos) {
|
||||
this.appos = appos;
|
||||
}
|
||||
|
||||
public void setLoginagent(String loginagent) {
|
||||
this.loginagent = loginagent;
|
||||
}
|
||||
public void setLoginagent(String loginagent) {
|
||||
this.loginagent = loginagent;
|
||||
}
|
||||
|
||||
public String getLoginagent() {
|
||||
return this.loginagent;
|
||||
}
|
||||
public String getLoginagent() {
|
||||
return this.loginagent;
|
||||
}
|
||||
|
||||
public void setLoginaddr(String loginaddr) {
|
||||
this.loginaddr = loginaddr;
|
||||
}
|
||||
public void setLoginaddr(String loginaddr) {
|
||||
this.loginaddr = loginaddr;
|
||||
}
|
||||
|
||||
public String getLoginaddr() {
|
||||
return this.loginaddr;
|
||||
}
|
||||
public String getLoginaddr() {
|
||||
return this.loginaddr;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return this.createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return this.createtime;
|
||||
}
|
||||
|
||||
private static DataSource source;
|
||||
private static DataSource source;
|
||||
|
||||
// 创建对象
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoginRecord record = new LoginRecord();
|
||||
long now = System.currentTimeMillis();
|
||||
record.setCreatetime(now); // 设置创建时间
|
||||
record.setLoginid(Times.format36time(now) + "-" + Utility.uuid()); // 主键的生成规则
|
||||
// .... 填充其他字段
|
||||
source.insert(record);
|
||||
}
|
||||
// 创建对象
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoginRecord record = new LoginRecord();
|
||||
long now = System.currentTimeMillis();
|
||||
record.setCreatetime(now); // 设置创建时间
|
||||
record.setLoginid(Times.format36time(now) + "-" + Utility.uuid()); // 主键的生成规则
|
||||
// .... 填充其他字段
|
||||
source.insert(record);
|
||||
}
|
||||
|
||||
public static class TableStrategy implements DistributeTableStrategy<LoginRecord> {
|
||||
public static class TableStrategy implements DistributeTableStrategy<LoginRecord> {
|
||||
|
||||
private static final String dayformat = "%1$tY%1$tm%1$td"; // 一天一个表
|
||||
private static final String dayformat = "%1$tY%1$tm%1$td"; // 一天一个表
|
||||
|
||||
private static final String yearformat = "%1$tY"; // 一年一个库
|
||||
private static final String yearformat = "%1$tY"; // 一年一个库
|
||||
|
||||
// 过滤查询时调用本方法
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable day = node.findValue("#day"); // LoginRecord没有day字段,所以前面要加#,表示虚拟字段, 值为yyyyMMdd格式
|
||||
if (day != null) getTable(table, (Integer) day, 0L); // 存在#day参数则直接使用day值
|
||||
Serializable time = node.findValue("createtime"); // 存在createtime则使用最小时间,且createtime的范围必须在一天内,因为本表以天为单位建表
|
||||
if (time instanceof Long) {
|
||||
return new String[] {getTable(table, 0, (Long) time)};
|
||||
}
|
||||
Range.LongRange createTime = (Range.LongRange) time;
|
||||
return new String[] {getTable(table, 0, createTime.getMin())};
|
||||
}
|
||||
// 过滤查询时调用本方法
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable day = node.findValue("#day"); // LoginRecord没有day字段,所以前面要加#,表示虚拟字段, 值为yyyyMMdd格式
|
||||
if (day != null) getTable(table, (Integer) day, 0L); // 存在#day参数则直接使用day值
|
||||
Serializable time = node.findValue("createtime"); // 存在createtime则使用最小时间,且createtime的范围必须在一天内,因为本表以天为单位建表
|
||||
if (time instanceof Long) {
|
||||
return new String[] {getTable(table, 0, (Long) time)};
|
||||
}
|
||||
Range.LongRange createTime = (Range.LongRange) time;
|
||||
return new String[] {getTable(table, 0, createTime.getMin())};
|
||||
}
|
||||
|
||||
// 创建或单个查询时调用本方法
|
||||
@Override
|
||||
public String getTable(String table, LoginRecord bean) {
|
||||
return getTable(table, 0, bean.getCreatetime());
|
||||
}
|
||||
// 创建或单个查询时调用本方法
|
||||
@Override
|
||||
public String getTable(String table, LoginRecord bean) {
|
||||
return getTable(table, 0, bean.getCreatetime());
|
||||
}
|
||||
|
||||
// 根据主键ID查询单个记录时调用本方法
|
||||
@Override
|
||||
public String getTable(String table, Serializable primary) {
|
||||
String id = (String) primary;
|
||||
return getTable(table, 0, Long.parseLong(id.substring(0, 9), 36));
|
||||
}
|
||||
// 根据主键ID查询单个记录时调用本方法
|
||||
@Override
|
||||
public String getTable(String table, Serializable primary) {
|
||||
String id = (String) primary;
|
||||
return getTable(table, 0, Long.parseLong(id.substring(0, 9), 36));
|
||||
}
|
||||
|
||||
private String getTable(String table, int day, long createtime) { // day为0或yyyyMMdd格式数据
|
||||
int pos = table.indexOf('.');
|
||||
String year =
|
||||
day > 0 ? String.valueOf(day / 10000) : String.format(yearformat, createtime); // 没有day取createtime
|
||||
return "platf_login_" + year + "." + table.substring(pos + 1) + "_"
|
||||
+ (day > 0 ? day : String.format(dayformat, createtime));
|
||||
}
|
||||
}
|
||||
private String getTable(String table, int day, long createtime) { // day为0或yyyyMMdd格式数据
|
||||
int pos = table.indexOf('.');
|
||||
String year =
|
||||
day > 0 ? String.valueOf(day / 10000) : String.format(yearformat, createtime); // 没有day取createtime
|
||||
return "platf_login_" + year + "." + table.substring(pos + 1) + "_"
|
||||
+ (day > 0 ? day : String.format(dayformat, createtime));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,42 +13,42 @@ import org.redkale.source.*;
|
||||
/** @author zhangjx */
|
||||
public class LoginTestBean implements FilterBean {
|
||||
|
||||
private String sessionid;
|
||||
private String sessionid;
|
||||
|
||||
private int sid;
|
||||
private int sid;
|
||||
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoginTestBean bean = new LoginTestBean();
|
||||
bean.setSessionid("xxx");
|
||||
bean.setSid(23333);
|
||||
BiFunction<DataSource, Class, List> fullloader = (s, z) -> new ArrayList();
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<CacheTestBean> info = (EntityInfo<CacheTestBean>)
|
||||
method.invoke(null, CacheTestBean.class, true, new Properties(), null, fullloader);
|
||||
EntityCache<CacheTestBean> cache = new EntityCache(info, null);
|
||||
FilterNode node = FilterNodeBean.createFilterNode(bean);
|
||||
System.out.println("cache = " + cache + ", node = " + node);
|
||||
Method pre = FilterNode.class.getDeclaredMethod("createPredicate", EntityCache.class);
|
||||
pre.setAccessible(true);
|
||||
// 为null是因为CacheTestBean 没有sid和sessionid这两个字段
|
||||
System.out.println(pre.invoke(node, cache));
|
||||
}
|
||||
public static void main(String[] args) throws Throwable {
|
||||
LoginTestBean bean = new LoginTestBean();
|
||||
bean.setSessionid("xxx");
|
||||
bean.setSid(23333);
|
||||
BiFunction<DataSource, Class, List> fullloader = (s, z) -> new ArrayList();
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<CacheTestBean> info = (EntityInfo<CacheTestBean>)
|
||||
method.invoke(null, CacheTestBean.class, true, new Properties(), null, fullloader);
|
||||
EntityCache<CacheTestBean> cache = new EntityCache(info, null);
|
||||
FilterNode node = FilterNodeBean.createFilterNode(bean);
|
||||
System.out.println("cache = " + cache + ", node = " + node);
|
||||
Method pre = FilterNode.class.getDeclaredMethod("createPredicate", EntityCache.class);
|
||||
pre.setAccessible(true);
|
||||
// 为null是因为CacheTestBean 没有sid和sessionid这两个字段
|
||||
System.out.println(pre.invoke(node, cache));
|
||||
}
|
||||
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
|
||||
public int getSid() {
|
||||
return sid;
|
||||
}
|
||||
public int getSid() {
|
||||
return sid;
|
||||
}
|
||||
|
||||
public void setSid(int sid) {
|
||||
this.sid = sid;
|
||||
}
|
||||
public void setSid(int sid) {
|
||||
this.sid = sid;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,69 +18,69 @@ import org.redkale.persistence.Id;
|
||||
*/
|
||||
public class LoginTestRecord {
|
||||
|
||||
@Id
|
||||
private String sessionid;
|
||||
@Id
|
||||
private String sessionid;
|
||||
|
||||
private int userid;
|
||||
private int userid;
|
||||
|
||||
private String loginagent;
|
||||
private String loginagent;
|
||||
|
||||
private String loginip;
|
||||
private String loginip;
|
||||
|
||||
private long logintime;
|
||||
private long logintime;
|
||||
|
||||
private long logouttime;
|
||||
private long logouttime;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
public String getSessionid() {
|
||||
return sessionid;
|
||||
}
|
||||
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
public void setSessionid(String sessionid) {
|
||||
this.sessionid = sessionid;
|
||||
}
|
||||
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getLoginagent() {
|
||||
return loginagent;
|
||||
}
|
||||
public String getLoginagent() {
|
||||
return loginagent;
|
||||
}
|
||||
|
||||
public void setLoginagent(String loginagent) {
|
||||
this.loginagent = loginagent;
|
||||
}
|
||||
public void setLoginagent(String loginagent) {
|
||||
this.loginagent = loginagent;
|
||||
}
|
||||
|
||||
public String getLoginip() {
|
||||
return loginip;
|
||||
}
|
||||
public String getLoginip() {
|
||||
return loginip;
|
||||
}
|
||||
|
||||
public void setLoginip(String loginip) {
|
||||
this.loginip = loginip;
|
||||
}
|
||||
public void setLoginip(String loginip) {
|
||||
this.loginip = loginip;
|
||||
}
|
||||
|
||||
public long getLogintime() {
|
||||
return logintime;
|
||||
}
|
||||
public long getLogintime() {
|
||||
return logintime;
|
||||
}
|
||||
|
||||
public void setLogintime(long logintime) {
|
||||
this.logintime = logintime;
|
||||
}
|
||||
public void setLogintime(long logintime) {
|
||||
this.logintime = logintime;
|
||||
}
|
||||
|
||||
public long getLogouttime() {
|
||||
return logouttime;
|
||||
}
|
||||
public long getLogouttime() {
|
||||
return logouttime;
|
||||
}
|
||||
|
||||
public void setLogouttime(long logouttime) {
|
||||
this.logouttime = logouttime;
|
||||
}
|
||||
public void setLogouttime(long logouttime) {
|
||||
this.logouttime = logouttime;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,76 +13,76 @@ import org.redkale.source.*;
|
||||
@DistributeTable(strategy = LoginUserRecord.TableStrategy.class)
|
||||
public class LoginUserRecord extends BaseEntity {
|
||||
|
||||
@Id
|
||||
@Column(comment = "记录ID; 值=userid+'-'+UUID")
|
||||
private String seqid = ""; // 记录ID; 值=userid+'-'+UUID
|
||||
@Id
|
||||
@Column(comment = "记录ID; 值=userid+'-'+UUID")
|
||||
private String seqid = ""; // 记录ID; 值=userid+'-'+UUID
|
||||
|
||||
@Column(updatable = false, comment = "C端用户ID")
|
||||
private long userid; // C端用户ID
|
||||
@Column(updatable = false, comment = "C端用户ID")
|
||||
private long userid; // C端用户ID
|
||||
|
||||
@Column(comment = "LoginRecord主键")
|
||||
private String loginid = ""; // LoginRecord主键
|
||||
@Column(comment = "LoginRecord主键")
|
||||
private String loginid = ""; // LoginRecord主键
|
||||
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
|
||||
/** 以下省略getter setter方法 */
|
||||
//
|
||||
public String getSeqid() {
|
||||
return seqid;
|
||||
}
|
||||
/** 以下省略getter setter方法 */
|
||||
//
|
||||
public String getSeqid() {
|
||||
return seqid;
|
||||
}
|
||||
|
||||
public void setSeqid(String seqid) {
|
||||
this.seqid = seqid;
|
||||
}
|
||||
public void setSeqid(String seqid) {
|
||||
this.seqid = seqid;
|
||||
}
|
||||
|
||||
public long getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public long getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getLoginid() {
|
||||
return loginid;
|
||||
}
|
||||
public String getLoginid() {
|
||||
return loginid;
|
||||
}
|
||||
|
||||
public void setLoginid(String loginid) {
|
||||
this.loginid = loginid;
|
||||
}
|
||||
public void setLoginid(String loginid) {
|
||||
this.loginid = loginid;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
|
||||
public static class TableStrategy implements DistributeTableStrategy<LoginUserRecord> {
|
||||
public static class TableStrategy implements DistributeTableStrategy<LoginUserRecord> {
|
||||
|
||||
@Override
|
||||
public String getTable(String table, LoginUserRecord bean) {
|
||||
return getTable(table, bean.getUserid());
|
||||
}
|
||||
@Override
|
||||
public String getTable(String table, LoginUserRecord bean) {
|
||||
return getTable(table, bean.getUserid());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable id = node.findValue("userid");
|
||||
if (id != null) return new String[] {getTable(table, id)};
|
||||
return new String[] {getHashTable(table, (Integer) node.findValue("#hash"))};
|
||||
}
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable id = node.findValue("userid");
|
||||
if (id != null) return new String[] {getTable(table, id)};
|
||||
return new String[] {getHashTable(table, (Integer) node.findValue("#hash"))};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTable(String table, Serializable primary) {
|
||||
String id = (String) primary;
|
||||
return getHashTable(table, (int) (Long.parseLong(id.substring(0, id.indexOf('-'))) % 100));
|
||||
}
|
||||
@Override
|
||||
public String getTable(String table, Serializable primary) {
|
||||
String id = (String) primary;
|
||||
return getHashTable(table, (int) (Long.parseLong(id.substring(0, id.indexOf('-'))) % 100));
|
||||
}
|
||||
|
||||
private String getHashTable(String table, int hash) {
|
||||
int pos = table.indexOf('.');
|
||||
return "platf_login." + table.substring(pos + 1) + "_" + (hash > 9 ? hash : ("0" + hash));
|
||||
}
|
||||
}
|
||||
private String getHashTable(String table, int hash) {
|
||||
int pos = table.indexOf('.');
|
||||
return "platf_login." + table.substring(pos + 1) + "_" + (hash > 9 ? hash : ("0" + hash));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,116 +19,116 @@ import org.redkale.util.Sheet;
|
||||
/** @author zhangjx */
|
||||
public class TestSourceCache {
|
||||
|
||||
public static class TestEntityBean implements FilterBean {
|
||||
public static class TestEntityBean implements FilterBean {
|
||||
|
||||
@FilterColumn(express = FilterExpress.GT)
|
||||
public int userid;
|
||||
@FilterColumn(express = FilterExpress.GT)
|
||||
public int userid;
|
||||
|
||||
@FilterColumn(express = FilterExpress.LIKE)
|
||||
public String username;
|
||||
@FilterColumn(express = FilterExpress.LIKE)
|
||||
public String username;
|
||||
|
||||
public TestEntityBean(int userid, String username) {
|
||||
this.userid = userid;
|
||||
this.username = username;
|
||||
}
|
||||
}
|
||||
public TestEntityBean(int userid, String username) {
|
||||
this.userid = userid;
|
||||
this.username = username;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
final BiFunction<DataSource, Class, List> fullloader = (DataSource t, Class u) -> null;
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<TestEntity> info = (EntityInfo<TestEntity>)
|
||||
method.invoke(null, TestEntity.class, false, new Properties(), null, fullloader);
|
||||
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 + " 秒");
|
||||
public static void main(String[] args) throws Exception {
|
||||
final BiFunction<DataSource, Class, List> fullloader = (DataSource t, Class u) -> null;
|
||||
Method method = EntityInfo.class.getDeclaredMethod(
|
||||
"load", Class.class, boolean.class, Properties.class, DataSource.class, BiFunction.class);
|
||||
method.setAccessible(true);
|
||||
final EntityInfo<TestEntity> info = (EntityInfo<TestEntity>)
|
||||
method.invoke(null, TestEntity.class, false, new Properties(), null, fullloader);
|
||||
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);
|
||||
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 = FilterNodes.gt("userid", 1000).like("username", "用户");
|
||||
System.out.println("node = " + node);
|
||||
final FilterNode node2 = FilterNodes.gt(TestEntity::getUserid, 1000).like("username", "用户");
|
||||
Assertions.assertEquals(node.toString(), node2.toString());
|
||||
Sheet<TestEntity> 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, false, null, flipper, node);
|
||||
}
|
||||
cdl.countDown();
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
cdl.await();
|
||||
e = System.currentTimeMillis() - s;
|
||||
System.out.println("十万条数据中100并发查询一页循环10次记录耗时: " + e / 1000.0 + " 秒 "
|
||||
+ sheet); // CopyOnWriteArrayList 0.798 ConcurrentLinkedQueue 1.063
|
||||
}
|
||||
final Flipper flipper = new Flipper(2);
|
||||
flipper.setSort("userid DESC, createtime DESC");
|
||||
final FilterNode node = FilterNodes.gt("userid", 1000).like("username", "用户");
|
||||
System.out.println("node = " + node);
|
||||
final FilterNode node2 = FilterNodes.gt(TestEntity::getUserid, 1000).like("username", "用户");
|
||||
Assertions.assertEquals(node.toString(), node2.toString());
|
||||
Sheet<TestEntity> 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, false, null, flipper, node);
|
||||
}
|
||||
cdl.countDown();
|
||||
}
|
||||
}.start();
|
||||
}
|
||||
cdl.await();
|
||||
e = System.currentTimeMillis() - s;
|
||||
System.out.println("十万条数据中100并发查询一页循环10次记录耗时: " + e / 1000.0 + " 秒 "
|
||||
+ sheet); // CopyOnWriteArrayList 0.798 ConcurrentLinkedQueue 1.063
|
||||
}
|
||||
|
||||
@VirtualEntity
|
||||
public static class TestEntity {
|
||||
@VirtualEntity
|
||||
public static class TestEntity {
|
||||
|
||||
@Id
|
||||
private int userid;
|
||||
@Id
|
||||
private int userid;
|
||||
|
||||
private String username;
|
||||
private String username;
|
||||
|
||||
private long createtime = System.currentTimeMillis();
|
||||
private long createtime = System.currentTimeMillis();
|
||||
|
||||
public TestEntity() {}
|
||||
public TestEntity() {}
|
||||
|
||||
public TestEntity(int userid, String username) {
|
||||
this.userid = userid;
|
||||
this.username = username;
|
||||
}
|
||||
public TestEntity(int userid, String username) {
|
||||
this.userid = userid;
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
public int getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(int userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,96 +14,96 @@ import org.redkale.source.*;
|
||||
@DistributeTable(strategy = UserDetail.TableStrategy.class)
|
||||
public class UserDetail extends BaseEntity {
|
||||
|
||||
public static class TableStrategy implements DistributeTableStrategy<UserDetail> {
|
||||
public static class TableStrategy implements DistributeTableStrategy<UserDetail> {
|
||||
|
||||
@Override
|
||||
public String getTable(String table, UserDetail bean) {
|
||||
return getTable(table, bean.getUserid());
|
||||
}
|
||||
@Override
|
||||
public String getTable(String table, UserDetail bean) {
|
||||
return getTable(table, bean.getUserid());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable id = node.findValue("userid");
|
||||
if (id != null) return new String[] {getTable(table, id)};
|
||||
return new String[] {getHashTable(table, (Integer) node.findValue("#hash"))};
|
||||
}
|
||||
@Override
|
||||
public String[] getTables(String table, FilterNode node) {
|
||||
Serializable id = node.findValue("userid");
|
||||
if (id != null) return new String[] {getTable(table, id)};
|
||||
return new String[] {getHashTable(table, (Integer) node.findValue("#hash"))};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTable(String table, Serializable userid) {
|
||||
return getHashTable(table, (int) (((Long) userid) % 100));
|
||||
}
|
||||
@Override
|
||||
public String getTable(String table, Serializable userid) {
|
||||
return getHashTable(table, (int) (((Long) userid) % 100));
|
||||
}
|
||||
|
||||
private String getHashTable(String table, int hash) {
|
||||
int pos = table.indexOf('.');
|
||||
return "platf_user." + table.substring(pos + 1) + "_" + (hash > 9 ? hash : ("0" + hash));
|
||||
}
|
||||
}
|
||||
private String getHashTable(String table, int hash) {
|
||||
int pos = table.indexOf('.');
|
||||
return "platf_user." + table.substring(pos + 1) + "_" + (hash > 9 ? hash : ("0" + hash));
|
||||
}
|
||||
}
|
||||
|
||||
@Id
|
||||
private long userid; // 用户ID
|
||||
@Id
|
||||
private long userid; // 用户ID
|
||||
|
||||
@Column(length = 64, comment = "用户昵称")
|
||||
private String username = ""; // 用户昵称
|
||||
@Column(length = 64, comment = "用户昵称")
|
||||
private String username = ""; // 用户昵称
|
||||
|
||||
@Column(length = 32, comment = "手机号码")
|
||||
private String mobile = ""; // 手机号码
|
||||
@Column(length = 32, comment = "手机号码")
|
||||
private String mobile = ""; // 手机号码
|
||||
|
||||
@Column(length = 64, comment = "密码")
|
||||
@ConvertColumn(ignore = true, type = ConvertType.ALL)
|
||||
private String password = ""; // 密码
|
||||
@Column(length = 64, comment = "密码")
|
||||
@ConvertColumn(ignore = true, type = ConvertType.ALL)
|
||||
private String password = ""; // 密码
|
||||
|
||||
@Column(length = 128, comment = "备注")
|
||||
private String remark = ""; // 备注
|
||||
@Column(length = 128, comment = "备注")
|
||||
private String remark = ""; // 备注
|
||||
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
@Column(updatable = false, comment = "创建时间")
|
||||
private long createtime; // 创建时间
|
||||
|
||||
/** 以下省略getter setter方法 */
|
||||
public long getUserid() {
|
||||
return userid;
|
||||
}
|
||||
/** 以下省略getter setter方法 */
|
||||
public long getUserid() {
|
||||
return userid;
|
||||
}
|
||||
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
public void setUserid(long userid) {
|
||||
this.userid = userid;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getMobile() {
|
||||
return mobile;
|
||||
}
|
||||
public String getMobile() {
|
||||
return mobile;
|
||||
}
|
||||
|
||||
public void setMobile(String mobile) {
|
||||
this.mobile = mobile;
|
||||
}
|
||||
public void setMobile(String mobile) {
|
||||
this.mobile = mobile;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
public String getRemark() {
|
||||
return remark;
|
||||
}
|
||||
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
public void setRemark(String remark) {
|
||||
this.remark = remark;
|
||||
}
|
||||
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
public long getCreatetime() {
|
||||
return createtime;
|
||||
}
|
||||
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
public void setCreatetime(long createtime) {
|
||||
this.createtime = createtime;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ import org.redkale.persistence.*;
|
||||
@Entity
|
||||
public abstract class BaseEntity implements Serializable {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return JsonConvert.root().convertTo(this);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user