This commit is contained in:
redkale
2024-05-27 12:19:58 +08:00
parent 4d1eaa9766
commit 5079560037
356 changed files with 81489 additions and 81489 deletions

View File

@@ -1,39 +1,39 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.asm;
import java.io.*;
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>", "&#60;tt&#62;")
.replace("</tt>", "&#60;/tt&#62;")
.replace("{@link org.redkale.asm.tree.MethodNode#getLabelNode} method.", "")
.getBytes());
out.close();
}
// 需要屏蔽ClassReader中判断checks the class version的部分
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.asm;
import java.io.*;
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>", "&#60;tt&#62;")
.replace("</tt>", "&#60;/tt&#62;")
.replace("{@link org.redkale.asm.tree.MethodNode#getLabelNode} method.", "")
.getBytes());
out.close();
}
// 需要屏蔽ClassReader中判断checks the class version的部分
}
}

View File

@@ -1,119 +1,119 @@
/*
*
*/
package org.redkale.test.cache;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.redkale.annotation.Resource;
import org.redkale.cache.CacheManager;
import org.redkale.cache.Cached;
import org.redkale.service.Service;
import org.redkale.source.Range;
import org.redkale.util.RedkaleException;
/** @author zhangjx */
public class CacheInstance implements Service {
@Resource
private CacheManager cacheManager;
// 修改远程缓存的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 = "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")
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 = "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",
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 {
private String name;
private int day;
private Integer status;
private Range.IntRange range;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Range.IntRange getRange() {
return range;
}
public void setRange(Range.IntRange range) {
this.range = range;
}
}
}
/*
*
*/
package org.redkale.test.cache;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.redkale.annotation.Resource;
import org.redkale.cache.CacheManager;
import org.redkale.cache.Cached;
import org.redkale.service.Service;
import org.redkale.source.Range;
import org.redkale.util.RedkaleException;
/** @author zhangjx */
public class CacheInstance implements Service {
@Resource
private CacheManager cacheManager;
// 修改远程缓存的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 = "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")
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 = "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",
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 {
private String name;
private int day;
private Integer status;
private Range.IntRange range;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Range.IntRange getRange() {
return range;
}
public void setRange(Range.IntRange range) {
this.range = range;
}
}
}

View File

@@ -1,62 +1,62 @@
/*
*
*/
package org.redkale.test.cache;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.redkale.cache.CacheManager;
import org.redkale.cache.spi.CacheAsmMethodBoost;
import org.redkale.cache.spi.CacheManagerService;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.Sncp;
import org.redkale.net.sncp.SncpClient;
import org.redkale.net.sncp.SncpRpcGroups;
import org.redkale.source.CacheMemorySource;
import org.redkale.util.Environment;
import org.redkale.util.Utility;
/** @author zhangjx */
public class CacheInstanceTest {
private static ResourceFactory resourceFactory;
private static CacheManagerService manager;
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);
}
@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 {}
}
/*
*
*/
package org.redkale.test.cache;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.redkale.cache.CacheManager;
import org.redkale.cache.spi.CacheAsmMethodBoost;
import org.redkale.cache.spi.CacheManagerService;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.Sncp;
import org.redkale.net.sncp.SncpClient;
import org.redkale.net.sncp.SncpRpcGroups;
import org.redkale.source.CacheMemorySource;
import org.redkale.util.Environment;
import org.redkale.util.Utility;
/** @author zhangjx */
public class CacheInstanceTest {
private static ResourceFactory resourceFactory;
private static CacheManagerService manager;
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);
}
@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 {}
}

View File

@@ -1,144 +1,144 @@
/*
*
*/
package org.redkale.test.cache;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.*;
import org.redkale.cache.spi.CacheManagerService;
import org.redkale.convert.json.JsonConvert;
import org.redkale.source.CacheMemorySource;
import org.redkale.util.Utility;
/** @author zhangjx */
public class CacheManagerTest {
private static CacheManagerService manager;
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);
}
@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("这是名字备注");
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());
}
public static class ParallelBean {
public static final AtomicInteger c1 = new AtomicInteger();
public String getName() {
c1.incrementAndGet();
System.out.println("执行了getName方法(" + c1.get() + ")");
return "hello";
}
}
public static class CachingBean {
private String name;
private String remark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}
/*
*
*/
package org.redkale.test.cache;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.*;
import org.redkale.cache.spi.CacheManagerService;
import org.redkale.convert.json.JsonConvert;
import org.redkale.source.CacheMemorySource;
import org.redkale.util.Utility;
/** @author zhangjx */
public class CacheManagerTest {
private static CacheManagerService manager;
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);
}
@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("这是名字备注");
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());
}
public static class ParallelBean {
public static final AtomicInteger c1 = new AtomicInteger();
public String getName() {
c1.incrementAndGet();
System.out.println("执行了getName方法(" + c1.get() + ")");
return "hello";
}
}
public static class CachingBean {
private String name;
private String remark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}

View File

@@ -1,172 +1,172 @@
/*
*
*/
package org.redkale.test.cache;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.redkale.annotation.Resource;
import org.redkale.annotation.ResourceType;
import org.redkale.cache.spi.CacheAction;
import org.redkale.cache.spi.DynForCache;
import org.redkale.net.sncp.Sncp.SncpDyn;
import org.redkale.util.AnyValue;
import org.redkale.util.RedkaleException;
import org.redkale.util.ThrowSupplier;
@Resource(name = "")
@SncpDyn(remote = false, type = CacheInstance.class)
@ResourceType(CacheInstance.class)
public class _DynLocalCacheInstance extends CacheInstance {
private AnyValue _redkale_conf;
private String _redkale_mq;
private CacheAction _redkale_getNameCacheAction1;
private CacheAction _redkale_getInfoCacheAction2;
private CacheAction _redkale_getNameAsyncCacheAction3;
private CacheAction _redkale_getInfo2AsyncCacheAction4;
private CacheAction _redkale_getName2AsyncCacheAction5;
private CacheAction _redkale_getInfoAsyncCacheAction6;
private CacheAction _redkale_getName2CacheAction7;
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
private String getName2_afterCache() throws RedkaleException {
return super.getName2();
}
}
/*
*
*/
package org.redkale.test.cache;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.redkale.annotation.Resource;
import org.redkale.annotation.ResourceType;
import org.redkale.cache.spi.CacheAction;
import org.redkale.cache.spi.DynForCache;
import org.redkale.net.sncp.Sncp.SncpDyn;
import org.redkale.util.AnyValue;
import org.redkale.util.RedkaleException;
import org.redkale.util.ThrowSupplier;
@Resource(name = "")
@SncpDyn(remote = false, type = CacheInstance.class)
@ResourceType(CacheInstance.class)
public class _DynLocalCacheInstance extends CacheInstance {
private AnyValue _redkale_conf;
private String _redkale_mq;
private CacheAction _redkale_getNameCacheAction1;
private CacheAction _redkale_getInfoCacheAction2;
private CacheAction _redkale_getNameAsyncCacheAction3;
private CacheAction _redkale_getInfo2AsyncCacheAction4;
private CacheAction _redkale_getName2AsyncCacheAction5;
private CacheAction _redkale_getInfoAsyncCacheAction6;
private CacheAction _redkale_getName2CacheAction7;
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
private String getName2_afterCache() throws RedkaleException {
return super.getName2();
}
}

View File

@@ -1,73 +1,73 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.convert.ConvertField;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.Attribute;
/** @author zhangjx */
public class BiFunctionConvertTest {
public static class GamePlayer {
public int userid;
public String username;
public int[] cards;
}
public static class GameTable {
public int tableid;
public GamePlayer[] players;
}
@Test
public void run() throws Throwable {
GamePlayer player1 = new GamePlayer();
player1.userid = 1;
player1.username = "玩家1";
player1.cards = new int[] {11, 12, 13, 14, 15};
GamePlayer player2 = new GamePlayer();
player2.userid = 2;
player2.username = "玩家2";
player2.cards = new int[] {21, 22, 23, 24, 25};
GamePlayer player3 = new GamePlayer();
player3.userid = 3;
player3.username = "玩家3";
player3.cards = new int[] {31, 32, 33, 34, 35};
GameTable table = new GameTable();
table.tableid = 100;
table.players = new GamePlayer[] {player1, player2, player3};
JsonConvert convert1 = JsonConvert.root();
System.out.println(convert1.convertTo(table));
JsonConvert convert2 = convert1.newConvert(
(Attribute t, Object u) -> {
if (t.field().equals("cards") && u instanceof GamePlayer) {
int userid = ((GamePlayer) u).userid;
if (userid == 3) return null; // 玩家3的cards不输出
return t.get(u);
}
return t.get(u);
},
(Object u) -> {
if (table != u) return null;
// return new ConvertField[]{new ConvertField("extcol1", 30), new ConvertField("extcol2", "扩展字段值")};
return ConvertField.ofArray("extcol1", 30, "extcol2", "扩展字段值");
});
System.out.println(convert2.convertTo(table));
Assertions.assertEquals(
"{\"players\":[{\"cards\":[11,12,13,14,15],\"userid\":1,\"username\":\"玩家1\"},{\"cards\":[21,22,23,24,25],\"userid\":2,\"username\":\"玩家2\"},{\"userid\":3,\"username\":\"玩家3\"}],\"tableid\":100,\"extcol1\":30,\"extcol2\":\"扩展字段值\"}",
convert2.convertTo(table));
// {"players":[{"cards":[11,12,13,14,15],"userid":1,"username":"玩家1"},{"cards":[21,22,23,24,25],"userid":2,"username":"玩家2"},{"cards":[31,32,33,34,35],"userid":3,"username":"玩家3"}],"tableid":100}
// {"players":[{"cards":[11,12,13,14,15],"userid":1,"username":"玩家1"},{"cards":[21,22,23,24,25],"userid":2,"username":"玩家2"},{"userid":3,"username":"玩家3"}],"tableid":100,"extcol1":30,"extcol2":"扩展字段值"}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.convert.ConvertField;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.Attribute;
/** @author zhangjx */
public class BiFunctionConvertTest {
public static class GamePlayer {
public int userid;
public String username;
public int[] cards;
}
public static class GameTable {
public int tableid;
public GamePlayer[] players;
}
@Test
public void run() throws Throwable {
GamePlayer player1 = new GamePlayer();
player1.userid = 1;
player1.username = "玩家1";
player1.cards = new int[] {11, 12, 13, 14, 15};
GamePlayer player2 = new GamePlayer();
player2.userid = 2;
player2.username = "玩家2";
player2.cards = new int[] {21, 22, 23, 24, 25};
GamePlayer player3 = new GamePlayer();
player3.userid = 3;
player3.username = "玩家3";
player3.cards = new int[] {31, 32, 33, 34, 35};
GameTable table = new GameTable();
table.tableid = 100;
table.players = new GamePlayer[] {player1, player2, player3};
JsonConvert convert1 = JsonConvert.root();
System.out.println(convert1.convertTo(table));
JsonConvert convert2 = convert1.newConvert(
(Attribute t, Object u) -> {
if (t.field().equals("cards") && u instanceof GamePlayer) {
int userid = ((GamePlayer) u).userid;
if (userid == 3) return null; // 玩家3的cards不输出
return t.get(u);
}
return t.get(u);
},
(Object u) -> {
if (table != u) return null;
// return new ConvertField[]{new ConvertField("extcol1", 30), new ConvertField("extcol2", "扩展字段值")};
return ConvertField.ofArray("extcol1", 30, "extcol2", "扩展字段值");
});
System.out.println(convert2.convertTo(table));
Assertions.assertEquals(
"{\"players\":[{\"cards\":[11,12,13,14,15],\"userid\":1,\"username\":\"玩家1\"},{\"cards\":[21,22,23,24,25],\"userid\":2,\"username\":\"玩家2\"},{\"userid\":3,\"username\":\"玩家3\"}],\"tableid\":100,\"extcol1\":30,\"extcol2\":\"扩展字段值\"}",
convert2.convertTo(table));
// {"players":[{"cards":[11,12,13,14,15],"userid":1,"username":"玩家1"},{"cards":[21,22,23,24,25],"userid":2,"username":"玩家2"},{"cards":[31,32,33,34,35],"userid":3,"username":"玩家3"}],"tableid":100}
// {"players":[{"cards":[11,12,13,14,15],"userid":1,"username":"玩家1"},{"cards":[21,22,23,24,25],"userid":2,"username":"玩家2"},{"userid":3,"username":"玩家3"}],"tableid":100,"extcol1":30,"extcol2":"扩展字段值"}
}
}

View File

@@ -1,286 +1,286 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import org.junit.jupiter.api.*;
import org.redkale.annotation.ConstructorParameters;
import org.redkale.convert.bson.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
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();
}
@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 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());
}
@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();
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();
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);
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);
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());
}
@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 {
@Id
private int userid;
private String chname = "";
@Transient
private boolean flag = true;
@Transient
private List<SimpleChildEntity> children;
@Transient
private SimpleEntity user;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getChname() {
return chname;
}
public void setChname(String chname) {
this.chname = chname;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public List<SimpleChildEntity> getChildren() {
return children;
}
public void setChildren(List<SimpleChildEntity> children) {
this.children = children;
}
public SimpleEntity getUser() {
return user;
}
public void setUser(SimpleEntity user) {
this.user = user;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class ConstructorArgsEntity {
private final int userid;
private String name;
private long createtime;
@ConstructorParameters({"userid", "name"})
public ConstructorArgsEntity(int userid, String name) {
this.userid = userid;
this.name = name;
}
public int getUserid() {
return userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import org.junit.jupiter.api.*;
import org.redkale.annotation.ConstructorParameters;
import org.redkale.convert.bson.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
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();
}
@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 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());
}
@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();
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();
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);
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);
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());
}
@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 {
@Id
private int userid;
private String chname = "";
@Transient
private boolean flag = true;
@Transient
private List<SimpleChildEntity> children;
@Transient
private SimpleEntity user;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getChname() {
return chname;
}
public void setChname(String chname) {
this.chname = chname;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public List<SimpleChildEntity> getChildren() {
return children;
}
public void setChildren(List<SimpleChildEntity> children) {
this.children = children;
}
public SimpleEntity getUser() {
return user;
}
public void setUser(SimpleEntity user) {
this.user = user;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class ConstructorArgsEntity {
private final int userid;
private String name;
private long createtime;
@ConstructorParameters({"userid", "name"})
public ConstructorArgsEntity(int userid, String name) {
this.userid = userid;
this.name = name;
}
public int getUserid() {
return userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}

View File

@@ -1,41 +1,41 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.junit.jupiter.api.*;
import org.redkale.convert.ConvertImpl;
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);
}
@ConvertImpl(OneImpl.class)
public static interface OneEntity {
public String getName();
}
public static class OneImpl implements OneEntity {
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.junit.jupiter.api.*;
import org.redkale.convert.ConvertImpl;
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);
}
@ConvertImpl(OneImpl.class)
public static interface OneEntity {
public String getName();
}
public static class OneImpl implements OneEntity {
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@@ -1,155 +1,155 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
/** @author redkale */
public class ConvertRecord {
private String aname;
private String desc = "";
private int id = (int) System.currentTimeMillis();
private int[] integers;
private long[] longs;
private List<String> strings;
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 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 String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int[] getIntegers() {
return integers;
}
public void setIntegers(int[] integers) {
this.integers = integers;
}
public long[] getLongs() {
return longs;
}
public void setLongs(long[] longs) {
this.longs = longs;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
public Map<String, Integer> getMap() {
return map;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
/** @author redkale */
public class ConvertRecord {
private String aname;
private String desc = "";
private int id = (int) System.currentTimeMillis();
private int[] integers;
private long[] longs;
private List<String> strings;
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 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 String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int[] getIntegers() {
return integers;
}
public void setIntegers(int[] integers) {
this.integers = integers;
}
public long[] getLongs() {
return longs;
}
public void setLongs(long[] longs) {
this.longs = longs;
}
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
public Map<String, Integer> getMap() {
return map;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
}

View File

@@ -1,51 +1,51 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
/** @author zhangjx */
public class Fortune implements Comparable<Fortune> {
@Id
private int id;
private String message = "";
public Fortune() {}
public Fortune(int id, String message) {
this.id = id;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public int compareTo(Fortune o) {
return message.compareTo(o.message);
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
/** @author zhangjx */
public class Fortune implements Comparable<Fortune> {
@Id
private int id;
private String message = "";
public Fortune() {}
public Fortune(int id, String message) {
this.id = id;
this.message = message;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public int compareTo(Fortune o) {
return message.compareTo(o.message);
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}

View File

@@ -1,106 +1,106 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.util.TypeToken;
/**
* 支持泛型的
*
* @author zhangjx
* @param <T>
* @param <K>
* @param <V>
*/
public class GenericEntity<T, K, V> {
private K name;
private List<? extends T> list;
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());
}
@Override
public String toString() {
return "{\"entry\":" + entry + ",\"list\":" + list + ",\"name\":\"" + name + "\"}";
}
public K getName() {
return name;
}
public void setName(K name) {
this.name = name;
}
public List<? extends T> getList() {
return list;
}
public void setList(List<? extends T> list) {
this.list = list;
}
public Entry<K, V> getEntry() {
return entry;
}
public void setEntry(Entry<K, V> entry) {
this.entry = entry;
}
public static class Entry<K, V> {
private K key;
private V value;
public Entry() {}
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.util.TypeToken;
/**
* 支持泛型的
*
* @author zhangjx
* @param <T>
* @param <K>
* @param <V>
*/
public class GenericEntity<T, K, V> {
private K name;
private List<? extends T> list;
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());
}
@Override
public String toString() {
return "{\"entry\":" + entry + ",\"list\":" + list + ",\"name\":\"" + name + "\"}";
}
public K getName() {
return name;
}
public void setName(K name) {
this.name = name;
}
public List<? extends T> getList() {
return list;
}
public void setList(List<? extends T> list) {
this.list = list;
}
public Entry<K, V> getEntry() {
return entry;
}
public void setEntry(Entry<K, V> entry) {
this.entry = entry;
}
public static class Entry<K, V> {
private K key;
private V value;
public Entry() {}
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}

View File

@@ -1,128 +1,128 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.convert.bson.*;
import org.redkale.convert.json.*;
import org.redkale.util.*;
/** @author zhangjx */
public class InnerCoderEntity {
private final String val;
private final int id;
private InnerCoderEntity(int id, String value) {
this.id = id;
this.val = value;
}
public static InnerCoderEntity create(int id, String value) {
return new InnerCoderEntity(id, value);
}
/**
* 该方法提供给Convert组件自动加载。 1) 方法名可以随意。 2) 方法必须是static 3方法的参数有且只能有一个 且必须是org.redkale.convert.ConvertFactory或子类。 —3.1)
* 参数类型为org.redkale.convert.ConvertFactory 表示适合JSON和BSON。 —3.2) 参数类型为org.redkale.convert.json.JsonFactory 表示仅适合JSON。
* —3.3) 参数类型为org.redkale.convert.bson.BsonFactory 表示仅适合BSON。
* 4方法的返回类型必须是org.redkale.convert.Decodeable/org.redkale.convert.Encodeable/org.redkale.convert.SimpledCoder
* 若返回类型不是org.redkale.convert.SimpledCoder, 就必须提供两个方法: 一个返回Decodeable 一个返回 Encodeable。
*
* @param factory
* @return
*/
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<Integer, DeMember> deMemberTagMap;
// 必须与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")
};
{
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 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 String getVal() {
return val;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public static void main(String[] args) throws Exception {
InnerCoderEntity record = InnerCoderEntity.create(200, "haha");
final JsonConvert convert = JsonConvert.root();
String json = convert.convertTo(record);
System.out.println(json);
System.out.println(convert.convertFrom(InnerCoderEntity.class, json).toString());
final BsonConvert convert2 = BsonFactory.root().getConvert();
byte[] bs = convert2.convertTo(InnerCoderEntity.class, null);
Utility.println("--", bs);
InnerCoderEntity r = convert2.convertFrom(InnerCoderEntity.class, bs);
System.out.println(r);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.convert.bson.*;
import org.redkale.convert.json.*;
import org.redkale.util.*;
/** @author zhangjx */
public class InnerCoderEntity {
private final String val;
private final int id;
private InnerCoderEntity(int id, String value) {
this.id = id;
this.val = value;
}
public static InnerCoderEntity create(int id, String value) {
return new InnerCoderEntity(id, value);
}
/**
* 该方法提供给Convert组件自动加载。 1) 方法名可以随意。 2) 方法必须是static 3方法的参数有且只能有一个 且必须是org.redkale.convert.ConvertFactory或子类。 —3.1)
* 参数类型为org.redkale.convert.ConvertFactory 表示适合JSON和BSON。 —3.2) 参数类型为org.redkale.convert.json.JsonFactory 表示仅适合JSON。
* —3.3) 参数类型为org.redkale.convert.bson.BsonFactory 表示仅适合BSON。
* 4方法的返回类型必须是org.redkale.convert.Decodeable/org.redkale.convert.Encodeable/org.redkale.convert.SimpledCoder
* 若返回类型不是org.redkale.convert.SimpledCoder, 就必须提供两个方法: 一个返回Decodeable 一个返回 Encodeable。
*
* @param factory
* @return
*/
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<Integer, DeMember> deMemberTagMap;
// 必须与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")
};
{
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 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 String getVal() {
return val;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public static void main(String[] args) throws Exception {
InnerCoderEntity record = InnerCoderEntity.create(200, "haha");
final JsonConvert convert = JsonConvert.root();
String json = convert.convertTo(record);
System.out.println(json);
System.out.println(convert.convertFrom(InnerCoderEntity.class, json).toString());
final BsonConvert convert2 = BsonFactory.root().getConvert();
byte[] bs = convert2.convertTo(InnerCoderEntity.class, null);
Utility.println("--", bs);
InnerCoderEntity r = convert2.convertFrom(InnerCoderEntity.class, bs);
System.out.println(r);
}
}

View File

@@ -1,149 +1,149 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Map;
import org.junit.jupiter.api.*;
import org.redkale.convert.Convert;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class JsonMainTest {
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();
}
@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 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 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());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.Map;
import org.junit.jupiter.api.*;
import org.redkale.convert.Convert;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class JsonMainTest {
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();
}
@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 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 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());
}
}

View File

@@ -1,210 +1,210 @@
/*
*
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.*;
import org.redkale.annotation.Comment;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.TypeToken;
/** @author zhangjx */
public class JsonPvBeanTest {
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"
+ "";
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("-----------------");
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 {
@Comment("页面名称")
public String pagename;
@Comment("页面类别")
public String cate;
@Comment("页面类别")
public String code;
@Comment("页面功能点")
public List<Functions> functions;
@Override
public String toString() {
return "{\"pagename\":\"" + pagename + "\",\"cate\":\"" + cate + "\",\"code\":\"" + code
+ "\",\"functions\":" + functions + "}";
}
public static class Functions {
@Comment("功能名称")
public String functionname;
@Comment("功能类型")
public String type;
@Override
public String toString() {
return "{\"functionname\":\"" + functionname + "\",\"type\":\"" + type + "\"}";
}
}
}
}
/*
*
*/
package org.redkale.test.convert;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.*;
import org.redkale.annotation.Comment;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.TypeToken;
/** @author zhangjx */
public class JsonPvBeanTest {
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"
+ "";
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("-----------------");
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 {
@Comment("页面名称")
public String pagename;
@Comment("页面类别")
public String cate;
@Comment("页面类别")
public String code;
@Comment("页面功能点")
public List<Functions> functions;
@Override
public String toString() {
return "{\"pagename\":\"" + pagename + "\",\"cate\":\"" + cate + "\",\"code\":\"" + code
+ "\",\"functions\":" + functions + "}";
}
public static class Functions {
@Comment("功能名称")
public String functionname;
@Comment("功能类型")
public String type;
@Override
public String toString() {
return "{\"functionname\":\"" + functionname + "\",\"type\":\"" + type + "\"}";
}
}
}
}

View File

@@ -1,87 +1,87 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.convert.json.*;
import org.redkale.util.ByteArray;
/** @author zhangjx */
public final class Message {
protected boolean flag;
private int[] ints;
private List<Long> longs;
@ConvertSmallString
private String message;
public Message() {}
public List<Long> getLongs() {
return longs;
}
public void setLongs(List<Long> longs) {
this.longs = longs;
}
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@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));
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.convert.json.*;
import org.redkale.util.ByteArray;
/** @author zhangjx */
public final class Message {
protected boolean flag;
private int[] ints;
private List<Long> longs;
@ConvertSmallString
private String message;
public Message() {}
public List<Long> getLongs() {
return longs;
}
public void setLongs(List<Long> longs) {
this.longs = longs;
}
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
public Message(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@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));
}
}

View File

@@ -1,85 +1,85 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.Arrays;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.Utility;
/** @author zhangjx */
public class One {
protected String key;
protected int code;
protected byte[] bytes = new byte[] {3, 4, 5};
protected int[] ints = new int[] {3000, 4000, 5000};
public One(int code) {
this.code = code;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
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 = "哈哈";
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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.Arrays;
import org.redkale.convert.json.JsonConvert;
import org.redkale.util.Utility;
/** @author zhangjx */
public class One {
protected String key;
protected int code;
protected byte[] bytes = new byte[] {3, 4, 5};
protected int[] ints = new int[] {3000, 4000, 5000};
public One(int code) {
this.code = code;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public int[] getInts() {
return ints;
}
public void setInts(int[] ints) {
this.ints = ints;
}
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 = "哈哈";
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);
}
}

View File

@@ -1,56 +1,56 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.net.*;
import java.util.*;
import org.redkale.convert.ConvertEntity;
/** @author zhangjx */
@ConvertEntity("myname")
public class SimpleChildEntity extends SimpleEntity {
private short st = -1234;
private String extend;
public static SimpleChildEntity create() {
SimpleChildEntity v = new SimpleChildEntity();
v.setName("this is name\n \"test");
v.setId(1000000001);
v.setAddrs(new int[] {22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999});
v.setStrings(new String[] {"zzz", "yyy", "xxx"});
List<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 void setSt(short st) {
this.st = st;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.net.*;
import java.util.*;
import org.redkale.convert.ConvertEntity;
/** @author zhangjx */
@ConvertEntity("myname")
public class SimpleChildEntity extends SimpleEntity {
private short st = -1234;
private String extend;
public static SimpleChildEntity create() {
SimpleChildEntity v = new SimpleChildEntity();
v.setName("this is name\n \"test");
v.setId(1000000001);
v.setAddrs(new int[] {22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999});
v.setStrings(new String[] {"zzz", "yyy", "xxx"});
List<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 void setSt(short st) {
this.st = st;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend;
}
}

View File

@@ -1,133 +1,133 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.net.*;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.util.Creator;
/** @author zhangjx */
public class SimpleEntity {
private String name;
private String desc = "";
private int id = (int) System.currentTimeMillis();
private int[] addrs;
private List<String> lists;
private String[] strings;
private Map<String, Integer> map;
private InetSocketAddress addr;
public static SimpleEntity create() {
SimpleEntity v = new SimpleEntity();
v.setName("this is name\n \"test");
v.setId(1000000001);
v.setAddrs(new int[] {22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999});
v.setStrings(new String[] {"zzz", "yyy", "xxx"});
List<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());
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public InetSocketAddress getAddr() {
return addr;
}
public void setAddr(InetSocketAddress addr) {
this.addr = addr;
}
public int[] getAddrs() {
return addrs;
}
public void setAddrs(int[] addrs) {
this.addrs = addrs;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, Integer> getMap() {
return map;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String[] getStrings() {
return strings;
}
public void setStrings(String[] strings) {
this.strings = strings;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.net.*;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.util.Creator;
/** @author zhangjx */
public class SimpleEntity {
private String name;
private String desc = "";
private int id = (int) System.currentTimeMillis();
private int[] addrs;
private List<String> lists;
private String[] strings;
private Map<String, Integer> map;
private InetSocketAddress addr;
public static SimpleEntity create() {
SimpleEntity v = new SimpleEntity();
v.setName("this is name\n \"test");
v.setId(1000000001);
v.setAddrs(new int[] {22222, 33333, 44444, 55555, 66666, 77777, 88888, 99999});
v.setStrings(new String[] {"zzz", "yyy", "xxx"});
List<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());
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public InetSocketAddress getAddr() {
return addr;
}
public void setAddr(InetSocketAddress addr) {
this.addr = addr;
}
public int[] getAddrs() {
return addrs;
}
public void setAddrs(int[] addrs) {
this.addrs = addrs;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Map<String, Integer> getMap() {
return map;
}
public void setMap(Map<String, Integer> map) {
this.map = map;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String[] getStrings() {
return strings;
}
public void setStrings(String[] strings) {
this.strings = strings;
}
}

View File

@@ -1,66 +1,66 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
/** @author zhangjx */
public class Two extends One {
public Two() {
super(90100119);
}
protected List<String> list;
protected Map<String, String> stringMap;
protected List<ConvertRecord> records;
protected Map<String, ConvertRecord> recordMap;
public Map<String, String> getStringMap() {
return stringMap;
}
public void setStringMap(Map<String, String> stringMap) {
this.stringMap = stringMap;
}
String ip;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public List<ConvertRecord> getRecords() {
return records;
}
public void setRecords(List<ConvertRecord> records) {
this.records = records;
}
public Map<String, ConvertRecord> getRecordMap() {
return recordMap;
}
public void setRecordMap(Map<String, ConvertRecord> recordMap) {
this.recordMap = recordMap;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.util.*;
/** @author zhangjx */
public class Two extends One {
public Two() {
super(90100119);
}
protected List<String> list;
protected Map<String, String> stringMap;
protected List<ConvertRecord> records;
protected Map<String, ConvertRecord> recordMap;
public Map<String, String> getStringMap() {
return stringMap;
}
public void setStringMap(Map<String, String> stringMap) {
this.stringMap = stringMap;
}
String ip;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public List<ConvertRecord> getRecords() {
return records;
}
public void setRecords(List<ConvertRecord> records) {
this.records = records;
}
public Map<String, ConvertRecord> getRecordMap() {
return recordMap;
}
public void setRecordMap(Map<String, ConvertRecord> recordMap) {
this.recordMap = recordMap;
}
}

View File

@@ -1,55 +1,55 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
/** @author zhangjx */
public class World implements Comparable<World> {
@Id
private int id;
private int randomNumber;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(int randomNumber) {
this.randomNumber = randomNumber;
}
@Override
public int compareTo(World o) {
return Integer.compare(id, o.id);
}
@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));
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
/** @author zhangjx */
public class World implements Comparable<World> {
@Id
private int id;
private int randomNumber;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(int randomNumber) {
this.randomNumber = randomNumber;
}
@Override
public int compareTo(World o) {
return Integer.compare(id, o.id);
}
@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));
}
}

View File

@@ -1,46 +1,46 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncFortuneJsonEncoder extends JsonDynEncoder<Fortune> {
protected final byte[] idFieldBytes = "\"id\":".getBytes();
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
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;
}
out.writeTo('{');
out.writeTo(idFieldBytes);
out.writeInt(value.getId());
String message = value.getMessage();
if (message != null) {
out.writeTo(messageCommaFieldBytes);
out.writeString(message);
}
out.writeTo('}');
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncFortuneJsonEncoder extends JsonDynEncoder<Fortune> {
protected final byte[] idFieldBytes = "\"id\":".getBytes();
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
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;
}
out.writeTo('{');
out.writeTo(idFieldBytes);
out.writeInt(value.getId());
String message = value.getMessage();
if (message != null) {
out.writeTo(messageCommaFieldBytes);
out.writeString(message);
}
out.writeTo('}');
}
}

View File

@@ -1,47 +1,47 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncMessageJsonEncoder extends JsonDynEncoder<Message> {
protected final byte[] messageFieldBytes = "\"message\":".getBytes();
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
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;
}
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('}');
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncMessageJsonEncoder extends JsonDynEncoder<Message> {
protected final byte[] messageFieldBytes = "\"message\":".getBytes();
protected final byte[] messageCommaFieldBytes = ",\"message\":".getBytes();
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;
}
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('}');
}
}

View File

@@ -1,44 +1,44 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncWorldJsonEncoder extends JsonDynEncoder<World> {
protected final byte[] idFieldBytes = "\"id\":".getBytes();
protected final byte[] randomNumberFieldBytes = ",\"randomNumber\":".getBytes();
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;
}
out.writeTo('{');
boolean comma = false;
out.writeTo(idFieldBytes);
out.writeInt(value.getId());
out.writeTo(randomNumberFieldBytes);
out.writeInt(value.getRandomNumber());
out.writeTo('}');
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert;
import java.lang.reflect.Type;
import org.redkale.convert.json.*;
/** @author zhangjx */
public class _DyncWorldJsonEncoder extends JsonDynEncoder<World> {
protected final byte[] idFieldBytes = "\"id\":".getBytes();
protected final byte[] randomNumberFieldBytes = ",\"randomNumber\":".getBytes();
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;
}
out.writeTo('{');
boolean comma = false;
out.writeTo(idFieldBytes);
out.writeInt(value.getId());
out.writeTo(randomNumberFieldBytes);
out.writeInt(value.getRandomNumber());
out.writeTo('}');
}
}

View File

@@ -1,114 +1,114 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
/** @author redkale */
public class Image implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public enum Size {
SMALL,
LARGE
}
private String uri;
private String title; // Can be null
private int width;
private int height;
private Size size;
public Image() {}
public Image(String uri, String title, int width, int height, Size size) {
this.height = height;
this.title = title;
this.uri = uri;
this.width = width;
this.size = size;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Image image = (Image) o;
if (height != image.height) return false;
if (width != image.width) return false;
if (size != image.size) return false;
if (title != null ? !title.equals(image.title) : image.title != null) return false;
return !(uri != null ? !uri.equals(image.uri) : image.uri != null);
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (size != null ? size.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Image ");
sb.append("uri=").append((uri));
sb.append(", title=").append((title));
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", size=").append(size);
sb.append("]");
return sb.toString();
}
public void setUri(String uri) {
this.uri = uri;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public void setSize(Size size) {
this.size = size;
}
public String getUri() {
return uri;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Size getSize() {
return size;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
/** @author redkale */
public class Image implements java.io.Serializable {
private static final long serialVersionUID = 1L;
public enum Size {
SMALL,
LARGE
}
private String uri;
private String title; // Can be null
private int width;
private int height;
private Size size;
public Image() {}
public Image(String uri, String title, int width, int height, Size size) {
this.height = height;
this.title = title;
this.uri = uri;
this.width = width;
this.size = size;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Image image = (Image) o;
if (height != image.height) return false;
if (width != image.width) return false;
if (size != image.size) return false;
if (title != null ? !title.equals(image.title) : image.title != null) return false;
return !(uri != null ? !uri.equals(image.uri) : image.uri != null);
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (size != null ? size.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Image ");
sb.append("uri=").append((uri));
sb.append(", title=").append((title));
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", size=").append(size);
sb.append("]");
return sb.toString();
}
public void setUri(String uri) {
this.uri = uri;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public void setSize(Size size) {
this.size = size;
}
public String getUri() {
return uri;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Size getSize() {
return size;
}
}

View File

@@ -1,210 +1,210 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
import java.util.*;
/** @author redkale */
public class Media implements java.io.Serializable {
public enum Player {
JAVA,
FLASH;
}
private String uri;
private String title; // Can be unset.
private int width;
private int height;
private String format;
private long duration;
private long size;
private int bitrate; // Can be unset.
private List<String> persons;
private Player player;
private String copyright; // Can be unset.
public Media() {}
public Media(
String uri,
String title,
int width,
int height,
String format,
long duration,
long size,
int bitrate,
boolean hasBitrate,
List<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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Media media = (Media) o;
if (bitrate != media.bitrate) return false;
if (duration != media.duration) return false;
if (height != media.height) return false;
if (size != media.size) return false;
if (width != media.width) return false;
if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false;
if (format != null ? !format.equals(media.format) : media.format != null) return false;
if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false;
if (player != media.player) return false;
if (title != null ? !title.equals(media.title) : media.title != null) return false;
if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false;
return true;
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (format != null ? format.hashCode() : 0);
result = 31 * result + (int) (duration ^ (duration >>> 32));
result = 31 * result + (int) (size ^ (size >>> 32));
result = 31 * result + bitrate;
result = 31 * result + (persons != null ? persons.hashCode() : 0);
result = 31 * result + (player != null ? player.hashCode() : 0);
result = 31 * result + (copyright != null ? copyright.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Media ");
sb.append("uri=").append((uri));
sb.append(", title=").append((title));
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", format=").append((format));
sb.append(", duration=").append(duration);
sb.append(", size=").append(size);
sb.append(", bitrate=").append(String.valueOf(bitrate));
sb.append(", persons=").append((persons));
sb.append(", player=").append(player);
sb.append(", copyright=").append((copyright));
sb.append("]");
return sb.toString();
}
public void setUri(String uri) {
this.uri = uri;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public void setFormat(String format) {
this.format = format;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void setSize(long size) {
this.size = size;
}
public void setBitrate(int bitrate) {
this.bitrate = bitrate;
}
public void setPersons(List<String> persons) {
this.persons = persons;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getUri() {
return uri;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String getFormat() {
return format;
}
public long getDuration() {
return duration;
}
public long getSize() {
return size;
}
public int getBitrate() {
return bitrate;
}
public List<String> getPersons() {
return persons;
}
public Player getPlayer() {
return player;
}
public String getCopyright() {
return copyright;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
import java.util.*;
/** @author redkale */
public class Media implements java.io.Serializable {
public enum Player {
JAVA,
FLASH;
}
private String uri;
private String title; // Can be unset.
private int width;
private int height;
private String format;
private long duration;
private long size;
private int bitrate; // Can be unset.
private List<String> persons;
private Player player;
private String copyright; // Can be unset.
public Media() {}
public Media(
String uri,
String title,
int width,
int height,
String format,
long duration,
long size,
int bitrate,
boolean hasBitrate,
List<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;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Media media = (Media) o;
if (bitrate != media.bitrate) return false;
if (duration != media.duration) return false;
if (height != media.height) return false;
if (size != media.size) return false;
if (width != media.width) return false;
if (copyright != null ? !copyright.equals(media.copyright) : media.copyright != null) return false;
if (format != null ? !format.equals(media.format) : media.format != null) return false;
if (persons != null ? !persons.equals(media.persons) : media.persons != null) return false;
if (player != media.player) return false;
if (title != null ? !title.equals(media.title) : media.title != null) return false;
if (uri != null ? !uri.equals(media.uri) : media.uri != null) return false;
return true;
}
@Override
public int hashCode() {
int result = uri != null ? uri.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + width;
result = 31 * result + height;
result = 31 * result + (format != null ? format.hashCode() : 0);
result = 31 * result + (int) (duration ^ (duration >>> 32));
result = 31 * result + (int) (size ^ (size >>> 32));
result = 31 * result + bitrate;
result = 31 * result + (persons != null ? persons.hashCode() : 0);
result = 31 * result + (player != null ? player.hashCode() : 0);
result = 31 * result + (copyright != null ? copyright.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[Media ");
sb.append("uri=").append((uri));
sb.append(", title=").append((title));
sb.append(", width=").append(width);
sb.append(", height=").append(height);
sb.append(", format=").append((format));
sb.append(", duration=").append(duration);
sb.append(", size=").append(size);
sb.append(", bitrate=").append(String.valueOf(bitrate));
sb.append(", persons=").append((persons));
sb.append(", player=").append(player);
sb.append(", copyright=").append((copyright));
sb.append("]");
return sb.toString();
}
public void setUri(String uri) {
this.uri = uri;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public void setFormat(String format) {
this.format = format;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void setSize(long size) {
this.size = size;
}
public void setBitrate(int bitrate) {
this.bitrate = bitrate;
}
public void setPersons(List<String> persons) {
this.persons = persons;
}
public void setPlayer(Player player) {
this.player = player;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getUri() {
return uri;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public String getFormat() {
return format;
}
public long getDuration() {
return duration;
}
public long getSize() {
return size;
}
public int getBitrate() {
return bitrate;
}
public List<String> getPersons() {
return persons;
}
public Player getPlayer() {
return player;
}
public String getCopyright() {
return copyright;
}
}

View File

@@ -1,105 +1,105 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.test.convert.*;
/** @author redkale */
public class MediaContent implements java.io.Serializable {
private Media media;
private List<Image> images;
public MediaContent() {}
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 MediaContent createDefault() {
String str = "{"
+ " media : {"
+ " uri : \"http://javaone.com/keynote.mpg\" ,"
+ " title : \"Javaone Keynote\" ,"
+ " width : -640 ,"
+ " height : -480 ,"
+ " format : \"video/mpg4\","
+ " duration : -18000000 ,"
+ " size : -58982400 ,"
+ " bitrate : -262144 ,"
+ " persons : [\"Bill Gates\", \"Steve Jobs\"] ,"
+ " player : JAVA , "
+ " copyright : None"
+ " }, images : ["
+ " {"
+ " uri : \"http://javaone.com/keynote_large.jpg\","
+ " title : \"Javaone Keynote\","
+ " width : -1024,"
+ " height : -768,"
+ " size : LARGE"
+ " }, {"
+ " uri : \"http://javaone.com/keynote_small.jpg\", "
+ " title : \"Javaone Keynote\" , "
+ " width : -320 , "
+ " height : -240 , "
+ " size : SMALL"
+ " }"
+ " ]"
+ "}";
return JsonFactory.root().getConvert().convertFrom(MediaContent.class, str);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MediaContent that = (MediaContent) o;
if (images != null ? !images.equals(that.images) : that.images != null) return false;
return !(media != null ? !media.equals(that.media) : that.media != null);
}
@Override
public int hashCode() {
int result = media != null ? media.hashCode() : 0;
result = 31 * result + (images != null ? images.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[MediaContent: ");
sb.append("media=").append(media);
sb.append(", images=").append(images);
sb.append("]");
return sb.toString();
}
public void setMedia(Media media) {
this.media = media;
}
public void setImages(List<Image> images) {
this.images = images;
}
public Media getMedia() {
return media;
}
public List<Image> getImages() {
return images;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.media;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.test.convert.*;
/** @author redkale */
public class MediaContent implements java.io.Serializable {
private Media media;
private List<Image> images;
public MediaContent() {}
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 MediaContent createDefault() {
String str = "{"
+ " media : {"
+ " uri : \"http://javaone.com/keynote.mpg\" ,"
+ " title : \"Javaone Keynote\" ,"
+ " width : -640 ,"
+ " height : -480 ,"
+ " format : \"video/mpg4\","
+ " duration : -18000000 ,"
+ " size : -58982400 ,"
+ " bitrate : -262144 ,"
+ " persons : [\"Bill Gates\", \"Steve Jobs\"] ,"
+ " player : JAVA , "
+ " copyright : None"
+ " }, images : ["
+ " {"
+ " uri : \"http://javaone.com/keynote_large.jpg\","
+ " title : \"Javaone Keynote\","
+ " width : -1024,"
+ " height : -768,"
+ " size : LARGE"
+ " }, {"
+ " uri : \"http://javaone.com/keynote_small.jpg\", "
+ " title : \"Javaone Keynote\" , "
+ " width : -320 , "
+ " height : -240 , "
+ " size : SMALL"
+ " }"
+ " ]"
+ "}";
return JsonFactory.root().getConvert().convertFrom(MediaContent.class, str);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MediaContent that = (MediaContent) o;
if (images != null ? !images.equals(that.images) : that.images != null) return false;
return !(media != null ? !media.equals(that.media) : that.media != null);
}
@Override
public int hashCode() {
int result = media != null ? media.hashCode() : 0;
result = 31 * result + (images != null ? images.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[MediaContent: ");
sb.append("media=").append(media);
sb.append(", images=").append(images);
sb.append("]");
return sb.toString();
}
public void setMedia(Media media) {
this.media = media;
}
public void setImages(List<Image> images) {
this.images = images;
}
public Media getMedia() {
return media;
}
public List<Image> getImages() {
return images;
}
}

View File

@@ -1,56 +1,56 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.proto;
import java.util.*;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.util.Utility;
/** @author zhangjx */
public class ArrayBean {
public static class IntArrayBean {
public int[] values1;
}
public static class IntListBean {
public List<Integer> values2;
}
public static class IntegerArrayBean {
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));
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.convert.proto;
import java.util.*;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.util.Utility;
/** @author zhangjx */
public class ArrayBean {
public static class IntArrayBean {
public int[] values1;
}
public static class IntListBean {
public List<Integer> values2;
}
public static class IntegerArrayBean {
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));
}
}

View File

@@ -1,238 +1,238 @@
/*
*/
package org.redkale.test.convert.proto;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import java.util.Arrays;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.convert.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.convert.proto.ProtobufObjectDecoder;
import org.redkale.convert.proto.ProtobufObjectEncoder;
import org.redkale.convert.proto.ProtobufReader;
import org.redkale.util.*;
/** @author zhangjx */
@SuppressWarnings("unchecked")
public class PBCustMessage2Test {
private boolean main;
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();
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();
}
public static interface BaseMessage {
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface MessageName {
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 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;
}
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};
}
@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 {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveMessage2() {}
public OnPlayerLeaveMessage2(int userid, String retinfo) {
this.userid = userid;
this.retinfo = retinfo;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class OnPlayerLeaveMessage {
@ConvertColumn(index = 1)
private String event = "onPlayerLeaveMessage";
@ConvertColumn(index = 2)
private OnPlayerLeaveContent result;
public OnPlayerLeaveMessage() {}
public OnPlayerLeaveMessage(int userid) {
this.result = new OnPlayerLeaveContent(userid);
}
public OnPlayerLeaveMessage(int userid, String retinfo) {
this.result = new OnPlayerLeaveContent(userid, retinfo);
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public OnPlayerLeaveContent getResult() {
return result;
}
public void setResult(OnPlayerLeaveContent result) {
this.result = result;
}
public static class OnPlayerLeaveContent {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveContent() {}
public OnPlayerLeaveContent(int userid) {
this.userid = userid;
}
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);
}
}
}
/*
*/
package org.redkale.test.convert.proto;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import java.util.Arrays;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.convert.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.convert.proto.ProtobufObjectDecoder;
import org.redkale.convert.proto.ProtobufObjectEncoder;
import org.redkale.convert.proto.ProtobufReader;
import org.redkale.util.*;
/** @author zhangjx */
@SuppressWarnings("unchecked")
public class PBCustMessage2Test {
private boolean main;
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();
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();
}
public static interface BaseMessage {
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface MessageName {
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 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;
}
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};
}
@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 {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveMessage2() {}
public OnPlayerLeaveMessage2(int userid, String retinfo) {
this.userid = userid;
this.retinfo = retinfo;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class OnPlayerLeaveMessage {
@ConvertColumn(index = 1)
private String event = "onPlayerLeaveMessage";
@ConvertColumn(index = 2)
private OnPlayerLeaveContent result;
public OnPlayerLeaveMessage() {}
public OnPlayerLeaveMessage(int userid) {
this.result = new OnPlayerLeaveContent(userid);
}
public OnPlayerLeaveMessage(int userid, String retinfo) {
this.result = new OnPlayerLeaveContent(userid, retinfo);
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public OnPlayerLeaveContent getResult() {
return result;
}
public void setResult(OnPlayerLeaveContent result) {
this.result = result;
}
public static class OnPlayerLeaveContent {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveContent() {}
public OnPlayerLeaveContent(int userid) {
this.userid = userid;
}
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);
}
}
}

View File

@@ -1,200 +1,200 @@
/*
*/
package org.redkale.test.convert.proto;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import java.util.*;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.convert.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.convert.proto.ProtobufFactory;
import org.redkale.convert.proto.ProtobufObjectDecoder;
import org.redkale.convert.proto.ProtobufObjectEncoder;
import org.redkale.convert.proto.ProtobufReader;
import org.redkale.util.*;
/** @author zhangjx */
public class PBCustMessageTest {
private boolean main;
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();
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();
}
public static interface BaseMessage {
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface MessageName {
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 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};
}
@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 {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveMessage2() {}
public OnPlayerLeaveMessage2(int userid, String retinfo) {
this.userid = userid;
this.retinfo = retinfo;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class OnPlayerLeaveMessage {
@ConvertColumn(index = 1)
private OnPlayerLeaveContent onPlayerLeaveMessage;
public OnPlayerLeaveMessage() {}
public OnPlayerLeaveMessage(int userid) {
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
}
public OnPlayerLeaveMessage(int userid, String retinfo) {
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
}
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
return onPlayerLeaveMessage;
}
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
}
public static class OnPlayerLeaveContent {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveContent() {}
public OnPlayerLeaveContent(int userid) {
this.userid = userid;
}
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);
}
}
}
/*
*/
package org.redkale.test.convert.proto;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.*;
import java.util.*;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.convert.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.convert.proto.ProtobufConvert;
import org.redkale.convert.proto.ProtobufFactory;
import org.redkale.convert.proto.ProtobufObjectDecoder;
import org.redkale.convert.proto.ProtobufObjectEncoder;
import org.redkale.convert.proto.ProtobufReader;
import org.redkale.util.*;
/** @author zhangjx */
public class PBCustMessageTest {
private boolean main;
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();
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();
}
public static interface BaseMessage {
@Inherited
@Documented
@Target({TYPE})
@Retention(RUNTIME)
public @interface MessageName {
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 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};
}
@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 {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveMessage2() {}
public OnPlayerLeaveMessage2(int userid, String retinfo) {
this.userid = userid;
this.retinfo = retinfo;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
public static class OnPlayerLeaveMessage {
@ConvertColumn(index = 1)
private OnPlayerLeaveContent onPlayerLeaveMessage;
public OnPlayerLeaveMessage() {}
public OnPlayerLeaveMessage(int userid) {
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid);
}
public OnPlayerLeaveMessage(int userid, String retinfo) {
this.onPlayerLeaveMessage = new OnPlayerLeaveContent(userid, retinfo);
}
public OnPlayerLeaveContent getOnPlayerLeaveMessage() {
return onPlayerLeaveMessage;
}
public void setOnPlayerLeaveMessage(OnPlayerLeaveContent onPlayerLeaveMessage) {
this.onPlayerLeaveMessage = onPlayerLeaveMessage;
}
public static class OnPlayerLeaveContent {
@ConvertColumn(index = 1)
public int userid;
@ConvertColumn(index = 2)
public String retinfo;
public OnPlayerLeaveContent() {}
public OnPlayerLeaveContent(int userid) {
this.userid = userid;
}
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);
}
}
}

View File

@@ -1,108 +1,108 @@
package org.redkale.test.convert.proto;
/// *
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
// package org.redkalex.test.protobuf;
//
// import java.util.Arrays;
// import org.redkale.convert.ConvertColumn;
// import org.redkale.convert.json.JsonConvert;
// import org.redkale.util.Utility;
// import org.redkalex.convert.protobuf.ProtobufConvert;
//
/// **
// *
// * @author zhangjx
// */
// public class SimpleBean {
//
// public static class PSimpleEntry {
//
// @ConvertColumn(index = 1)
// public int id = 66;
//
// @ConvertColumn(index = 2)
// public String name = "哈哈";
//
// @ConvertColumn(index = 3)
// public String email = "redkale@redkale.org";
// }
//
// public static class PTwoEntry {
//
// @ConvertColumn(index = 1)
// public int status = 2;
//
// @ConvertColumn(index = 2)
// public long createtime = System.currentTimeMillis();
//
// }
//
// @ConvertColumn(index = 1)
// public PSimpleEntry simple;
//
// @ConvertColumn(index = 2)
// public PTwoEntry two;
//
// @ConvertColumn(index = 3)
// public String strings = "abcd";
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// public static void main(String[] args) throws Throwable {
// //System.out.println(ProtobufConvert.root().getProtoDescriptor(SimpleBean.class));
// SimpleBean bean = new SimpleBean();
// bean.simple = new PSimpleEntry();
// bean.two = new PTwoEntry();
// bean.strings = "abcde";
//
// //-------------------------------
// byte[] jsonbs = JsonConvert.root().convertToBytes(bean);
// byte[] bs = ProtobufConvert.root().convertTo(bean);
// Utility.println("predkale ", bs);
// PSimpleBeanOuterClass.PSimpleBean.Builder builder = PSimpleBeanOuterClass.PSimpleBean.newBuilder();
//
// PSimpleBeanOuterClass.PSimpleBean bean2 = createPSimpleBean(bean, builder);
// byte[] bs2 = bean2.toByteArray();
// Utility.println("protobuf ", bs2);
// Thread.sleep(10);
// if (!Arrays.equals(bs, bs2)) throw new RuntimeException("两者序列化出来的byte[]不一致");
//
// System.out.println(bean);
// System.out.println(ProtobufConvert.root().convertFrom(SimpleBean.class, bs).toString());
// System.out.println(JsonConvert.root().convertFrom(SimpleBean.class, jsonbs).toString());
//
// }
//
// private static PSimpleBeanOuterClass.PSimpleBean createPSimpleBean(SimpleBean bean,
// PSimpleBeanOuterClass.PSimpleBean.Builder builder) {
// if (builder == null) {
// builder = PSimpleBeanOuterClass.PSimpleBean.newBuilder();
// } else {
// builder.clear();
// }
// PSimpleBeanOuterClass.PSimpleBean.PSimpleEntry.Builder sentry =
// PSimpleBeanOuterClass.PSimpleBean.PSimpleEntry.newBuilder();
// sentry.setId(bean.simple.id);
// sentry.setName(bean.simple.name);
// sentry.setEmail(bean.simple.email);
// builder.setSimple(sentry.build());
//
// PSimpleBeanOuterClass.PSimpleBean.PTwoEntry.Builder tentry =
// PSimpleBeanOuterClass.PSimpleBean.PTwoEntry.newBuilder();
// tentry.setStatus(bean.two.status);
// tentry.setCreatetime(bean.two.createtime);
// builder.setTwo(tentry.build());
//
// builder.setStrings(bean.strings);
//
// PSimpleBeanOuterClass.PSimpleBean bean2 = builder.build();
// return bean2;
// }
// }
package org.redkale.test.convert.proto;
/// *
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
// package org.redkalex.test.protobuf;
//
// import java.util.Arrays;
// import org.redkale.convert.ConvertColumn;
// import org.redkale.convert.json.JsonConvert;
// import org.redkale.util.Utility;
// import org.redkalex.convert.protobuf.ProtobufConvert;
//
/// **
// *
// * @author zhangjx
// */
// public class SimpleBean {
//
// public static class PSimpleEntry {
//
// @ConvertColumn(index = 1)
// public int id = 66;
//
// @ConvertColumn(index = 2)
// public String name = "哈哈";
//
// @ConvertColumn(index = 3)
// public String email = "redkale@redkale.org";
// }
//
// public static class PTwoEntry {
//
// @ConvertColumn(index = 1)
// public int status = 2;
//
// @ConvertColumn(index = 2)
// public long createtime = System.currentTimeMillis();
//
// }
//
// @ConvertColumn(index = 1)
// public PSimpleEntry simple;
//
// @ConvertColumn(index = 2)
// public PTwoEntry two;
//
// @ConvertColumn(index = 3)
// public String strings = "abcd";
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// public static void main(String[] args) throws Throwable {
// //System.out.println(ProtobufConvert.root().getProtoDescriptor(SimpleBean.class));
// SimpleBean bean = new SimpleBean();
// bean.simple = new PSimpleEntry();
// bean.two = new PTwoEntry();
// bean.strings = "abcde";
//
// //-------------------------------
// byte[] jsonbs = JsonConvert.root().convertToBytes(bean);
// byte[] bs = ProtobufConvert.root().convertTo(bean);
// Utility.println("predkale ", bs);
// PSimpleBeanOuterClass.PSimpleBean.Builder builder = PSimpleBeanOuterClass.PSimpleBean.newBuilder();
//
// PSimpleBeanOuterClass.PSimpleBean bean2 = createPSimpleBean(bean, builder);
// byte[] bs2 = bean2.toByteArray();
// Utility.println("protobuf ", bs2);
// Thread.sleep(10);
// if (!Arrays.equals(bs, bs2)) throw new RuntimeException("两者序列化出来的byte[]不一致");
//
// System.out.println(bean);
// System.out.println(ProtobufConvert.root().convertFrom(SimpleBean.class, bs).toString());
// System.out.println(JsonConvert.root().convertFrom(SimpleBean.class, jsonbs).toString());
//
// }
//
// private static PSimpleBeanOuterClass.PSimpleBean createPSimpleBean(SimpleBean bean,
// PSimpleBeanOuterClass.PSimpleBean.Builder builder) {
// if (builder == null) {
// builder = PSimpleBeanOuterClass.PSimpleBean.newBuilder();
// } else {
// builder.clear();
// }
// PSimpleBeanOuterClass.PSimpleBean.PSimpleEntry.Builder sentry =
// PSimpleBeanOuterClass.PSimpleBean.PSimpleEntry.newBuilder();
// sentry.setId(bean.simple.id);
// sentry.setName(bean.simple.name);
// sentry.setEmail(bean.simple.email);
// builder.setSimple(sentry.build());
//
// PSimpleBeanOuterClass.PSimpleBean.PTwoEntry.Builder tentry =
// PSimpleBeanOuterClass.PSimpleBean.PTwoEntry.newBuilder();
// tentry.setStatus(bean.two.status);
// tentry.setCreatetime(bean.two.createtime);
// builder.setTwo(tentry.build());
//
// builder.setStrings(bean.strings);
//
// PSimpleBeanOuterClass.PSimpleBean bean2 = builder.build();
// return bean2;
// }
// }

View File

@@ -1,244 +1,244 @@
package org.redkale.test.convert.proto;
/// *
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
// package org.redkalex.test.protobuf;
//
// import org.redkalex.convert.protobuf.ProtobufReader;
// import org.redkalex.convert.protobuf.ProtobufConvert;
// import com.google.protobuf.*;
// import java.util.*;
// import org.redkale.convert.ConvertColumn;
// import org.redkale.convert.json.JsonConvert;
// import org.redkale.service.RetResult;
// import org.redkale.util.*;
//
/// **
// *
// * @author zhangjx
// */
// public class TestBean {
//
// public static class PTestEntry {
//
// @ConvertColumn(index = 1)
// public boolean[] bools = new boolean[]{true, false, true};
//
// @ConvertColumn(index = 2)
// public byte[] bytes = new byte[]{1, 2, 3, 4};
//
// @ConvertColumn(index = 3)
// public char[] chars = new char[]{'A', 'B', 'C'};
//
// @ConvertColumn(index = 4)
// public short[] shorts = new short[]{10, 20, 30};
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
// }
//
// public static enum Kind {
// ONE,
// TWO,
// THREE
// }
//
// @ConvertColumn(index = 1)
// public boolean[] bools;
//
// @ConvertColumn(index = 2)
// public byte[] bytes;
//
// @ConvertColumn(index = 3)
// public char[] chars;
//
// @ConvertColumn(index = 4)
// public PTestEntry[] entrys;
//
// @ConvertColumn(index = 5)
// public int[] ints;
//
// @ConvertColumn(index = 6)
// public float[] floats;
//
// @ConvertColumn(index = 7)
// public long[] longs;
//
// @ConvertColumn(index = 8)
// public double[] doubles; //8
//
// @ConvertColumn(index = 9)
// public String[] strings; //9
//
// @ConvertColumn(index = 10)
// public int id = 0x7788; //10
//
// @ConvertColumn(index = 11)
// public String name; //11
//
// @ConvertColumn(index = 12)
// public String email; //12
//
// @ConvertColumn(index = 13)
// public Kind kind; //13
//
// @ConvertColumn(index = 14)
// public Map<String, Integer> map; //14
//
// @ConvertColumn(index = 15)
// public String end; //15
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// public static void main3(String[] args) throws Throwable {
// byte[] src = new byte[]{(byte) 0x82, (byte) 0x01, (byte) 0x84, (byte) 0x01, (byte) 0x86, (byte) 0x01};
// src = new byte[]{(byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x01};
// CodedInputStream input = CodedInputStream.newInstance(src);
// System.out.println("结果1 " + input.readSInt32());
// System.out.println("结果1 " + input.readSInt32());
// System.out.println("结果1 " + input.readSInt32());
// ProtobufReader reader = new ProtobufReader(src);
// System.out.println("结果2 " + reader.readInt());
// System.out.println("结果2 " + reader.readInt());
// System.out.println("结果2 " + reader.readInt());
// }
//
// private static java.lang.reflect.Type retstring = new TypeToken<RetResult<Map<String, String>>>() {
// }.getType();
//
// public static void main2(String[] args) throws Throwable {
// System.out.println(ProtobufConvert.root().getProtoDescriptor(retstring));
// }
//
// public static void main(String[] args) throws Throwable {
// System.setProperty("convert.protobuf.enumtostring", "false"); //禁用枚举按字符串类型出来
// //System.out.println(ProtobufConvert.root().getProtoDescriptor(TestBean.class));
// //System.out.println(Integer.toHexString(14<<3|2));
// TestBean bean = new TestBean();
//
// bean.bools = new boolean[]{true, false, true};
// bean.bytes = new byte[]{1, 2, 3, 4};
// bean.chars = new char[]{'A', 'B', 'C'};
// bean.ints = new int[]{100, 200, 300};
// bean.floats = new float[]{10.12f, 20.34f};
// bean.longs = new long[]{111, 222, 333};
// bean.doubles = new double[]{65.65, 78.78};
// bean.name = "redkale";
// bean.email = "redkale@qq.org";
// bean.kind = Kind.TWO;
// bean.strings = new String[]{"str1", "str2", "str3"};
// bean.entrys = new PTestEntry[]{new PTestEntry(), null, new PTestEntry()};
// bean.map = Utility.ofMap("aa", 0x55, "bb", 0x66);
// bean.end = "over";
//
// //-------------------------------
// byte[] jsonbs = JsonConvert.root().convertToBytes(bean);
// byte[] bs = ProtobufConvert.root().convertTo(bean);
// Utility.println("pconvert ", bs);
// PTestBeanOuterClass.PTestBean.Builder builder = PTestBeanOuterClass.PTestBean.newBuilder();
//
// PTestBeanOuterClass.PTestBean bean2 = createPTestBean(bean, builder);
// byte[] bs2 = bean2.toByteArray();
// Utility.println("protobuf ", bs2);
// Thread.sleep(10);
// if (!Arrays.equals(bs, bs2)) throw new RuntimeException("两者序列化出来的byte[]不一致");
//
// System.out.println(bean);
// String frombean = ProtobufConvert.root().convertFrom(TestBean.class, bs).toString();
// System.out.println(frombean);
// if (!bean.toString().equals(frombean)) throw new RuntimeException("ProtobufConvert反解析后的结果不正确");
// System.out.println(JsonConvert.root().convertFrom(TestBean.class, jsonbs).toString());
//
// int count = 100000;
// long s, e;
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// ProtobufConvert.root().convertTo(bean);
// }
// e = System.currentTimeMillis() - s;
// System.out.println("redkale-protobuf耗时-------" + e);
//
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// JsonConvert.root().convertToBytes(bean);
// }
// e = System.currentTimeMillis() - s;
// System.out.println("redkale-json文本耗时-------" + e);
//
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// createPTestBean(bean, builder).toByteArray();
// }
// e = System.currentTimeMillis() - s;
// System.out.println("原生编译protobuf耗时-------" + e);
// }
//
// private static PTestBeanOuterClass.PTestBean createPTestBean(TestBean bean, PTestBeanOuterClass.PTestBean.Builder
// builder) {
// if (builder == null) {
// builder = PTestBeanOuterClass.PTestBean.newBuilder();
// } else {
// builder.clear();
// }
// for (int i = 0; bean.bools != null && i < bean.bools.length; i++) {
// builder.addBools(bean.bools[i]);
// }
// if (bean.bytes != null) builder.addBytes(ByteString.copyFrom(bean.bytes));
// for (int i = 0; bean.chars != null && i < bean.chars.length; i++) {
// builder.addChars(bean.chars[i]);
// }
// for (int i = 0; bean.entrys != null && i < bean.entrys.length; i++) {
// PTestBeanOuterClass.PTestBean.PTestEntry.Builder entry =
// PTestBeanOuterClass.PTestBean.PTestEntry.newBuilder();
// if (bean.entrys[i] == null) {
// builder.addEntrys(entry.build());
// continue;
// }
// for (int j = 0; bean.entrys[i].bools != null && j < bean.entrys[i].bools.length; j++) {
// entry.addBools(bean.entrys[i].bools[j]);
// }
// if (bean.entrys[i].bytes != null) entry.addBytes(ByteString.copyFrom(bean.entrys[i].bytes));
// for (int j = 0; bean.entrys[i].chars != null && j < bean.entrys[i].chars.length; j++) {
// entry.addChars(bean.entrys[i].chars[j]);
// }
// for (int j = 0; bean.entrys[i].shorts != null && j < bean.entrys[i].shorts.length; j++) {
// entry.addShorts(bean.entrys[i].shorts[j]);
// }
// builder.addEntrys(entry.build());
// }
// for (int i = 0; bean.ints != null && i < bean.ints.length; i++) {
// builder.addInts(bean.ints[i]);
// }
// for (int i = 0; bean.floats != null && i < bean.floats.length; i++) {
// builder.addFloats(bean.floats[i]);
// }
// for (int i = 0; bean.longs != null && i < bean.longs.length; i++) {
// builder.addLongs(bean.longs[i]);
// }
// for (int i = 0; bean.doubles != null && i < bean.doubles.length; i++) {
// builder.addDoubles(bean.doubles[i]);
// }
// for (int i = 0; bean.strings != null && i < bean.strings.length; i++) {
// builder.addStrings(bean.strings[i]);
// }
// builder.setId(bean.id);
// if (bean.name != null) builder.setName(bean.name);
// if (bean.email != null) builder.setEmail(bean.email);
// if (bean.kind != null) builder.setKind(PTestBeanOuterClass.PTestBean.Kind.TWO);
// if (bean.map != null) builder.putAllMap(bean.map);
// if (bean.end != null) builder.setEnd(bean.end);
// PTestBeanOuterClass.PTestBean bean2 = builder.build();
// return bean2;
// }
// }
//
//// protoc --java_out=D:\Java-Projects\RedkalePluginsProject\test\
// --proto_path=D:\Java-Projects\RedkalePluginsProject\test\org\redkalex\test\protobuf\ PTestBean.proto
package org.redkale.test.convert.proto;
/// *
// * To change this license header, choose License Headers in Project Properties.
// * To change this template file, choose Tools | Templates
// * and open the template in the editor.
// */
// package org.redkalex.test.protobuf;
//
// import org.redkalex.convert.protobuf.ProtobufReader;
// import org.redkalex.convert.protobuf.ProtobufConvert;
// import com.google.protobuf.*;
// import java.util.*;
// import org.redkale.convert.ConvertColumn;
// import org.redkale.convert.json.JsonConvert;
// import org.redkale.service.RetResult;
// import org.redkale.util.*;
//
/// **
// *
// * @author zhangjx
// */
// public class TestBean {
//
// public static class PTestEntry {
//
// @ConvertColumn(index = 1)
// public boolean[] bools = new boolean[]{true, false, true};
//
// @ConvertColumn(index = 2)
// public byte[] bytes = new byte[]{1, 2, 3, 4};
//
// @ConvertColumn(index = 3)
// public char[] chars = new char[]{'A', 'B', 'C'};
//
// @ConvertColumn(index = 4)
// public short[] shorts = new short[]{10, 20, 30};
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
// }
//
// public static enum Kind {
// ONE,
// TWO,
// THREE
// }
//
// @ConvertColumn(index = 1)
// public boolean[] bools;
//
// @ConvertColumn(index = 2)
// public byte[] bytes;
//
// @ConvertColumn(index = 3)
// public char[] chars;
//
// @ConvertColumn(index = 4)
// public PTestEntry[] entrys;
//
// @ConvertColumn(index = 5)
// public int[] ints;
//
// @ConvertColumn(index = 6)
// public float[] floats;
//
// @ConvertColumn(index = 7)
// public long[] longs;
//
// @ConvertColumn(index = 8)
// public double[] doubles; //8
//
// @ConvertColumn(index = 9)
// public String[] strings; //9
//
// @ConvertColumn(index = 10)
// public int id = 0x7788; //10
//
// @ConvertColumn(index = 11)
// public String name; //11
//
// @ConvertColumn(index = 12)
// public String email; //12
//
// @ConvertColumn(index = 13)
// public Kind kind; //13
//
// @ConvertColumn(index = 14)
// public Map<String, Integer> map; //14
//
// @ConvertColumn(index = 15)
// public String end; //15
//
// @Override
// public String toString() {
// return JsonConvert.root().convertTo(this);
// }
//
// public static void main3(String[] args) throws Throwable {
// byte[] src = new byte[]{(byte) 0x82, (byte) 0x01, (byte) 0x84, (byte) 0x01, (byte) 0x86, (byte) 0x01};
// src = new byte[]{(byte) 0x01, (byte) 0x00, (byte) 0x01, (byte) 0x01};
// CodedInputStream input = CodedInputStream.newInstance(src);
// System.out.println("结果1 " + input.readSInt32());
// System.out.println("结果1 " + input.readSInt32());
// System.out.println("结果1 " + input.readSInt32());
// ProtobufReader reader = new ProtobufReader(src);
// System.out.println("结果2 " + reader.readInt());
// System.out.println("结果2 " + reader.readInt());
// System.out.println("结果2 " + reader.readInt());
// }
//
// private static java.lang.reflect.Type retstring = new TypeToken<RetResult<Map<String, String>>>() {
// }.getType();
//
// public static void main2(String[] args) throws Throwable {
// System.out.println(ProtobufConvert.root().getProtoDescriptor(retstring));
// }
//
// public static void main(String[] args) throws Throwable {
// System.setProperty("convert.protobuf.enumtostring", "false"); //禁用枚举按字符串类型出来
// //System.out.println(ProtobufConvert.root().getProtoDescriptor(TestBean.class));
// //System.out.println(Integer.toHexString(14<<3|2));
// TestBean bean = new TestBean();
//
// bean.bools = new boolean[]{true, false, true};
// bean.bytes = new byte[]{1, 2, 3, 4};
// bean.chars = new char[]{'A', 'B', 'C'};
// bean.ints = new int[]{100, 200, 300};
// bean.floats = new float[]{10.12f, 20.34f};
// bean.longs = new long[]{111, 222, 333};
// bean.doubles = new double[]{65.65, 78.78};
// bean.name = "redkale";
// bean.email = "redkale@qq.org";
// bean.kind = Kind.TWO;
// bean.strings = new String[]{"str1", "str2", "str3"};
// bean.entrys = new PTestEntry[]{new PTestEntry(), null, new PTestEntry()};
// bean.map = Utility.ofMap("aa", 0x55, "bb", 0x66);
// bean.end = "over";
//
// //-------------------------------
// byte[] jsonbs = JsonConvert.root().convertToBytes(bean);
// byte[] bs = ProtobufConvert.root().convertTo(bean);
// Utility.println("pconvert ", bs);
// PTestBeanOuterClass.PTestBean.Builder builder = PTestBeanOuterClass.PTestBean.newBuilder();
//
// PTestBeanOuterClass.PTestBean bean2 = createPTestBean(bean, builder);
// byte[] bs2 = bean2.toByteArray();
// Utility.println("protobuf ", bs2);
// Thread.sleep(10);
// if (!Arrays.equals(bs, bs2)) throw new RuntimeException("两者序列化出来的byte[]不一致");
//
// System.out.println(bean);
// String frombean = ProtobufConvert.root().convertFrom(TestBean.class, bs).toString();
// System.out.println(frombean);
// if (!bean.toString().equals(frombean)) throw new RuntimeException("ProtobufConvert反解析后的结果不正确");
// System.out.println(JsonConvert.root().convertFrom(TestBean.class, jsonbs).toString());
//
// int count = 100000;
// long s, e;
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// ProtobufConvert.root().convertTo(bean);
// }
// e = System.currentTimeMillis() - s;
// System.out.println("redkale-protobuf耗时-------" + e);
//
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// JsonConvert.root().convertToBytes(bean);
// }
// e = System.currentTimeMillis() - s;
// System.out.println("redkale-json文本耗时-------" + e);
//
// s = System.currentTimeMillis();
// for (int z = 0; z < count; z++) {
// createPTestBean(bean, builder).toByteArray();
// }
// e = System.currentTimeMillis() - s;
// System.out.println("原生编译protobuf耗时-------" + e);
// }
//
// private static PTestBeanOuterClass.PTestBean createPTestBean(TestBean bean, PTestBeanOuterClass.PTestBean.Builder
// builder) {
// if (builder == null) {
// builder = PTestBeanOuterClass.PTestBean.newBuilder();
// } else {
// builder.clear();
// }
// for (int i = 0; bean.bools != null && i < bean.bools.length; i++) {
// builder.addBools(bean.bools[i]);
// }
// if (bean.bytes != null) builder.addBytes(ByteString.copyFrom(bean.bytes));
// for (int i = 0; bean.chars != null && i < bean.chars.length; i++) {
// builder.addChars(bean.chars[i]);
// }
// for (int i = 0; bean.entrys != null && i < bean.entrys.length; i++) {
// PTestBeanOuterClass.PTestBean.PTestEntry.Builder entry =
// PTestBeanOuterClass.PTestBean.PTestEntry.newBuilder();
// if (bean.entrys[i] == null) {
// builder.addEntrys(entry.build());
// continue;
// }
// for (int j = 0; bean.entrys[i].bools != null && j < bean.entrys[i].bools.length; j++) {
// entry.addBools(bean.entrys[i].bools[j]);
// }
// if (bean.entrys[i].bytes != null) entry.addBytes(ByteString.copyFrom(bean.entrys[i].bytes));
// for (int j = 0; bean.entrys[i].chars != null && j < bean.entrys[i].chars.length; j++) {
// entry.addChars(bean.entrys[i].chars[j]);
// }
// for (int j = 0; bean.entrys[i].shorts != null && j < bean.entrys[i].shorts.length; j++) {
// entry.addShorts(bean.entrys[i].shorts[j]);
// }
// builder.addEntrys(entry.build());
// }
// for (int i = 0; bean.ints != null && i < bean.ints.length; i++) {
// builder.addInts(bean.ints[i]);
// }
// for (int i = 0; bean.floats != null && i < bean.floats.length; i++) {
// builder.addFloats(bean.floats[i]);
// }
// for (int i = 0; bean.longs != null && i < bean.longs.length; i++) {
// builder.addLongs(bean.longs[i]);
// }
// for (int i = 0; bean.doubles != null && i < bean.doubles.length; i++) {
// builder.addDoubles(bean.doubles[i]);
// }
// for (int i = 0; bean.strings != null && i < bean.strings.length; i++) {
// builder.addStrings(bean.strings[i]);
// }
// builder.setId(bean.id);
// if (bean.name != null) builder.setName(bean.name);
// if (bean.email != null) builder.setEmail(bean.email);
// if (bean.kind != null) builder.setKind(PTestBeanOuterClass.PTestBean.Kind.TWO);
// if (bean.map != null) builder.putAllMap(bean.map);
// if (bean.end != null) builder.setEnd(bean.end);
// PTestBeanOuterClass.PTestBean bean2 = builder.build();
// return bean2;
// }
// }
//
//// protoc --java_out=D:\Java-Projects\RedkalePluginsProject\test\
// --proto_path=D:\Java-Projects\RedkalePluginsProject\test\org\redkalex\test\protobuf\ PTestBean.proto

View File

@@ -1,345 +1,345 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.lang.reflect.Type;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.net.http.*;
import org.redkale.util.AnyValue;
/** @author zhangjx */
public interface HttpRequestDesc {
// 获取客户端地址IP
public SocketAddress getRemoteAddress();
// 获取客户端地址IP, 与getRemoteAddres() 的区别在于:
// 本方法优先取header中指定为RemoteAddress名的值没有则返回getRemoteAddres()的getHostAddress()。
// 本方法适用于服务前端有如nginx的代理服务器进行中转通过getRemoteAddres()是获取不到客户端的真实IP。
public String getRemoteAddr();
// 获取请求内容指定的编码字符串
public String getBody(Charset charset);
// 获取请求内容的UTF-8编码字符串
public String getBodyUTF8();
// 获取请求内容的byte[]
public byte[] getBody();
// 获取请求内容的JavaBean对象
public <T> T getBodyJson(java.lang.reflect.Type type);
// 获取请求内容的JavaBean对象
public <T> T getBodyJson(JsonConvert convert, java.lang.reflect.Type type);
// 获取文件上传对象
public MultiContext getMultiContext();
// 获取文件上传信息列表 等价于 getMultiContext().parts();
public Iterable<MultiPart> multiParts() throws IOException;
// 设置当前用户信息, 通常在HttpServlet.preExecute方法里设置currentUser
// 数据类型由@HttpUserType指定
public <T> HttpRequest setCurrentUser(T user);
// 获取当前用户信息 数据类型由@HttpUserType指定
public <T> T currentUser();
// 获取模块ID来自@HttpServlet.moduleid()
public int getModuleid();
// 获取操作ID来自@HttpMapping.actionid()
public int getActionid();
// 获取sessionid
public String getSessionid(boolean autoCreate);
// 更新sessionid
public String changeSessionid();
// 指定值更新sessionid
public String changeSessionid(String newsessionid);
// 使sessionid失效
public void invalidateSession();
// 获取所有Cookie对象
public java.net.HttpCookie[] getCookies();
// 获取Cookie值
public String getCookie(String name);
// 获取Cookie值 没有返回默认值
public String getCookie(String name, String defaultValue);
// 获取协议名 http、https、ws、wss等
public String getProtocol();
// 获取请求方法 GET、POST等
public String getMethod();
// 获取Content-Type的header值
public String getContentType();
// 获取请求内容的长度, 为-1表示内容长度不确定
public long getContentLength();
// 获取Connection的Header值
public String getConnection();
// 获取Host的Header值
public String getHost();
// 获取请求的URL
public String getRequestURI();
// 截取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(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 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最后的一个/后面的部分的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最后的一个/后面的部分的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);
// 获取请求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: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: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段的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段的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转换成Map
public Map<String, String> getHeadersToMap(Map<String, String> map);
// 获取所有的header名
public String[] getHeaderNames();
// 获取指定的header值
public String getHeader(String name);
// 获取指定的header值, 没有返回默认值
public String getHeader(String name, String defaultValue);
// 获取指定的header的json值
public <T> T getJsonHeader(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的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(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(int radix, String name, int defaultValue);
// 获取指定的header的long值, 没有返回默认long值
public long getLongHeader(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的double值, 没有返回默认double值
public double getDoubleHeader(String name, double defaultValue);
// 获取请求参数总对象
public AnyValue getParameters();
// 将请求参数转换成Map
public Map<String, String> getParametersToMap(Map<String, String> map);
// 将请求参数转换成String, 字符串格式为: bean1={}&amp;id=13&amp;name=xxx
// 不会返回null没有参数返回空字符串
public String getParametersToString();
// 将请求参数转换成String, 字符串格式为: prefix + bean1={}&amp;id=13&amp;name=xxx
// 拼接前缀, 如果无参数,返回的字符串不会含有拼接前缀
// 不会返回null没有参数返回空字符串
public String getParametersToString(String prefix);
// 获取所有参数名
public String[] getParameterNames();
// 获取指定的参数值
public String getParameter(String name);
// 获取指定的参数值, 没有返回默认值
public String getParameter(String name, String defaultValue);
// 获取指定的参数json值
public <T> T getJsonParameter(Type type, String name);
// 获取指定的参数json值
public <T> T getJsonParameter(JsonConvert convert, Type type, String name);
// 获取指定的参数boolean值, 没有返回默认boolean值
public boolean getBooleanParameter(String name, boolean 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, int defaultValue);
// 获取指定的参数int值, 没有返回默认int值
public int getIntParameter(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(int radix, String name, long defaultValue);
// 获取指定的参数float值, 没有返回默认float值
public float getFloatParameter(String name, float defaultValue);
// 获取指定的参数double值, 没有返回默认double值
public double getDoubleParameter(String name, double defaultValue);
// 获取翻页对象 同 getFlipper("flipper", false, 0);
public org.redkale.source.Flipper getFlipper();
// 获取翻页对象 同 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", 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上下文对象
public HttpContext getContext();
// 获取所有属性值, servlet执行完后会被清空
public Map<String, Object> getAttributes();
// 获取指定属性值, servlet执行完后会被清空
public <T> T getAttribute(String name);
// 删除指定属性
public void removeAttribute(String name);
// 设置属性值, servlet执行完后会被清空
public void setAttribute(String name, Object value);
// 获取request创建时间
public long getCreatetime();
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.lang.reflect.Type;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
import org.redkale.convert.json.*;
import org.redkale.net.http.*;
import org.redkale.util.AnyValue;
/** @author zhangjx */
public interface HttpRequestDesc {
// 获取客户端地址IP
public SocketAddress getRemoteAddress();
// 获取客户端地址IP, 与getRemoteAddres() 的区别在于:
// 本方法优先取header中指定为RemoteAddress名的值没有则返回getRemoteAddres()的getHostAddress()。
// 本方法适用于服务前端有如nginx的代理服务器进行中转通过getRemoteAddres()是获取不到客户端的真实IP。
public String getRemoteAddr();
// 获取请求内容指定的编码字符串
public String getBody(Charset charset);
// 获取请求内容的UTF-8编码字符串
public String getBodyUTF8();
// 获取请求内容的byte[]
public byte[] getBody();
// 获取请求内容的JavaBean对象
public <T> T getBodyJson(java.lang.reflect.Type type);
// 获取请求内容的JavaBean对象
public <T> T getBodyJson(JsonConvert convert, java.lang.reflect.Type type);
// 获取文件上传对象
public MultiContext getMultiContext();
// 获取文件上传信息列表 等价于 getMultiContext().parts();
public Iterable<MultiPart> multiParts() throws IOException;
// 设置当前用户信息, 通常在HttpServlet.preExecute方法里设置currentUser
// 数据类型由@HttpUserType指定
public <T> HttpRequest setCurrentUser(T user);
// 获取当前用户信息 数据类型由@HttpUserType指定
public <T> T currentUser();
// 获取模块ID来自@HttpServlet.moduleid()
public int getModuleid();
// 获取操作ID来自@HttpMapping.actionid()
public int getActionid();
// 获取sessionid
public String getSessionid(boolean autoCreate);
// 更新sessionid
public String changeSessionid();
// 指定值更新sessionid
public String changeSessionid(String newsessionid);
// 使sessionid失效
public void invalidateSession();
// 获取所有Cookie对象
public java.net.HttpCookie[] getCookies();
// 获取Cookie值
public String getCookie(String name);
// 获取Cookie值 没有返回默认值
public String getCookie(String name, String defaultValue);
// 获取协议名 http、https、ws、wss等
public String getProtocol();
// 获取请求方法 GET、POST等
public String getMethod();
// 获取Content-Type的header值
public String getContentType();
// 获取请求内容的长度, 为-1表示内容长度不确定
public long getContentLength();
// 获取Connection的Header值
public String getConnection();
// 获取Host的Header值
public String getHost();
// 获取请求的URL
public String getRequestURI();
// 截取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(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 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最后的一个/后面的部分的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最后的一个/后面的部分的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);
// 获取请求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: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: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段的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段的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转换成Map
public Map<String, String> getHeadersToMap(Map<String, String> map);
// 获取所有的header名
public String[] getHeaderNames();
// 获取指定的header值
public String getHeader(String name);
// 获取指定的header值, 没有返回默认值
public String getHeader(String name, String defaultValue);
// 获取指定的header的json值
public <T> T getJsonHeader(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的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(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(int radix, String name, int defaultValue);
// 获取指定的header的long值, 没有返回默认long值
public long getLongHeader(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的double值, 没有返回默认double值
public double getDoubleHeader(String name, double defaultValue);
// 获取请求参数总对象
public AnyValue getParameters();
// 将请求参数转换成Map
public Map<String, String> getParametersToMap(Map<String, String> map);
// 将请求参数转换成String, 字符串格式为: bean1={}&amp;id=13&amp;name=xxx
// 不会返回null没有参数返回空字符串
public String getParametersToString();
// 将请求参数转换成String, 字符串格式为: prefix + bean1={}&amp;id=13&amp;name=xxx
// 拼接前缀, 如果无参数,返回的字符串不会含有拼接前缀
// 不会返回null没有参数返回空字符串
public String getParametersToString(String prefix);
// 获取所有参数名
public String[] getParameterNames();
// 获取指定的参数值
public String getParameter(String name);
// 获取指定的参数值, 没有返回默认值
public String getParameter(String name, String defaultValue);
// 获取指定的参数json值
public <T> T getJsonParameter(Type type, String name);
// 获取指定的参数json值
public <T> T getJsonParameter(JsonConvert convert, Type type, String name);
// 获取指定的参数boolean值, 没有返回默认boolean值
public boolean getBooleanParameter(String name, boolean 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, int defaultValue);
// 获取指定的参数int值, 没有返回默认int值
public int getIntParameter(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(int radix, String name, long defaultValue);
// 获取指定的参数float值, 没有返回默认float值
public float getFloatParameter(String name, float defaultValue);
// 获取指定的参数double值, 没有返回默认double值
public double getDoubleParameter(String name, double defaultValue);
// 获取翻页对象 同 getFlipper("flipper", false, 0);
public org.redkale.source.Flipper getFlipper();
// 获取翻页对象 同 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", 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上下文对象
public HttpContext getContext();
// 获取所有属性值, servlet执行完后会被清空
public Map<String, Object> getAttributes();
// 获取指定属性值, servlet执行完后会被清空
public <T> T getAttribute(String name);
// 删除指定属性
public void removeAttribute(String name);
// 设置属性值, servlet执行完后会被清空
public void setAttribute(String name, Object value);
// 获取request创建时间
public long getCreatetime();
}

View File

@@ -1,171 +1,171 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.CompletionHandler;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.*;
import org.redkale.convert.Convert;
import org.redkale.convert.json.*;
import org.redkale.net.http.*;
/** @author zhangjx */
public interface HttpResponseDesc {
// 增加Cookie值
public HttpResponse addCookie(HttpCookie... cookies);
// 增加Cookie值
public HttpResponse addCookie(Collection<HttpCookie> cookies);
// 创建CompletionHandler实例将非字符串对象以JSON格式输出字符串以文本输出
public CompletionHandler createAsyncHandler();
// 传入的CompletionHandler子类必须是public且保证其子类可被继承且completed、failed可被重载且包含空参数的构造函数
public <H extends CompletionHandler> H createAsyncHandler(Class<H> handlerClass);
// 获取ByteBuffer生成器
public Supplier<ByteBuffer> getBufferSupplier();
// 设置状态码
public void setStatus(int status);
// 获取状态码
public int getStatus();
// 获取 ContentType
public String getContentType();
// 设置 ContentType
public HttpResponse setContentType(String contentType);
// 获取内容长度
public long getContentLength();
// 设置内容长度
public HttpResponse setContentLength(long contentLength);
// 设置Header值
public HttpResponse setHeader(String name, Object value);
// 添加Header值
public HttpResponse addHeader(String name, Object value);
// 添加Header值
public HttpResponse addHeader(Map<String, ?> map);
// 跳过header的输出
// 通常应用场景是调用者的输出内容里已经包含了HTTP的响应头信息因此需要调用此方法避免重复输出HTTP响应头信息。
public HttpResponse skipHeader();
// 异步输出指定内容
public <A> void sendBody(ByteBuffer buffer, 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连接
public void finish(boolean kill);
// 将对象以JSON格式输出
public void finishJson(Object obj);
// 将对象数组用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);
// 将对象数组用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(final JsonConvert convert, final Type type, final Object obj);
// 将对象以JSON格式输出
public void finishJson(final Object... objs);
// 将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);
// 将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 Type type, final CompletableFuture future);
// 将HttpResult的结果对象以JSON格式输出
public void finishJson(final HttpResult result);
// 将HttpResult的结果对象以JSON格式输出
public void finishJson(final JsonConvert convert, final HttpResult result);
// 将指定字符串以响应结果输出
public void finish(String obj);
// 以指定响应码附带内容输出, message 可以为null
public void finish(int status, String message);
// 将结果对象输出
public void finish(final Object obj);
// 将结果对象输出
public void finish(final Convert convert, final Object obj);
// 将结果对象输出
public void finish(final Convert convert, final Type type, final Object obj);
// 以304状态码输出
public void finish304();
// 以404状态码输出
public void finish404();
// 将指定byte[]按响应结果输出
public void finish(final byte[] bs);
// 将指定ByteBuffer按响应结果输出
public void finish(ByteBuffer buffer);
// 将指定ByteBuffer按响应结果输出
// kill 输出后是否强制关闭连接
public void finish(boolean kill, ByteBuffer buffer);
// 将指定ByteBuffer数组按响应结果输出
public void finish(ByteBuffer... buffers);
// 将指定ByteBuffer数组按响应结果输出
// kill 输出后是否强制关闭连接
public void finish(boolean kill, ByteBuffer... buffers);
// 将指定文件按响应结果输出
public void finish(File file) throws IOException;
// 将文件按指定文件名输出
public void finish(final String filename, File file) throws IOException;
// HttpResponse回收时回调的监听方法
public void recycleListener(BiConsumer<HttpRequest, HttpResponse> recycleListener);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.CompletionHandler;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.*;
import org.redkale.convert.Convert;
import org.redkale.convert.json.*;
import org.redkale.net.http.*;
/** @author zhangjx */
public interface HttpResponseDesc {
// 增加Cookie值
public HttpResponse addCookie(HttpCookie... cookies);
// 增加Cookie值
public HttpResponse addCookie(Collection<HttpCookie> cookies);
// 创建CompletionHandler实例将非字符串对象以JSON格式输出字符串以文本输出
public CompletionHandler createAsyncHandler();
// 传入的CompletionHandler子类必须是public且保证其子类可被继承且completed、failed可被重载且包含空参数的构造函数
public <H extends CompletionHandler> H createAsyncHandler(Class<H> handlerClass);
// 获取ByteBuffer生成器
public Supplier<ByteBuffer> getBufferSupplier();
// 设置状态码
public void setStatus(int status);
// 获取状态码
public int getStatus();
// 获取 ContentType
public String getContentType();
// 设置 ContentType
public HttpResponse setContentType(String contentType);
// 获取内容长度
public long getContentLength();
// 设置内容长度
public HttpResponse setContentLength(long contentLength);
// 设置Header值
public HttpResponse setHeader(String name, Object value);
// 添加Header值
public HttpResponse addHeader(String name, Object value);
// 添加Header值
public HttpResponse addHeader(Map<String, ?> map);
// 跳过header的输出
// 通常应用场景是调用者的输出内容里已经包含了HTTP的响应头信息因此需要调用此方法避免重复输出HTTP响应头信息。
public HttpResponse skipHeader();
// 异步输出指定内容
public <A> void sendBody(ByteBuffer buffer, 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连接
public void finish(boolean kill);
// 将对象以JSON格式输出
public void finishJson(Object obj);
// 将对象数组用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);
// 将对象数组用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(final JsonConvert convert, final Type type, final Object obj);
// 将对象以JSON格式输出
public void finishJson(final Object... objs);
// 将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);
// 将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 Type type, final CompletableFuture future);
// 将HttpResult的结果对象以JSON格式输出
public void finishJson(final HttpResult result);
// 将HttpResult的结果对象以JSON格式输出
public void finishJson(final JsonConvert convert, final HttpResult result);
// 将指定字符串以响应结果输出
public void finish(String obj);
// 以指定响应码附带内容输出, message 可以为null
public void finish(int status, String message);
// 将结果对象输出
public void finish(final Object obj);
// 将结果对象输出
public void finish(final Convert convert, final Object obj);
// 将结果对象输出
public void finish(final Convert convert, final Type type, final Object obj);
// 以304状态码输出
public void finish304();
// 以404状态码输出
public void finish404();
// 将指定byte[]按响应结果输出
public void finish(final byte[] bs);
// 将指定ByteBuffer按响应结果输出
public void finish(ByteBuffer buffer);
// 将指定ByteBuffer按响应结果输出
// kill 输出后是否强制关闭连接
public void finish(boolean kill, ByteBuffer buffer);
// 将指定ByteBuffer数组按响应结果输出
public void finish(ByteBuffer... buffers);
// 将指定ByteBuffer数组按响应结果输出
// kill 输出后是否强制关闭连接
public void finish(boolean kill, ByteBuffer... buffers);
// 将指定文件按响应结果输出
public void finish(File file) throws IOException;
// 将文件按指定文件名输出
public void finish(final String filename, File file) throws IOException;
// HttpResponse回收时回调的监听方法
public void recycleListener(BiConsumer<HttpRequest, HttpResponse> recycleListener);
}

View File

@@ -1,116 +1,116 @@
/*
*
*/
package org.redkale.test.http;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.boot.Application;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.http.HttpServer;
import org.redkale.net.http.WebClient;
import org.redkale.net.http.WebRequest;
import org.redkale.util.AnyValueWriter;
/** @author zhangjx */
public class HttpSimpleClientTest {
private static int port = 0;
private static Application application;
private static ResourceFactory factory;
private static HttpServer server;
private boolean main;
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();
}
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();
}
}
/*
*
*/
package org.redkale.test.http;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.boot.Application;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.http.HttpServer;
import org.redkale.net.http.WebClient;
import org.redkale.net.http.WebRequest;
import org.redkale.util.AnyValueWriter;
/** @author zhangjx */
public class HttpSimpleClientTest {
private static int port = 0;
private static Application application;
private static ResourceFactory factory;
private static HttpServer server;
private boolean main;
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();
}
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();
}
}

View File

@@ -1,20 +1,20 @@
/*
*
*/
package org.redkale.test.http;
import java.io.IOException;
import org.redkale.net.http.HttpMapping;
import org.redkale.net.http.HttpRequest;
import org.redkale.net.http.HttpResponse;
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"));
}
}
/*
*
*/
package org.redkale.test.http;
import java.io.IOException;
import org.redkale.net.http.HttpMapping;
import org.redkale.net.http.HttpRequest;
import org.redkale.net.http.HttpResponse;
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"));
}
}

View File

@@ -1,70 +1,70 @@
/*
*
*/
package org.redkale.test.http;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.mq.spi.WebRequestCoder;
import org.redkale.net.client.ClientRequest;
import org.redkale.net.http.WebRequest;
/** @author zhangjx */
public class RequestCoderTest {
private boolean main;
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 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());
}
}
/*
*
*/
package org.redkale.test.http;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.mq.spi.WebRequestCoder;
import org.redkale.net.client.ClientRequest;
import org.redkale.net.http.WebRequest;
/** @author zhangjx */
public class RequestCoderTest {
private boolean main;
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 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());
}
}

View File

@@ -1,34 +1,34 @@
/*
*
*/
package org.redkale.test.http;
import org.redkale.net.http.RestService;
import org.redkale.service.AbstractService;
import org.redkale.util.Utility;
/** @author zhangjx */
@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 sleep300() {
Utility.sleep(300);
return "ok300";
}
public String sleep400() {
Utility.sleep(400);
return "ok400";
}
public String sleep500() {
Utility.sleep(500);
return "ok500";
}
}
/*
*
*/
package org.redkale.test.http;
import org.redkale.net.http.RestService;
import org.redkale.service.AbstractService;
import org.redkale.util.Utility;
/** @author zhangjx */
@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 sleep300() {
Utility.sleep(300);
return "ok300";
}
public String sleep400() {
Utility.sleep(400);
return "ok400";
}
public String sleep500() {
Utility.sleep(500);
return "ok500";
}
}

View File

@@ -1,72 +1,72 @@
/*
*
*/
package org.redkale.test.http;
import java.io.*;
import java.net.*;
import org.junit.jupiter.api.*;
import org.redkale.boot.Application;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.http.*;
import org.redkale.net.sncp.Sncp;
import org.redkale.util.*;
/** @author zhangjx */
public class RestSleepTest {
private boolean main;
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());
// ------------------------ 初始化 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);
}
}
/*
*
*/
package org.redkale.test.http;
import java.io.*;
import java.net.*;
import org.junit.jupiter.api.*;
import org.redkale.boot.Application;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.http.*;
import org.redkale.net.sncp.Sncp;
import org.redkale.util.*;
/** @author zhangjx */
public class RestSleepTest {
private boolean main;
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());
// ------------------------ 初始化 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);
}
}

View File

@@ -1,36 +1,36 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.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));
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.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));
}
}

View File

@@ -1,43 +1,43 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.IOException;
import org.redkale.net.http.*;
/** @author zhangjx */
// @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);
}
}
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\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件1: <input type=\"file\" name=\"filepath1\"/><br/><br/>"
+ "描述: <input name=\"desc2\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件2: <input type=\"file\" name=\"filepath2\"/><br/><br/>"
+ "描述: <input name=\"desc3\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件3: <input type=\"file\" name=\"filepath3\"/><br/><br/>"
+ "描述: <input name=\"desc4\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.IOException;
import org.redkale.net.http.*;
/** @author zhangjx */
// @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);
}
}
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\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件1: <input type=\"file\" name=\"filepath1\"/><br/><br/>"
+ "描述: <input name=\"desc2\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件2: <input type=\"file\" name=\"filepath2\"/><br/><br/>"
+ "描述: <input name=\"desc3\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;文件3: <input type=\"file\" name=\"filepath3\"/><br/><br/>"
+ "描述: <input name=\"desc4\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/>"
+ "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<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);
}
}

View File

@@ -1,198 +1,198 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.redkale.convert.Convert;
import org.redkale.net.http.*;
/** @author zhangjx */
public interface WebSocketDesc<G, T> {
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> send(Object message);
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> sendMap(Object... messages);
// 给自身发送消息, 消息类型是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);
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> send(Convert convert, Object message);
// 给自身发送消息, 消息类型是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, 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, 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, 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, Stream<G> userids);
// 给所有人广播消息, 返回结果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 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 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(
WebSocketRange wsrange, Convert convert, final Object message, boolean last);
// 给指定userid的WebSocket节点发送操作
public CompletableFuture<Integer> sendAction(final WebSocketAction action, Serializable... userids);
// 广播操作, 给所有人发操作指令
public CompletableFuture<Integer> broadcastAction(final WebSocketAction action);
// 获取用户在线的SNCP节点地址列表不是分布式则返回元素数量为1且元素值为null的列表
public CompletableFuture<Collection<InetSocketAddress>> getRpcNodeAddresses(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(byte[] data);
// 发送PONG消息附带其他信息 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> sendPong(byte[] data);
// 强制关闭用户的所有WebSocket
public CompletableFuture<Integer> forceCloseWebSocket(Serializable userid);
// 更改本WebSocket的userid
public CompletableFuture<Void> changeUserid(final G newuserid);
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户多连接模式
/* protected */ Stream<WebSocket> getLocalWebSockets(G userid);
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户单连接模式
/* protected */ WebSocket findLocalWebSocket(G userid);
// 获取当前进程节点所有在线的WebSocket
/* protected */ Collection<WebSocket> getLocalWebSockets();
// 获取ByteBuffer资源池
/* protected */ Supplier<ByteBuffer> getByteBufferSupplier();
// 返回sessionid, null表示连接不合法或异常,默认实现是request.sessionid(true),通常需要重写该方法
/* protected */ CompletableFuture<String> onOpen(final HttpRequest request);
// 创建userid null表示异常 必须实现该方法
/* protected abstract */ CompletableFuture<G> createUserid();
// WebSocket.broadcastMessage时的过滤条件
/* protected */ boolean predicate(WebSocketRange wsrange);
// WebSokcet连接成功后的回调方法
public void onConnected();
// ping后的回调方法
public void onPing(byte[] bytes);
// pong后的回调方法
public void onPong(byte[] bytes);
// 接收到消息的回调方法
public void onMessage(T message, boolean last);
// 接收到文本消息的回调方法
public void onMessage(String message, boolean last);
// 接收到二进制消息的回调方法
public void onMessage(byte[] bytes, boolean last);
// 关闭的回调方法调用此方法时WebSocket已经被关闭
public void onClose(int code, String reason);
// 获取当前WebSocket下的属性
public T getAttribute(String name);
// 移出当前WebSocket下的属性
public T removeAttribute(String name);
// 给当前WebSocket下的增加属性
public void setAttribute(String name, Object value);
// 获取当前WebSocket所属的userid
public G getUserid();
// 获取当前WebSocket的会话ID 不会为null
public Serializable getSessionid();
// 获取客户端直接地址, 当WebSocket连接是由代理服务器转发的则该值固定为代理服务器的IP地址
public SocketAddress getRemoteAddress();
// 获取客户端真实地址 同 HttpRequest.getRemoteAddr()
public String getRemoteAddr();
// 获取WebSocket创建时间
public long getCreatetime();
// 获取最后一次发送消息的时间
public long getLastSendTime();
// 获取最后一次读取消息的时间
public long getLastReadTime();
// 获取最后一次ping的时间
public long getLastPingTime();
// 显式地关闭WebSocket
public void close();
// WebSocket是否已关闭
public boolean isClosed();
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.http;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Stream;
import org.redkale.convert.Convert;
import org.redkale.net.http.*;
/** @author zhangjx */
public interface WebSocketDesc<G, T> {
// 给自身发送消息, 消息类型是String或byte[]或可JavaBean对象 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> send(Object message);
// 给自身发送消息, 消息类型是key-value键值对 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> sendMap(Object... messages);
// 给自身发送消息, 消息类型是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);
// 给自身发送消息, 消息类型是JavaBean对象 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> send(Convert convert, Object message);
// 给自身发送消息, 消息类型是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, 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, 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, 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, Stream<G> userids);
// 给所有人广播消息, 返回结果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 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 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(
WebSocketRange wsrange, Convert convert, final Object message, boolean last);
// 给指定userid的WebSocket节点发送操作
public CompletableFuture<Integer> sendAction(final WebSocketAction action, Serializable... userids);
// 广播操作, 给所有人发操作指令
public CompletableFuture<Integer> broadcastAction(final WebSocketAction action);
// 获取用户在线的SNCP节点地址列表不是分布式则返回元素数量为1且元素值为null的列表
public CompletableFuture<Collection<InetSocketAddress>> getRpcNodeAddresses(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(byte[] data);
// 发送PONG消息附带其他信息 返回结果0表示成功非0表示错误码
public CompletableFuture<Integer> sendPong(byte[] data);
// 强制关闭用户的所有WebSocket
public CompletableFuture<Integer> forceCloseWebSocket(Serializable userid);
// 更改本WebSocket的userid
public CompletableFuture<Void> changeUserid(final G newuserid);
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户多连接模式
/* protected */ Stream<WebSocket> getLocalWebSockets(G userid);
// 获取指定userid的WebSocket数组, 没有返回null 此方法用于单用户单连接模式
/* protected */ WebSocket findLocalWebSocket(G userid);
// 获取当前进程节点所有在线的WebSocket
/* protected */ Collection<WebSocket> getLocalWebSockets();
// 获取ByteBuffer资源池
/* protected */ Supplier<ByteBuffer> getByteBufferSupplier();
// 返回sessionid, null表示连接不合法或异常,默认实现是request.sessionid(true),通常需要重写该方法
/* protected */ CompletableFuture<String> onOpen(final HttpRequest request);
// 创建userid null表示异常 必须实现该方法
/* protected abstract */ CompletableFuture<G> createUserid();
// WebSocket.broadcastMessage时的过滤条件
/* protected */ boolean predicate(WebSocketRange wsrange);
// WebSokcet连接成功后的回调方法
public void onConnected();
// ping后的回调方法
public void onPing(byte[] bytes);
// pong后的回调方法
public void onPong(byte[] bytes);
// 接收到消息的回调方法
public void onMessage(T message, boolean last);
// 接收到文本消息的回调方法
public void onMessage(String message, boolean last);
// 接收到二进制消息的回调方法
public void onMessage(byte[] bytes, boolean last);
// 关闭的回调方法调用此方法时WebSocket已经被关闭
public void onClose(int code, String reason);
// 获取当前WebSocket下的属性
public T getAttribute(String name);
// 移出当前WebSocket下的属性
public T removeAttribute(String name);
// 给当前WebSocket下的增加属性
public void setAttribute(String name, Object value);
// 获取当前WebSocket所属的userid
public G getUserid();
// 获取当前WebSocket的会话ID 不会为null
public Serializable getSessionid();
// 获取客户端直接地址, 当WebSocket连接是由代理服务器转发的则该值固定为代理服务器的IP地址
public SocketAddress getRemoteAddress();
// 获取客户端真实地址 同 HttpRequest.getRemoteAddr()
public String getRemoteAddr();
// 获取WebSocket创建时间
public long getCreatetime();
// 获取最后一次发送消息的时间
public long getLastSendTime();
// 获取最后一次读取消息的时间
public long getLastReadTime();
// 获取最后一次ping的时间
public long getLastPingTime();
// 显式地关闭WebSocket
public void close();
// WebSocket是否已关闭
public boolean isClosed();
}

View File

@@ -1,81 +1,81 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.inject;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.io.File;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import org.junit.jupiter.api.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceAnnotationLoader;
import org.redkale.inject.ResourceFactory;
/** @author zhangjx */
public class ResourceAnnotationTest {
private boolean main;
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());
}
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 Class<CustomConf> annotationType() {
return CustomConf.class;
}
}
public static class InjectBean {
@CustomConf(path = "conf/test.xml")
public File conf;
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
@Documented
@Target({FIELD})
@Retention(RUNTIME)
public static @interface CustomConf {
String path();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.inject;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.io.File;
import java.lang.annotation.*;
import java.lang.reflect.Field;
import org.junit.jupiter.api.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceAnnotationLoader;
import org.redkale.inject.ResourceFactory;
/** @author zhangjx */
public class ResourceAnnotationTest {
private boolean main;
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());
}
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 Class<CustomConf> annotationType() {
return CustomConf.class;
}
}
public static class InjectBean {
@CustomConf(path = "conf/test.xml")
public File conf;
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
@Documented
@Target({FIELD})
@Retention(RUNTIME)
public static @interface CustomConf {
String path();
}
}

View File

@@ -1,65 +1,65 @@
/*
*
*/
package org.redkale.test.inject;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.annotation.Resource;
import org.redkale.annotation.ResourceInjected;
import org.redkale.inject.ResourceFactory;
import org.redkale.service.Service;
/** @author zhangjx */
public class ResourceInjectedTest {
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());
}
public static class RoomService implements Service {
@Resource
private ResourceService resService;
public void test() {
resService.doing();
}
}
public static class ResourceService implements Service {
private static final AtomicInteger counter = new AtomicInteger();
@Resource(name = "res.id")
private int id;
@Resource(name = "res.name")
private String name;
@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);
}
}
}
/*
*
*/
package org.redkale.test.inject;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.redkale.annotation.Resource;
import org.redkale.annotation.ResourceInjected;
import org.redkale.inject.ResourceFactory;
import org.redkale.service.Service;
/** @author zhangjx */
public class ResourceInjectedTest {
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());
}
public static class RoomService implements Service {
@Resource
private ResourceService resService;
public void test() {
resService.doing();
}
}
public static class ResourceService implements Service {
private static final AtomicInteger counter = new AtomicInteger();
@Resource(name = "res.id")
private int id;
@Resource(name = "res.name")
private String name;
@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);
}
}
}

View File

@@ -1,181 +1,181 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template bigint, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.inject;
import java.math.BigInteger;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.redkale.annotation.*;
import org.redkale.inject.ResourceEvent;
import org.redkale.inject.ResourceFactory;
/** @author zhangjx */
public class ResourceTest {
private boolean main;
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");
factory.register(aservice); // 放进Resource池内默认的资源名name为""
factory.register(bservice); // 放进Resource池内默认的资源名name为""
factory.inject(aservice); // 给aservice注入id、bservicebigint没有资源所以为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("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);
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 = "${desc}", required = false)
private String desc;
@Resource
private AService aservice;
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());
}
}
@ConstructorParameters({"name"})
public BService(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public AService getAservice() {
return aservice;
}
public void setAservice(AService aservice) {
this.aservice = aservice;
}
@Override
public String toString() {
return "{name:\"" + name + "\", id: " + id + ", aserivce:" + aservice + "}";
}
}
class AService {
@Resource(name = "${id}")
private String id;
@Resource(name = "id") // property.开头的资源名允许String自动转换成primitive数值类型
private int intid;
@Resource(name = "bigint", required = false)
private BigInteger bigint;
@Resource(name = "seqid", required = false)
private int seqid;
@Resource
private BService bservice;
@Override
public String toString() {
return "{id:\"" + id + "\", intid: " + intid + ", bigint:" + bigint + ", bservice:"
+ (bservice == null ? null : ("{name:" + bservice.getName() + "}")) + "}";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIntid() {
return intid;
}
public void setIntid(int intid) {
this.intid = intid;
}
public int getSeqid() {
return seqid;
}
public void setSeqid(int seqid) {
this.seqid = seqid;
}
public BigInteger getBigint() {
return bigint;
}
public void setBigint(BigInteger bigint) {
this.bigint = bigint;
}
public void setBservice(BService bservice) {
this.bservice = bservice;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template bigint, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.inject;
import java.math.BigInteger;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.redkale.annotation.*;
import org.redkale.inject.ResourceEvent;
import org.redkale.inject.ResourceFactory;
/** @author zhangjx */
public class ResourceTest {
private boolean main;
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");
factory.register(aservice); // 放进Resource池内默认的资源名name为""
factory.register(bservice); // 放进Resource池内默认的资源名name为""
factory.inject(aservice); // 给aservice注入id、bservicebigint没有资源所以为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("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);
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 = "${desc}", required = false)
private String desc;
@Resource
private AService aservice;
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());
}
}
@ConstructorParameters({"name"})
public BService(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public AService getAservice() {
return aservice;
}
public void setAservice(AService aservice) {
this.aservice = aservice;
}
@Override
public String toString() {
return "{name:\"" + name + "\", id: " + id + ", aserivce:" + aservice + "}";
}
}
class AService {
@Resource(name = "${id}")
private String id;
@Resource(name = "id") // property.开头的资源名允许String自动转换成primitive数值类型
private int intid;
@Resource(name = "bigint", required = false)
private BigInteger bigint;
@Resource(name = "seqid", required = false)
private int seqid;
@Resource
private BService bservice;
@Override
public String toString() {
return "{id:\"" + id + "\", intid: " + intid + ", bigint:" + bigint + ", bservice:"
+ (bservice == null ? null : ("{name:" + bservice.getName() + "}")) + "}";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getIntid() {
return intid;
}
public void setIntid(int intid) {
this.intid = intid;
}
public int getSeqid() {
return seqid;
}
public void setSeqid(int seqid) {
this.seqid = seqid;
}
public BigInteger getBigint() {
return bigint;
}
public void setBigint(BigInteger bigint) {
this.bigint = bigint;
}
public void setBservice(BService bservice) {
this.bservice = bservice;
}
}

View File

@@ -1,39 +1,39 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.text.SimpleDateFormat;
import org.redkale.convert.*;
/**
* @author zhangjx
* @param <R> R
* @param <W> W
*/
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");
@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;
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.text.SimpleDateFormat;
import org.redkale.convert.*;
/**
* @author zhangjx
* @param <R> R
* @param <W> W
*/
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");
@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;
}
}
}

View File

@@ -1,23 +1,23 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
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 failed(Throwable exc, Object attachment) {
throw new UnsupportedOperationException(
"Not supported yet."); // To change body of generated methods, choose Tools | Templates.
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
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 failed(Throwable exc, Object attachment) {
throw new UnsupportedOperationException(
"Not supported yet."); // To change body of generated methods, choose Tools | Templates.
}
}

View File

@@ -1,68 +1,68 @@
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
import org.redkale.net.http.*;
import org.redkale.source.FilterBean;
public class HelloBean implements FilterBean {
private int helloid;
@RestHeader(name = "User-Agent")
private String useragent; // 从Http Header中获取浏览器信息
@RestCookie(name = "hello-cookie")
private String rescookie; // 从Cookie中获取名为hello-cookie的值
@RestAddress
private String clientaddr; // 客户端请求IP
@RestSessionid
private String sessionid; // 用户Sessionid, 未登录时为null
/** 以下省略getter setter方法 */
public int getHelloid() {
return helloid;
}
public void setHelloid(int helloid) {
this.helloid = helloid;
}
public String getUseragent() {
return useragent;
}
public void setUseragent(String useragent) {
this.useragent = useragent;
}
public String getRescookie() {
return rescookie;
}
public void setRescookie(String rescookie) {
this.rescookie = rescookie;
}
public String getClientaddr() {
return clientaddr;
}
public void setClientaddr(String clientaddr) {
this.clientaddr = clientaddr;
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
import org.redkale.net.http.*;
import org.redkale.source.FilterBean;
public class HelloBean implements FilterBean {
private int helloid;
@RestHeader(name = "User-Agent")
private String useragent; // 从Http Header中获取浏览器信息
@RestCookie(name = "hello-cookie")
private String rescookie; // 从Cookie中获取名为hello-cookie的值
@RestAddress
private String clientaddr; // 客户端请求IP
@RestSessionid
private String sessionid; // 用户Sessionid, 未登录时为null
/** 以下省略getter setter方法 */
public int getHelloid() {
return helloid;
}
public void setHelloid(int helloid) {
this.helloid = helloid;
}
public String getUseragent() {
return useragent;
}
public void setUseragent(String useragent) {
this.useragent = useragent;
}
public String getRescookie() {
return rescookie;
}
public void setRescookie(String rescookie) {
this.rescookie = rescookie;
}
public String getClientaddr() {
return clientaddr;
}
public void setClientaddr(String clientaddr) {
this.clientaddr = clientaddr;
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}

View File

@@ -1,151 +1,151 @@
package org.redkale.test.rest;
import java.util.Map;
import org.redkale.convert.json.JsonFactory;
import org.redkale.net.http.*;
import org.redkale.persistence.Id;
import org.redkale.persistence.VirtualEntity;
@VirtualEntity
public class HelloEntity {
@Id
private int helloid;
private String helloname;
private int creator;
private long updatetime;
private long createtime;
@RestHeader(name = "hello-res")
private String resname;
@RestBody
private String bodystr;
@RestBody
private byte[] bodys;
@RestUploadFile
private byte[] uploads;
@RestBody
private Map<String, String> bodymap;
@RestAddress
private String clientaddr;
@RestPath
private String uri;
public HelloEntity() {}
public HelloEntity(int id) {
this.helloid = id;
}
/** 以下省略getter setter方法 */
public int getHelloid() {
return helloid;
}
public void setHelloid(int helloid) {
this.helloid = helloid;
}
public String getHelloname() {
return helloname;
}
public void setHelloname(String helloname) {
this.helloname = helloname;
}
public long getUpdatetime() {
return updatetime;
}
public void setUpdatetime(long updatetime) {
this.updatetime = updatetime;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public int getCreator() {
return creator;
}
public void setCreator(int creator) {
this.creator = creator;
}
public String getClientaddr() {
return clientaddr;
}
public void setClientaddr(String clientaddr) {
this.clientaddr = clientaddr;
}
public String getResname() {
return resname;
}
public void setResname(String resname) {
this.resname = resname;
}
public String getBodystr() {
return bodystr;
}
public void setBodystr(String bodystr) {
this.bodystr = bodystr;
}
public byte[] getBodys() {
return bodys;
}
public void setBodys(byte[] bodys) {
this.bodys = bodys;
}
public Map<String, String> getBodymap() {
return bodymap;
}
public void setBodymap(Map<String, String> bodymap) {
this.bodymap = bodymap;
}
public byte[] getUploads() {
return uploads;
}
public void setUploads(byte[] uploads) {
this.uploads = uploads;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}
package org.redkale.test.rest;
import java.util.Map;
import org.redkale.convert.json.JsonFactory;
import org.redkale.net.http.*;
import org.redkale.persistence.Id;
import org.redkale.persistence.VirtualEntity;
@VirtualEntity
public class HelloEntity {
@Id
private int helloid;
private String helloname;
private int creator;
private long updatetime;
private long createtime;
@RestHeader(name = "hello-res")
private String resname;
@RestBody
private String bodystr;
@RestBody
private byte[] bodys;
@RestUploadFile
private byte[] uploads;
@RestBody
private Map<String, String> bodymap;
@RestAddress
private String clientaddr;
@RestPath
private String uri;
public HelloEntity() {}
public HelloEntity(int id) {
this.helloid = id;
}
/** 以下省略getter setter方法 */
public int getHelloid() {
return helloid;
}
public void setHelloid(int helloid) {
this.helloid = helloid;
}
public String getHelloname() {
return helloname;
}
public void setHelloname(String helloname) {
this.helloname = helloname;
}
public long getUpdatetime() {
return updatetime;
}
public void setUpdatetime(long updatetime) {
this.updatetime = updatetime;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public int getCreator() {
return creator;
}
public void setCreator(int creator) {
this.creator = creator;
}
public String getClientaddr() {
return clientaddr;
}
public void setClientaddr(String clientaddr) {
this.clientaddr = clientaddr;
}
public String getResname() {
return resname;
}
public void setResname(String resname) {
this.resname = resname;
}
public String getBodystr() {
return bodystr;
}
public void setBodystr(String bodystr) {
this.bodystr = bodystr;
}
public byte[] getBodys() {
return bodys;
}
public void setBodys(byte[] bodys) {
this.bodys = bodys;
}
public Map<String, String> getBodymap() {
return bodymap;
}
public void setBodymap(Map<String, String> bodymap) {
this.bodymap = bodymap;
}
public byte[] getUploads() {
return uploads;
}
public void setUploads(byte[] uploads) {
this.uploads = uploads;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}

View File

@@ -1,130 +1,130 @@
package org.redkale.test.rest;
import java.nio.channels.CompletionHandler;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.*;
import org.redkale.source.DataSource;
import org.redkale.source.Flipper;
import org.redkale.util.*;
/** 类说明: Flipper : Source组件中的翻页对象 UserInfo :当前用户类 HelloEntity: Hello模块的实体类 HelloBean: Hello模块实现FilterBean的过滤Bean类 */
@RestService(autoMapping = true)
public class HelloService implements Service {
private int nodeid;
@Resource
private DataSource source;
public HelloService() {}
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 HttpResult showHello(int id) {
return new HttpResult("a");
}
// 删除记录
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 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);
}
// 查询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 = "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 = "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 = "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);
}
}
package org.redkale.test.rest;
import java.nio.channels.CompletionHandler;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.*;
import org.redkale.source.DataSource;
import org.redkale.source.Flipper;
import org.redkale.util.*;
/** 类说明: Flipper : Source组件中的翻页对象 UserInfo :当前用户类 HelloEntity: Hello模块的实体类 HelloBean: Hello模块实现FilterBean的过滤Bean类 */
@RestService(autoMapping = true)
public class HelloService implements Service {
private int nodeid;
@Resource
private DataSource source;
public HelloService() {}
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 HttpResult showHello(int id) {
return new HttpResult("a");
}
// 删除记录
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 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);
}
// 查询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 = "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 = "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 = "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);
}
}

View File

@@ -1,59 +1,59 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.*;
import org.redkale.source.*;
import org.redkale.util.Sheet;
/** 类说明: Flipper : Source组件中的翻页对象 UserInfo :当前用户类 HelloEntity: Hello模块的实体类 HelloBean: Hello模块实现FilterBean的过滤Bean类 */
@RestService(name = "hello", moduleid = 0, autoMapping = true, repair = true, ignore = false, comment = "Hello服务模块")
public class HelloService2 implements Service {
@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 = "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);
}
// 查询列表
@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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.*;
import org.redkale.source.*;
import org.redkale.util.Sheet;
/** 类说明: Flipper : Source组件中的翻页对象 UserInfo :当前用户类 HelloEntity: Hello模块的实体类 HelloBean: Hello模块实现FilterBean的过滤Bean类 */
@RestService(name = "hello", moduleid = 0, autoMapping = true, repair = true, ignore = false, comment = "Hello服务模块")
public class HelloService2 implements Service {
@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 = "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);
}
// 查询列表
@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);
}
}

View File

@@ -1,43 +1,43 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
/**
* LoginBean
*
* @author zhangjx
*/
public class LoginBean {
//账号
private String account = "";
//密码
private String password = "";
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
/**
* LoginBean
*
* @author zhangjx
*/
public class LoginBean {
// 账号
private String account = "";
// 密码
private String password = "";
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}

View File

@@ -1,157 +1,157 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.lang.reflect.*;
import java.util.*;
import org.redkale.service.*;
/** @author zhangjx */
public abstract class RetCodes {
protected static final Map<Integer, String> rets = new HashMap<>();
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());
}
}
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, "未知错误");
}
// 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_FILETOOBIG = 30010003;
@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_LOGIN_FAIL = 30020002;
@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_FREEZED = 30020005;
@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_STATUS_ILLEGAL = 30020008;
@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_USERNAME_ILLEGAL = 30020011;
@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_MOBILE_ILLEGAL = 30020014;
@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_EMAIL_ILLEGAL = 30020017;
@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_EXISTS = 30020020;
@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_EXISTS = 30020023;
@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("验证码无效")
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_CAPTCHA_ILLEGAL = 30020028; // 图片验证码
@RetLabel("用户类型无效")
public static final int RET_USER_TYPE_ILLEGAL = 30020029;
@RetLabel("用户设备ID无效")
public static final int RET_USER_APPTOKEN_ILLEGAL = 30020030;
static {
load(RetCodes.class);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.lang.reflect.*;
import java.util.*;
import org.redkale.service.*;
/** @author zhangjx */
public abstract class RetCodes {
protected static final Map<Integer, String> rets = new HashMap<>();
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());
}
}
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, "未知错误");
}
// 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_FILETOOBIG = 30010003;
@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_LOGIN_FAIL = 30020002;
@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_FREEZED = 30020005;
@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_STATUS_ILLEGAL = 30020008;
@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_USERNAME_ILLEGAL = 30020011;
@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_MOBILE_ILLEGAL = 30020014;
@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_EMAIL_ILLEGAL = 30020017;
@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_EXISTS = 30020020;
@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_EXISTS = 30020023;
@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("验证码无效")
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_CAPTCHA_ILLEGAL = 30020028; // 图片验证码
@RetLabel("用户类型无效")
public static final int RET_USER_TYPE_ILLEGAL = 30020029;
@RetLabel("用户设备ID无效")
public static final int RET_USER_APPTOKEN_ILLEGAL = 30020030;
static {
load(RetCodes.class);
}
}

View File

@@ -1,37 +1,37 @@
package org.redkale.test.rest;
import java.io.IOException;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
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_AUTHILLEGAL = RetCodes.retResult(RetCodes.RET_USER_AUTH_ILLEGAL);
@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 authenticate(HttpRequest request, HttpResponse response) throws IOException {
int userid = request.currentUserid(int.class);
if (userid < 1) {
response.finishJson(RET_UNLOGIN);
return;
}
response.nextEvent();
}
}
package org.redkale.test.rest;
import java.io.IOException;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
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_AUTHILLEGAL = RetCodes.retResult(RetCodes.RET_USER_AUTH_ILLEGAL);
@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 authenticate(HttpRequest request, HttpResponse response) throws IOException {
int userid = request.currentUserid(int.class);
if (userid < 1) {
response.finishJson(RET_UNLOGIN);
return;
}
response.nextEvent();
}
}

View File

@@ -1,44 +1,44 @@
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
import org.redkale.persistence.Id;
/**
* 当前用户对象
*
* @author zhangjx
*/
public class UserInfo {
@Id
private int userid;
private String username = "";
public int getUserid() {
return userid;
}
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 String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}
package org.redkale.test.rest;
import org.redkale.convert.json.JsonFactory;
import org.redkale.persistence.Id;
/**
* 当前用户对象
*
* @author zhangjx
*/
public class UserInfo {
@Id
private int userid;
private String username = "";
public int getUserid() {
return userid;
}
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 String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return JsonFactory.root().getConvert().convertTo(this);
}
}

View File

@@ -1,30 +1,30 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.service.*;
/**
* 简单的定义UserService接口
*
* @author zhangjx
*/
public class UserService implements Service {
/**
* 根据登录态获取当前用户信息
*
* @param sessionid
* @return
*/
public UserInfo current(String sessionid) {
return new UserInfo();
}
public RetResult<UserInfo> login(LoginBean bean) {
return new RetResult<>(new UserInfo());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import org.redkale.service.*;
/**
* 简单的定义UserService接口
*
* @author zhangjx
*/
public class UserService implements Service {
/**
* 根据登录态获取当前用户信息
*
* @param sessionid
* @return
*/
public UserInfo current(String sessionid) {
return new UserInfo();
}
public RetResult<UserInfo> login(LoginBean bean) {
return new RetResult<>(new UserInfo());
}
}

View File

@@ -1,177 +1,177 @@
package org.redkale.test.rest;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.source.Flipper;
import org.redkale.util.*;
@WebServlet(
value = {"/hello/*"},
repair = true)
public class _DynHelloRestServlet1 extends SimpleRestServlet {
@Resource
private HelloService _redkale_service;
@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();
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);
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/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/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/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/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/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/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/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);
}
}
package org.redkale.test.rest;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.source.Flipper;
import org.redkale.util.*;
@WebServlet(
value = {"/hello/*"},
repair = true)
public class _DynHelloRestServlet1 extends SimpleRestServlet {
@Resource
private HelloService _redkale_service;
@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();
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);
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/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/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/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/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/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/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/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);
}
}

View File

@@ -1,96 +1,96 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.io.IOException;
import java.util.Map;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.source.Flipper;
import org.redkale.util.*;
/** @author zhangjx */
@WebServlet(
value = {"/hello/*"},
repair = true)
public class _DynHelloRestServlet2 extends SimpleRestServlet {
@Resource
private HelloService2 _redkale_service;
@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/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/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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.rest;
import java.io.IOException;
import java.util.Map;
import org.redkale.annotation.Resource;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.source.Flipper;
import org.redkale.util.*;
/** @author zhangjx */
@WebServlet(
value = {"/hello/*"},
repair = true)
public class _DynHelloRestServlet2 extends SimpleRestServlet {
@Resource
private HelloService2 _redkale_service;
@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/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/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);
}
}

View File

@@ -1,28 +1,28 @@
/*
*
*/
package org.redkale.test.schedule;
import org.redkale.schedule.Scheduled;
import org.redkale.service.Service;
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 String task2() {
System.out.println(Times.nowMillis() + "每秒*****执行task2");
return "";
}
@Scheduled(cron = "0/1 * * * * ?")
private void task3() {
System.out.println(Times.nowMillis() + "每秒执行task3");
}
}
/*
*
*/
package org.redkale.test.schedule;
import org.redkale.schedule.Scheduled;
import org.redkale.service.Service;
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 String task2() {
System.out.println(Times.nowMillis() + "每秒*****执行task2");
return "";
}
@Scheduled(cron = "0/1 * * * * ?")
private void task3() {
System.out.println(Times.nowMillis() + "每秒执行task3");
}
}

View File

@@ -1,28 +1,28 @@
/*
*
*/
package org.redkale.test.schedule;
import org.junit.jupiter.api.Test;
import org.redkale.schedule.spi.ScheduleManagerService;
import org.redkale.util.Utility;
/** @author zhangjx */
public class SchedulingTest {
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);
}
}
/*
*
*/
package org.redkale.test.schedule;
import org.junit.jupiter.api.Test;
import org.redkale.schedule.spi.ScheduleManagerService;
import org.redkale.util.Utility;
/** @author zhangjx */
public class SchedulingTest {
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);
}
}

View File

@@ -1,249 +1,249 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.logging.Level;
import org.redkale.annotation.Resource;
import org.redkale.boot.*;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.http.*;
import org.redkale.net.sncp.*;
import org.redkale.service.Service;
import org.redkale.util.*;
/** @author zhangjx */
@RestService(name = "abmain")
public class ABMainService implements Service {
private static final int abport = 8866;
@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));
// ------------------------ 初始化 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();
// ------------------------ 初始化 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);
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("开始请求");
// 不声明一个新的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/abc2/张先生";
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
.join());
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();
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());
HttpServer server = new HttpServer();
server.getResourceFactory().register(application);
server.getLogger().setLevel(Level.WARNING);
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
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));
// 异步方法
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));
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 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 = "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;
}
@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 int id2() {
return 2;
}
},
name);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.logging.Level;
import org.redkale.annotation.Resource;
import org.redkale.boot.*;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.http.*;
import org.redkale.net.sncp.*;
import org.redkale.service.Service;
import org.redkale.util.*;
/** @author zhangjx */
@RestService(name = "abmain")
public class ABMainService implements Service {
private static final int abport = 8866;
@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));
// ------------------------ 初始化 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();
// ------------------------ 初始化 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);
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("开始请求");
// 不声明一个新的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/abc2/张先生";
System.out.println(Utility.postHttpContentAsync(httpClient, url, StandardCharsets.UTF_8, null)
.join());
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();
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());
HttpServer server = new HttpServer();
server.getResourceFactory().register(application);
server.getLogger().setLevel(Level.WARNING);
server.addRestServlet(null, service, null, HttpServlet.class, "/pipes");
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));
// 异步方法
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));
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 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 = "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;
}
@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 int id2() {
return 2;
}
},
name);
}
}

View File

@@ -1,85 +1,85 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
import org.redkale.annotation.Resource;
import org.redkale.service.*;
import org.redkale.util.Utility;
/** @author zhangjx */
public class BCService implements Service {
@Resource
private CService cService;
@Resource(name = "@name")
private String serviceName;
@Resource(name = "@type")
private Class serviceType;
public String serviceName() {
return serviceName;
}
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 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;
}
@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 int id2() {
return 2;
}
},
name);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
import org.redkale.annotation.Resource;
import org.redkale.service.*;
import org.redkale.util.Utility;
/** @author zhangjx */
public class BCService implements Service {
@Resource
private CService cService;
@Resource(name = "@name")
private String serviceName;
@Resource(name = "@type")
private Class serviceType;
public String serviceName() {
return serviceName;
}
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 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;
}
@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 int id2() {
return 2;
}
},
name);
}
}

View File

@@ -1,47 +1,47 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
import org.redkale.annotation.Resource;
import org.redkale.service.*;
import org.redkale.util.Times;
/** @author zhangjx */
public class CService implements Service {
@Resource(name = "@name")
private String serviceName;
@Resource(name = "@type")
private Class serviceType;
public String serviceName() {
return serviceName;
}
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 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);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
import org.redkale.annotation.Resource;
import org.redkale.service.*;
import org.redkale.util.Times;
/** @author zhangjx */
public class CService implements Service {
@Resource(name = "@name")
private String serviceName;
@Resource(name = "@type")
private Class serviceType;
public String serviceName() {
return serviceName;
}
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 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);
}
}

View File

@@ -1,16 +1,16 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
/**
* @author zhangjx
* @param <V> V
* @param <A> A
*/
public abstract class MyAsyncHandler<V, A> extends MyAsyncInnerHandler<V, A> {
public abstract int id();
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
/**
* @author zhangjx
* @param <V> V
* @param <A> A
*/
public abstract class MyAsyncHandler<V, A> extends MyAsyncInnerHandler<V, A> {
public abstract int id();
}

View File

@@ -1,14 +1,14 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
/** @author zhangjx */
public abstract class MyAsyncInnerHandler<V, A> implements CompletionHandler<V, A> {
protected abstract int id2();
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.CompletionHandler;
/** @author zhangjx */
public abstract class MyAsyncInnerHandler<V, A> implements CompletionHandler<V, A> {
protected abstract int id2();
}

View File

@@ -1,31 +1,31 @@
package org.redkale.test.service;
import java.io.Serializable;
public class Person implements Serializable {
private byte[] b = new byte[1024 * 2];
private String name;
@Override
public String toString() {
return "{name=" + name + ", b =" + (b == null ? "null" : "[length=" + b.length + "]") + "}";
}
public byte[] getB() {
return b;
}
public void setB(byte[] b) {
this.b = b;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package org.redkale.test.service;
import java.io.Serializable;
public class Person implements Serializable {
private byte[] b = new byte[1024 * 2];
private String name;
@Override
public String toString() {
return "{name=" + name + ", b =" + (b == null ? "null" : "[length=" + b.length + "]") + "}";
}
public byte[] getB() {
return b;
}
public void setB(byte[] b) {
this.b = b;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -1,9 +1,9 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
/** @author zhangjx */
public class TestBean {}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
/** @author zhangjx */
public class TestBean {}

View File

@@ -1,29 +1,29 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.*;
import org.redkale.boot.*;
import org.redkale.net.sncp.*;
import org.redkale.service.*;
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 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));
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.service;
import java.nio.channels.*;
import org.redkale.boot.*;
import org.redkale.net.sncp.*;
import org.redkale.service.*;
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 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));
}
}

View File

@@ -1,94 +1,94 @@
/*
*
*/
package org.redkale.test.sncp;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.*;
import org.junit.jupiter.api.*;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.*;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpClientCodecTest {
private boolean main;
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());
}
}
/*
*
*/
package org.redkale.test.sncp;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.*;
import org.junit.jupiter.api.*;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.*;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpClientCodecTest {
private boolean main;
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());
}
}

View File

@@ -1,86 +1,86 @@
/*
*
*/
package org.redkale.test.sncp;
import java.io.File;
import java.nio.channels.CompletionHandler;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.redkale.net.sncp.SncpAsyncHandler;
/** @author zhangjx */
public class SncpHandlerTest {
private boolean main;
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);
}
}
@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);
}
@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);
}
@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);
}
@Override
public void failed(Throwable exc, Object attachment) {}
})
.completed("key1", "val1");
}
public abstract static class ITestHandler1 implements CompletionHandler<String, File> {
@Override
public abstract void completed(String result, File attachment);
}
public static interface IClose<T> {
public void close(T val);
}
public static interface ITestHandler2 extends CompletionHandler<String, String>, IClose<File> {}
public static interface ITestHandler3 extends CompletionHandler<String, String>, Map<String, String> {}
}
/*
*
*/
package org.redkale.test.sncp;
import java.io.File;
import java.nio.channels.CompletionHandler;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.redkale.net.sncp.SncpAsyncHandler;
/** @author zhangjx */
public class SncpHandlerTest {
private boolean main;
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);
}
}
@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);
}
@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);
}
@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);
}
@Override
public void failed(Throwable exc, Object attachment) {}
})
.completed("key1", "val1");
}
public abstract static class ITestHandler1 implements CompletionHandler<String, File> {
@Override
public abstract void completed(String result, File attachment);
}
public static interface IClose<T> {
public void close(T val);
}
public static interface ITestHandler2 extends CompletionHandler<String, String>, IClose<File> {}
public static interface ITestHandler3 extends CompletionHandler<String, String>, Map<String, String> {}
}

View File

@@ -1,83 +1,83 @@
/*
*
*/
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.logging.Logger;
import org.junit.jupiter.api.*;
import org.redkale.net.*;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpRequestParseTest {
private boolean main;
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());
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)));
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());
}
public static class SncpRequestTest extends SncpRequest {
protected SncpRequestTest(SncpContext context) {
super(context);
}
@Override
protected int readHeader(ByteBuffer buffer, Request last) {
return super.readHeader(buffer, last);
}
}
}
/*
*
*/
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.logging.Logger;
import org.junit.jupiter.api.*;
import org.redkale.net.*;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpRequestParseTest {
private boolean main;
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());
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)));
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());
}
public static class SncpRequestTest extends SncpRequest {
protected SncpRequestTest(SncpContext context) {
super(context);
}
@Override
protected int readHeader(ByteBuffer buffer, Request last) {
return super.readHeader(buffer, last);
}
}
}

View File

@@ -1,49 +1,49 @@
/*
*
*/
package org.redkale.test.sncp;
import java.util.concurrent.CompletableFuture;
import org.redkale.service.AbstractService;
import org.redkale.util.Times;
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> 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());
}
}
/*
*
*/
package org.redkale.test.sncp;
import java.util.concurrent.CompletableFuture;
import org.redkale.service.AbstractService;
import org.redkale.util.Times;
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> 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());
}
}

View File

@@ -1,69 +1,69 @@
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.junit.jupiter.api.*;
import org.redkale.boot.Application;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.WorkThread;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpSleepTest {
private boolean main;
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());
// ------------------------ 初始化 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);
}
}
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import org.junit.jupiter.api.*;
import org.redkale.boot.Application;
import org.redkale.convert.bson.BsonConvert;
import org.redkale.convert.json.JsonConvert;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.WorkThread;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpSleepTest {
private boolean main;
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());
// ------------------------ 初始化 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);
}
}

View File

@@ -1,258 +1,258 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.redkale.boot.*;
import org.redkale.convert.bson.*;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.*;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.service.Service;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpTest {
private static final String myhost = "127.0.0.1";
private static int port = 0;
private static int port2 = 1;
private static final String protocol = "SNCP.TCP"; // TCP UDP
private static final int clientCapacity = protocol.endsWith(".UDP") ? AsyncGroup.UDP_BUFFER_CAPACITY : 8192;
private static ResourceFactory factory;
private static Application application;
private static SncpRpcGroups rpcGroups;
private boolean main;
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);
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();
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);
// 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());
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");
}
@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();
}
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));
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();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.net.InetSocketAddress;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.redkale.boot.*;
import org.redkale.convert.bson.*;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.*;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.service.Service;
import org.redkale.util.*;
/** @author zhangjx */
public class SncpTest {
private static final String myhost = "127.0.0.1";
private static int port = 0;
private static int port2 = 1;
private static final String protocol = "SNCP.TCP"; // TCP UDP
private static final int clientCapacity = protocol.endsWith(".UDP") ? AsyncGroup.UDP_BUFFER_CAPACITY : 8192;
private static ResourceFactory factory;
private static Application application;
private static SncpRpcGroups rpcGroups;
private boolean main;
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);
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();
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);
// 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());
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");
}
@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();
}
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));
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();
}
}

View File

@@ -1,54 +1,54 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import org.redkale.convert.bson.BsonFactory;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
import org.redkale.source.FilterBean;
import org.redkale.util.Utility;
/** @author zhangjx */
public class SncpTestBean implements FilterBean {
@Id
private long id;
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());
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import org.redkale.convert.bson.BsonFactory;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Id;
import org.redkale.source.FilterBean;
import org.redkale.util.Utility;
/** @author zhangjx */
public class SncpTestBean implements FilterBean {
@Id
private long id;
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());
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}

View File

@@ -1,25 +1,25 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.util.concurrent.CompletableFuture;
import org.redkale.service.Service;
/** @author zhangjx */
public interface SncpTestIService extends Service {
public String queryResult(SncpTestBean bean);
public double queryDoubleResult(String a, int b, double value);
public long queryLongResult(String a, int b, long value);
public CompletableFuture<String> queryResultAsync(SncpTestBean bean);
public SncpTestBean insert(SncpTestBean bean);
public String updateBean(SncpTestBean bean);
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.util.concurrent.CompletableFuture;
import org.redkale.service.Service;
/** @author zhangjx */
public interface SncpTestIService extends Service {
public String queryResult(SncpTestBean bean);
public double queryDoubleResult(String a, int b, double value);
public long queryLongResult(String a, int b, long value);
public CompletableFuture<String> queryResultAsync(SncpTestBean bean);
public SncpTestBean insert(SncpTestBean bean);
public String updateBean(SncpTestBean bean);
}

View File

@@ -1,126 +1,126 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.ResourceType;
import org.redkale.boot.Application;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.service.*;
import org.redkale.util.Utility;
/** @author zhangjx */
@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 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 SncpTestBean insert(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();
}
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;
}
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);
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("-----------------------------------");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.ResourceType;
import org.redkale.boot.Application;
import org.redkale.inject.ResourceFactory;
import org.redkale.net.AsyncIOGroup;
import org.redkale.net.client.ClientAddress;
import org.redkale.net.sncp.*;
import org.redkale.service.*;
import org.redkale.util.Utility;
/** @author zhangjx */
@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 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 SncpTestBean insert(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();
}
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;
}
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);
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("-----------------------------------");
}
}

View File

@@ -1,166 +1,166 @@
/*
*
*/
package org.redkale.test.sncp;
import java.lang.reflect.Method;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.ResourceType;
import org.redkale.convert.*;
import org.redkale.net.sncp.*;
import org.redkale.net.sncp.SncpServlet.SncpActionServlet;
import org.redkale.service.Service;
import org.redkale.test.util.TestBean;
import org.redkale.util.Uint128;
/** @author zhangjx */
public interface TestService extends Service {
public boolean change(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 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;
}
public void delete(TestBean bean) {}
@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 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 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);
}
@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);
}
@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);
}
@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);
}
@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);
}
}
/*
*
*/
package org.redkale.test.sncp;
import java.lang.reflect.Method;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.ResourceType;
import org.redkale.convert.*;
import org.redkale.net.sncp.*;
import org.redkale.net.sncp.SncpServlet.SncpActionServlet;
import org.redkale.service.Service;
import org.redkale.test.util.TestBean;
import org.redkale.util.Uint128;
/** @author zhangjx */
public interface TestService extends Service {
public boolean change(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 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;
}
public void delete(TestBean bean) {}
@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 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 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);
}
@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);
}
@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);
}
@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);
}
@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);
}
}

View File

@@ -1,12 +1,12 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import org.redkale.annotation.ResourceType;
/** @author zhangjx */
@ResourceType(SncpTestIService.class)
public class _DynLocalSncpTestService extends SncpTestServiceImpl {}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.sncp;
import org.redkale.annotation.ResourceType;
/** @author zhangjx */
@ResourceType(SncpTestIService.class)
public class _DynLocalSncpTestService extends SncpTestServiceImpl {}

View File

@@ -1,18 +1,18 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.convert.json.*;
/** @author zhangjx */
public abstract class BaseEntity implements Serializable {
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.convert.json.*;
/** @author zhangjx */
public abstract class BaseEntity implements Serializable {
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}

View File

@@ -1,101 +1,101 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
import org.redkale.persistence.VirtualEntity;
import org.redkale.source.*;
/** @author zhangjx */
@VirtualEntity(loader = CacheTestBean.DefaultBeanLoader.class)
public class CacheTestBean {
@Id
private long pkgid;
private String name;
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();
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")));
}
public CacheTestBean() {}
public CacheTestBean(long pkgid, String name, long price) {
this.pkgid = pkgid;
this.name = name;
this.price = price;
}
public long getPkgid() {
return pkgid;
}
public void setPkgid(long pkgid) {
this.pkgid = pkgid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
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);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
import org.redkale.persistence.VirtualEntity;
import org.redkale.source.*;
/** @author zhangjx */
@VirtualEntity(loader = CacheTestBean.DefaultBeanLoader.class)
public class CacheTestBean {
@Id
private long pkgid;
private String name;
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();
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")));
}
public CacheTestBean() {}
public CacheTestBean(long pkgid, String name, long price) {
this.pkgid = pkgid;
this.name = name;
this.price = price;
}
public long getPkgid() {
return pkgid;
}
public void setPkgid(long pkgid) {
this.pkgid = pkgid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
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);
}
}
}

View File

@@ -1,440 +1,440 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import static org.redkale.source.FilterExpress.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.annotation.AutoLoad;
import org.redkale.convert.json.*;
import org.redkale.persistence.Entity;
import org.redkale.persistence.Id;
import org.redkale.persistence.Transient;
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;
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import static org.redkale.source.FilterExpress.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.*;
import org.junit.jupiter.api.*;
import org.redkale.annotation.AutoLoad;
import org.redkale.convert.json.*;
import org.redkale.persistence.Entity;
import org.redkale.persistence.Id;
import org.redkale.persistence.Transient;
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;
}
}
}

View File

@@ -1,125 +1,125 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import java.util.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Column;
import org.redkale.persistence.Id;
import org.redkale.source.*;
import org.redkale.util.AnyValueWriter;
/** @author zhangjx */
// @Cacheable
public class JsonRecord {
@SourceConvert
private static JsonConvert createConvert() {
return JsonConvert.root();
}
@Id
@Column(comment = "主键ID;")
private long recordid;
@Column(comment = ";")
private String recordname = "";
@Column(comment = ";")
private Map<String, Integer> rmap;
@Column(comment = ";")
private List<String> rlist;
@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 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);
}
public long getRecordid() {
return recordid;
}
public void setRecordid(long recordid) {
this.recordid = recordid;
}
public String getRecordname() {
return recordname;
}
public void setRecordname(String recordname) {
this.recordname = recordname;
}
public Map<String, Integer> getRmap() {
return rmap;
}
public void setRmap(Map<String, Integer> rmap) {
this.rmap = rmap;
}
public List<String> getRlist() {
return rlist;
}
public void setRlist(List<String> rlist) {
this.rlist = rlist;
}
public Set<String> getRset() {
return rset;
}
public void setRset(Set<String> rset) {
this.rset = rset;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import java.util.*;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.Column;
import org.redkale.persistence.Id;
import org.redkale.source.*;
import org.redkale.util.AnyValueWriter;
/** @author zhangjx */
// @Cacheable
public class JsonRecord {
@SourceConvert
private static JsonConvert createConvert() {
return JsonConvert.root();
}
@Id
@Column(comment = "主键ID;")
private long recordid;
@Column(comment = ";")
private String recordname = "";
@Column(comment = ";")
private Map<String, Integer> rmap;
@Column(comment = ";")
private List<String> rlist;
@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 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);
}
public long getRecordid() {
return recordid;
}
public void setRecordid(long recordid) {
this.recordid = recordid;
}
public String getRecordname() {
return recordname;
}
public void setRecordname(String recordname) {
this.recordname = recordname;
}
public Map<String, Integer> getRmap() {
return rmap;
}
public void setRmap(Map<String, Integer> rmap) {
this.rmap = rmap;
}
public List<String> getRlist() {
return rlist;
}
public void setRlist(List<String> rlist) {
this.rlist = rlist;
}
public Set<String> getRset() {
return rset;
}
public void setRset(Set<String> rset) {
this.rset = rset;
}
}

View File

@@ -1,161 +1,161 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.persistence.*;
import org.redkale.source.*;
import org.redkale.util.Times;
import org.redkale.util.Utility;
/** @author zhangjx */
@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位)
@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 = "APP版本信息")
private String appversion = ""; // APP版本信息
@Column(updatable = false, comment = "APP操作系统信息")
private String appos = ""; // APP操作系统信息
@Column(updatable = false, comment = "登录时客户端信息")
private String loginagent = ""; // 登录时客户端信息
@Column(updatable = false, comment = "登录时的IP")
private String loginaddr = ""; // 登录时的IP
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
//
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getLoginid() {
return this.loginid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public long getUserid() {
return this.userid;
}
public void setNetmode(String netmode) {
this.netmode = netmode;
}
public String getNetmode() {
return this.netmode;
}
public String getAppversion() {
return appversion;
}
public void setAppversion(String appversion) {
this.appversion = appversion;
}
public String getAppos() {
return appos;
}
public void setAppos(String appos) {
this.appos = appos;
}
public void setLoginagent(String loginagent) {
this.loginagent = loginagent;
}
public String getLoginagent() {
return this.loginagent;
}
public void setLoginaddr(String loginaddr) {
this.loginaddr = loginaddr;
}
public String getLoginaddr() {
return this.loginaddr;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public long getCreatetime() {
return this.createtime;
}
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 class TableStrategy implements DistributeTableStrategy<LoginRecord> {
private static final String dayformat = "%1$tY%1$tm%1$td"; // 一天一个表
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 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));
}
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));
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.persistence.*;
import org.redkale.source.*;
import org.redkale.util.Times;
import org.redkale.util.Utility;
/** @author zhangjx */
@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位)
@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 = "APP版本信息")
private String appversion = ""; // APP版本信息
@Column(updatable = false, comment = "APP操作系统信息")
private String appos = ""; // APP操作系统信息
@Column(updatable = false, comment = "登录时客户端信息")
private String loginagent = ""; // 登录时客户端信息
@Column(updatable = false, comment = "登录时的IP")
private String loginaddr = ""; // 登录时的IP
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
//
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getLoginid() {
return this.loginid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public long getUserid() {
return this.userid;
}
public void setNetmode(String netmode) {
this.netmode = netmode;
}
public String getNetmode() {
return this.netmode;
}
public String getAppversion() {
return appversion;
}
public void setAppversion(String appversion) {
this.appversion = appversion;
}
public String getAppos() {
return appos;
}
public void setAppos(String appos) {
this.appos = appos;
}
public void setLoginagent(String loginagent) {
this.loginagent = loginagent;
}
public String getLoginagent() {
return this.loginagent;
}
public void setLoginaddr(String loginaddr) {
this.loginaddr = loginaddr;
}
public String getLoginaddr() {
return this.loginaddr;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public long getCreatetime() {
return this.createtime;
}
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 class TableStrategy implements DistributeTableStrategy<LoginRecord> {
private static final String dayformat = "%1$tY%1$tm%1$td"; // 一天一个表
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 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));
}
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));
}
}
}

View File

@@ -1,54 +1,54 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.BiFunction;
import org.redkale.source.*;
/** @author zhangjx */
public class LoginTestBean implements FilterBean {
private String sessionid;
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 String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.BiFunction;
import org.redkale.source.*;
/** @author zhangjx */
public class LoginTestBean implements FilterBean {
private String sessionid;
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 String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
}

View File

@@ -1,86 +1,86 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import org.redkale.convert.json.*;
import org.redkale.persistence.Id;
/**
* CREATE TABLE `LoginTestRecord` ( `sessionid` VARCHAR(64) NOT NULL COMMENT '登录会话ID', `userid` INT(11) NOT NULL COMMENT
* '登录用户ID', `loginagent` VARCHAR(128) NOT NULL COMMENT '登录端信息', `loginip` VARCHAR(255) NOT NULL COMMENT '登录IP',
* `logintime` BIGINT(20) NOT NULL COMMENT '登录时间', `logouttime` BIGINT(20) NOT NULL COMMENT '注销时间', PRIMARY KEY
* (`sessionid`) ) ENGINE=INNODB DEFAULT CHARSET=utf8;
*
* @author zhangjx
*/
public class LoginTestRecord {
@Id
private String sessionid;
private int userid;
private String loginagent;
private String loginip;
private long logintime;
private long logouttime;
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getLoginagent() {
return loginagent;
}
public void setLoginagent(String loginagent) {
this.loginagent = loginagent;
}
public String getLoginip() {
return loginip;
}
public void setLoginip(String loginip) {
this.loginip = loginip;
}
public long getLogintime() {
return logintime;
}
public void setLogintime(long logintime) {
this.logintime = logintime;
}
public long getLogouttime() {
return logouttime;
}
public void setLogouttime(long logouttime) {
this.logouttime = logouttime;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import org.redkale.convert.json.*;
import org.redkale.persistence.Id;
/**
* CREATE TABLE `LoginTestRecord` ( `sessionid` VARCHAR(64) NOT NULL COMMENT '登录会话ID', `userid` INT(11) NOT NULL COMMENT
* '登录用户ID', `loginagent` VARCHAR(128) NOT NULL COMMENT '登录端信息', `loginip` VARCHAR(255) NOT NULL COMMENT '登录IP',
* `logintime` BIGINT(20) NOT NULL COMMENT '登录时间', `logouttime` BIGINT(20) NOT NULL COMMENT '注销时间', PRIMARY KEY
* (`sessionid`) ) ENGINE=INNODB DEFAULT CHARSET=utf8;
*
* @author zhangjx
*/
public class LoginTestRecord {
@Id
private String sessionid;
private int userid;
private String loginagent;
private String loginip;
private long logintime;
private long logouttime;
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
public String getSessionid() {
return sessionid;
}
public void setSessionid(String sessionid) {
this.sessionid = sessionid;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getLoginagent() {
return loginagent;
}
public void setLoginagent(String loginagent) {
this.loginagent = loginagent;
}
public String getLoginip() {
return loginip;
}
public void setLoginip(String loginip) {
this.loginip = loginip;
}
public long getLogintime() {
return logintime;
}
public void setLogintime(long logintime) {
this.logintime = logintime;
}
public long getLogouttime() {
return logouttime;
}
public void setLogouttime(long logouttime) {
this.logouttime = logouttime;
}
}

View File

@@ -1,88 +1,88 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.persistence.*;
import org.redkale.source.*;
/** @author zhangjx */
@DistributeTable(strategy = LoginUserRecord.TableStrategy.class)
public class LoginUserRecord extends BaseEntity {
@Id
@Column(comment = "记录ID; 值=userid+'-'+UUID")
private String seqid = ""; // 记录ID; 值=userid+'-'+UUID
@Column(updatable = false, comment = "C端用户ID")
private long userid; // C端用户ID
@Column(comment = "LoginRecord主键")
private String loginid = ""; // LoginRecord主键
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
//
public String getSeqid() {
return seqid;
}
public void setSeqid(String seqid) {
this.seqid = seqid;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public static class TableStrategy implements DistributeTableStrategy<LoginUserRecord> {
@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 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));
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.persistence.*;
import org.redkale.source.*;
/** @author zhangjx */
@DistributeTable(strategy = LoginUserRecord.TableStrategy.class)
public class LoginUserRecord extends BaseEntity {
@Id
@Column(comment = "记录ID; 值=userid+'-'+UUID")
private String seqid = ""; // 记录ID; 值=userid+'-'+UUID
@Column(updatable = false, comment = "C端用户ID")
private long userid; // C端用户ID
@Column(comment = "LoginRecord主键")
private String loginid = ""; // LoginRecord主键
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
//
public String getSeqid() {
return seqid;
}
public void setSeqid(String seqid) {
this.seqid = seqid;
}
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public static class TableStrategy implements DistributeTableStrategy<LoginUserRecord> {
@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 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));
}
}
}

View File

@@ -1,134 +1,134 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiFunction;
import org.junit.jupiter.api.Assertions;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
import org.redkale.persistence.VirtualEntity;
import org.redkale.source.*;
import org.redkale.util.Sheet;
/** @author zhangjx */
public class TestSourceCache {
public static class TestEntityBean implements FilterBean {
@FilterColumn(express = FilterExpress.GT)
public int userid;
@FilterColumn(express = FilterExpress.LIKE)
public String username;
public TestEntityBean(int userid, String username) {
this.userid = userid;
this.username = username;
}
}
public static void main(String[] args) throws Exception {
final 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);
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 {
@Id
private int userid;
private String username;
private long createtime = System.currentTimeMillis();
public TestEntity() {}
public TestEntity(int userid, String username) {
this.userid = userid;
this.username = username;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiFunction;
import org.junit.jupiter.api.Assertions;
import org.redkale.convert.json.JsonConvert;
import org.redkale.persistence.*;
import org.redkale.persistence.VirtualEntity;
import org.redkale.source.*;
import org.redkale.util.Sheet;
/** @author zhangjx */
public class TestSourceCache {
public static class TestEntityBean implements FilterBean {
@FilterColumn(express = FilterExpress.GT)
public int userid;
@FilterColumn(express = FilterExpress.LIKE)
public String username;
public TestEntityBean(int userid, String username) {
this.userid = userid;
this.username = username;
}
}
public static void main(String[] args) throws Exception {
final 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);
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 {
@Id
private int userid;
private String username;
private long createtime = System.currentTimeMillis();
public TestEntity() {}
public TestEntity(int userid, String username) {
this.userid = userid;
this.username = username;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
}

View File

@@ -1,109 +1,109 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.convert.*;
import org.redkale.persistence.*;
import org.redkale.source.*;
/** @author zhangjx */
@DistributeTable(strategy = UserDetail.TableStrategy.class)
public class UserDetail extends BaseEntity {
public static class TableStrategy implements DistributeTableStrategy<UserDetail> {
@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 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));
}
}
@Id
private long userid; // 用户ID
@Column(length = 64, comment = "用户昵称")
private String username = ""; // 用户昵称
@Column(length = 32, comment = "手机号码")
private String mobile = ""; // 手机号码
@Column(length = 64, comment = "密码")
@ConvertColumn(ignore = true, type = ConvertType.ALL)
private String password = ""; // 密码
@Column(length = 128, comment = "备注")
private String remark = ""; // 备注
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source;
import java.io.Serializable;
import org.redkale.convert.*;
import org.redkale.persistence.*;
import org.redkale.source.*;
/** @author zhangjx */
@DistributeTable(strategy = UserDetail.TableStrategy.class)
public class UserDetail extends BaseEntity {
public static class TableStrategy implements DistributeTableStrategy<UserDetail> {
@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 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));
}
}
@Id
private long userid; // 用户ID
@Column(length = 64, comment = "用户昵称")
private String username = ""; // 用户昵称
@Column(length = 32, comment = "手机号码")
private String mobile = ""; // 手机号码
@Column(length = 64, comment = "密码")
@ConvertColumn(ignore = true, type = ConvertType.ALL)
private String password = ""; // 密码
@Column(length = 128, comment = "备注")
private String remark = ""; // 备注
@Column(updatable = false, comment = "创建时间")
private long createtime; // 创建时间
/** 以下省略getter setter方法 */
public long getUserid() {
return userid;
}
public void setUserid(long userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
}

View File

@@ -1,20 +1,20 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source.parser;
import java.io.*;
import org.redkale.convert.json.*;
import org.redkale.persistence.*;
/** @author zhangjx */
@Entity
public abstract class BaseEntity implements Serializable {
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.test.source.parser;
import java.io.*;
import org.redkale.convert.json.*;
import org.redkale.persistence.*;
/** @author zhangjx */
@Entity
public abstract class BaseEntity implements Serializable {
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}

View File

@@ -1,9 +1,9 @@
/*
*
*/
package org.redkale.test.source.parser;
import org.redkale.source.DataSqlMapper;
/** @author zhangjx */
public interface BaseMapper<V> extends DataSqlMapper<V> {}
/*
*
*/
package org.redkale.test.source.parser;
import org.redkale.source.DataSqlMapper;
/** @author zhangjx */
public interface BaseMapper<V> extends DataSqlMapper<V> {}

View File

@@ -1,31 +1,31 @@
/*
*
*/
package org.redkale.test.source.parser;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.redkale.source.DataJdbcSource;
import org.redkale.source.DataSqlSource;
/** @author zhangjx */
public class DataSqlMapperTest {
private static DataSqlSource source = new DataJdbcSource();
public static void main(String[] args) throws Throwable {
DataSqlMapperTest test = new DataSqlMapperTest();
test.init();
test.run();
}
@BeforeAll
public static void init() throws Exception {
// do
}
@Test
public void run() throws Exception {
// do
}
}
/*
*
*/
package org.redkale.test.source.parser;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.redkale.source.DataJdbcSource;
import org.redkale.source.DataSqlSource;
/** @author zhangjx */
public class DataSqlMapperTest {
private static DataSqlSource source = new DataJdbcSource();
public static void main(String[] args) throws Throwable {
DataSqlMapperTest test = new DataSqlMapperTest();
test.init();
test.run();
}
@BeforeAll
public static void init() throws Exception {
// do
}
@Test
public void run() throws Exception {
// do
}
}

View File

@@ -1,62 +1,62 @@
/*
*
*/
package org.redkale.test.source.parser;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.redkale.source.DataSqlSource;
/** @author zhangjx */
public class DynForumInfoMapperImpl implements ForumInfoMapper {
private DataSqlSource _source;
private Class _type;
@Override
public ForumResult findForumResult(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryOne(ForumResult.class, sql, params);
}
public CompletableFuture<ForumResult> findForumResultAsync(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryOneAsync(ForumResult.class, sql, params);
}
@Override
public List<ForumResult> queryForumResult(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryList(ForumResult.class, sql, params);
}
public CompletableFuture<List<ForumResult>> queryForumResultAsync(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryListAsync(ForumResult.class, sql, params);
}
@Override
public DataSqlSource dataSource() {
return _source;
}
@Override
public Class<ForumInfo> entityType() {
return _type;
}
}
/*
*
*/
package org.redkale.test.source.parser;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.redkale.source.DataSqlSource;
/** @author zhangjx */
public class DynForumInfoMapperImpl implements ForumInfoMapper {
private DataSqlSource _source;
private Class _type;
@Override
public ForumResult findForumResult(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryOne(ForumResult.class, sql, params);
}
public CompletableFuture<ForumResult> findForumResultAsync(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryOneAsync(ForumResult.class, sql, params);
}
@Override
public List<ForumResult> queryForumResult(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryList(ForumResult.class, sql, params);
}
public CompletableFuture<List<ForumResult>> queryForumResultAsync(ForumBean bean) {
String sql =
"SELECT f.forum_groupid, s.forum_section_color FROM forum_info f, forum_section s WHERE f.forumid = s.forumid";
Map<String, Object> params = new HashMap<>();
params.put("bean", bean);
return dataSource().nativeQueryListAsync(ForumResult.class, sql, params);
}
@Override
public DataSqlSource dataSource() {
return _source;
}
@Override
public Class<ForumInfo> entityType() {
return _type;
}
}

View File

@@ -1,40 +1,40 @@
/*
*
*/
package org.redkale.test.source.parser;
import java.io.Serializable;
/** @author zhangjx */
public class ForumBean implements Serializable {
private String forumSectionid;
private String forumSectionColor;
private String forumid;
public String getForumSectionid() {
return forumSectionid;
}
public void setForumSectionid(String forumSectionid) {
this.forumSectionid = forumSectionid;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
public String getForumid() {
return forumid;
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
}
/*
*
*/
package org.redkale.test.source.parser;
import java.io.Serializable;
/** @author zhangjx */
public class ForumBean implements Serializable {
private String forumSectionid;
private String forumSectionColor;
private String forumid;
public String getForumSectionid() {
return forumSectionid;
}
public void setForumSectionid(String forumSectionid) {
this.forumSectionid = forumSectionid;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
public String getForumid() {
return forumid;
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
}

View File

@@ -1,255 +1,255 @@
package org.redkale.test.source.parser;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.persistence.*;
import org.redkale.util.Utility;
/** @author zhangjx */
@Table(name = "forum_info", comment = "论坛信息表")
public class ForumInfo extends BaseEntity implements Comparable<ForumInfo> {
@Id
@Column(name = "forum_id", length = 64, comment = "论坛ID")
private String forumid;
@Column(name = "forum_name", length = 128, comment = "论坛的名称")
private String forumName;
@Column(name = "forum_groupid", length = 64, comment = "论坛分类的ID")
private String forumGroupid;
@Column(name = "forum_sections", length = 1024, comment = "论坛小版块的ID集合")
private String[] forumSections;
@Column(name = "forum_managerids", length = 1024, comment = "论坛小版块的ID集合")
private Set<Integer> forumManagerids;
@Column(name = "forum_face_url", length = 255, comment = "论坛的图片url")
private String forumFaceUrl;
@Column(name = "forum_css_img_url", length = 255, comment = "论坛的背景图url")
private String forumCssImgUrl;
@Column(name = "forum_css_url", length = 255, comment = "论坛的样式url")
private String forumCssUrl;
@Column(name = "forum_css_content", length = 10240, comment = "论坛的css内容")
private String forumCssContent;
@Column(name = "forum_bar_html", length = 1024, comment = "版块的提示栏")
private String forumBarHtml;
@Column(name = "forum_desc", length = 255, comment = "论坛说明")
private String forumDesc;
@Column(name = "forum_notice", length = 1024, comment = "论坛公告")
private String forumNotice;
@Column(comment = "被关注的用户数")
private long followers;
@Column(name = "post_count", comment = "帖子数")
private long postCount;
@Column(name = "like_count", comment = "关注数")
private long likeCount;
@Column(comment = "排序顺序,值小靠前")
private int display = 1000;
@Transient
private Map<String, ForumSection> sections;
public ForumSection findForumSection(String forumSectionid) {
return sections == null ? null : sections.get(forumSectionid);
}
public synchronized void increLikeCount() {
this.likeCount++;
}
public synchronized void increPostCount(String sectionid) {
this.postCount++;
if (sections != null && sectionid != null && !sectionid.isEmpty()) {
ForumSection section = sections.get(sectionid);
if (section != null) {
section.increPostCount();
}
}
}
public synchronized void increFollowers() {
this.followers++;
}
public synchronized void decreFollowers() {
this.followers--;
}
public boolean containsManagerid(int userid) {
return forumManagerids != null && forumManagerids.contains(userid);
}
public boolean containsSection(String forumSectionid) {
return forumSections != null && forumSectionid != null && Utility.contains(forumSections, forumSectionid);
}
public boolean emptyForumNotice() {
return this.forumNotice == null || this.forumNotice.isEmpty();
}
public boolean emptyCssImgUrl() {
return this.forumCssImgUrl == null || this.forumCssImgUrl.isEmpty();
}
public boolean emptyCssUrl() {
return this.forumCssUrl == null || this.forumCssUrl.isEmpty();
}
public boolean emptyCssContent() {
return this.forumCssContent == null || this.forumCssContent.isEmpty();
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
public String getForumid() {
return this.forumid;
}
public void setForumName(String forumName) {
this.forumName = forumName;
}
public String getForumName() {
return this.forumName;
}
public void setForumFaceUrl(String forumFaceUrl) {
this.forumFaceUrl = forumFaceUrl;
}
public String getForumFaceUrl() {
return this.forumFaceUrl;
}
public String getForumCssImgUrl() {
return forumCssImgUrl;
}
public void setForumCssImgUrl(String forumCssImgUrl) {
this.forumCssImgUrl = forumCssImgUrl;
}
public String getForumCssUrl() {
return forumCssUrl;
}
public void setForumCssUrl(String forumCssUrl) {
this.forumCssUrl = forumCssUrl;
}
public String getForumCssContent() {
return forumCssContent;
}
public void setForumCssContent(String forumCssContent) {
this.forumCssContent = forumCssContent;
}
public String[] getForumSections() {
return forumSections;
}
public void setForumSections(String[] forumSections) {
this.forumSections = forumSections;
}
public Set<Integer> getForumManagerids() {
return forumManagerids;
}
public void setForumManagerids(Set<Integer> forumManagerids) {
this.forumManagerids = forumManagerids;
}
public String getForumGroupid() {
return forumGroupid;
}
public void setForumGroupid(String forumGroupid) {
this.forumGroupid = forumGroupid;
}
public String getForumDesc() {
return forumDesc;
}
public void setForumDesc(String forumDesc) {
this.forumDesc = forumDesc;
}
public String getForumNotice() {
return forumNotice;
}
public void setForumNotice(String forumNotice) {
this.forumNotice = forumNotice;
}
public long getFollowers() {
return followers;
}
public void setFollowers(long followers) {
this.followers = followers;
}
public void setPostCount(long postCount) {
this.postCount = postCount;
}
public long getPostCount() {
return this.postCount;
}
public long getLikeCount() {
return likeCount;
}
public void setLikeCount(long likeCount) {
this.likeCount = likeCount;
}
public void setDisplay(int display) {
this.display = display;
}
@ConvertColumn(ignore = true, type = ConvertType.PROTOBUF_JSON)
public int getDisplay() {
return this.display;
}
@Override
public int compareTo(ForumInfo o) {
return this.display - o.display;
}
public Map<String, ForumSection> getSections() {
return sections;
}
public void setSections(Map<String, ForumSection> sections) {
this.sections = sections;
}
public String getForumBarHtml() {
return forumBarHtml;
}
public void setForumBarHtml(String forumBarHtml) {
this.forumBarHtml = forumBarHtml;
}
}
package org.redkale.test.source.parser;
import java.util.*;
import org.redkale.convert.*;
import org.redkale.persistence.*;
import org.redkale.util.Utility;
/** @author zhangjx */
@Table(name = "forum_info", comment = "论坛信息表")
public class ForumInfo extends BaseEntity implements Comparable<ForumInfo> {
@Id
@Column(name = "forum_id", length = 64, comment = "论坛ID")
private String forumid;
@Column(name = "forum_name", length = 128, comment = "论坛的名称")
private String forumName;
@Column(name = "forum_groupid", length = 64, comment = "论坛分类的ID")
private String forumGroupid;
@Column(name = "forum_sections", length = 1024, comment = "论坛小版块的ID集合")
private String[] forumSections;
@Column(name = "forum_managerids", length = 1024, comment = "论坛小版块的ID集合")
private Set<Integer> forumManagerids;
@Column(name = "forum_face_url", length = 255, comment = "论坛的图片url")
private String forumFaceUrl;
@Column(name = "forum_css_img_url", length = 255, comment = "论坛的背景图url")
private String forumCssImgUrl;
@Column(name = "forum_css_url", length = 255, comment = "论坛的样式url")
private String forumCssUrl;
@Column(name = "forum_css_content", length = 10240, comment = "论坛的css内容")
private String forumCssContent;
@Column(name = "forum_bar_html", length = 1024, comment = "版块的提示栏")
private String forumBarHtml;
@Column(name = "forum_desc", length = 255, comment = "论坛说明")
private String forumDesc;
@Column(name = "forum_notice", length = 1024, comment = "论坛公告")
private String forumNotice;
@Column(comment = "被关注的用户数")
private long followers;
@Column(name = "post_count", comment = "帖子数")
private long postCount;
@Column(name = "like_count", comment = "关注数")
private long likeCount;
@Column(comment = "排序顺序,值小靠前")
private int display = 1000;
@Transient
private Map<String, ForumSection> sections;
public ForumSection findForumSection(String forumSectionid) {
return sections == null ? null : sections.get(forumSectionid);
}
public synchronized void increLikeCount() {
this.likeCount++;
}
public synchronized void increPostCount(String sectionid) {
this.postCount++;
if (sections != null && sectionid != null && !sectionid.isEmpty()) {
ForumSection section = sections.get(sectionid);
if (section != null) {
section.increPostCount();
}
}
}
public synchronized void increFollowers() {
this.followers++;
}
public synchronized void decreFollowers() {
this.followers--;
}
public boolean containsManagerid(int userid) {
return forumManagerids != null && forumManagerids.contains(userid);
}
public boolean containsSection(String forumSectionid) {
return forumSections != null && forumSectionid != null && Utility.contains(forumSections, forumSectionid);
}
public boolean emptyForumNotice() {
return this.forumNotice == null || this.forumNotice.isEmpty();
}
public boolean emptyCssImgUrl() {
return this.forumCssImgUrl == null || this.forumCssImgUrl.isEmpty();
}
public boolean emptyCssUrl() {
return this.forumCssUrl == null || this.forumCssUrl.isEmpty();
}
public boolean emptyCssContent() {
return this.forumCssContent == null || this.forumCssContent.isEmpty();
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
public String getForumid() {
return this.forumid;
}
public void setForumName(String forumName) {
this.forumName = forumName;
}
public String getForumName() {
return this.forumName;
}
public void setForumFaceUrl(String forumFaceUrl) {
this.forumFaceUrl = forumFaceUrl;
}
public String getForumFaceUrl() {
return this.forumFaceUrl;
}
public String getForumCssImgUrl() {
return forumCssImgUrl;
}
public void setForumCssImgUrl(String forumCssImgUrl) {
this.forumCssImgUrl = forumCssImgUrl;
}
public String getForumCssUrl() {
return forumCssUrl;
}
public void setForumCssUrl(String forumCssUrl) {
this.forumCssUrl = forumCssUrl;
}
public String getForumCssContent() {
return forumCssContent;
}
public void setForumCssContent(String forumCssContent) {
this.forumCssContent = forumCssContent;
}
public String[] getForumSections() {
return forumSections;
}
public void setForumSections(String[] forumSections) {
this.forumSections = forumSections;
}
public Set<Integer> getForumManagerids() {
return forumManagerids;
}
public void setForumManagerids(Set<Integer> forumManagerids) {
this.forumManagerids = forumManagerids;
}
public String getForumGroupid() {
return forumGroupid;
}
public void setForumGroupid(String forumGroupid) {
this.forumGroupid = forumGroupid;
}
public String getForumDesc() {
return forumDesc;
}
public void setForumDesc(String forumDesc) {
this.forumDesc = forumDesc;
}
public String getForumNotice() {
return forumNotice;
}
public void setForumNotice(String forumNotice) {
this.forumNotice = forumNotice;
}
public long getFollowers() {
return followers;
}
public void setFollowers(long followers) {
this.followers = followers;
}
public void setPostCount(long postCount) {
this.postCount = postCount;
}
public long getPostCount() {
return this.postCount;
}
public long getLikeCount() {
return likeCount;
}
public void setLikeCount(long likeCount) {
this.likeCount = likeCount;
}
public void setDisplay(int display) {
this.display = display;
}
@ConvertColumn(ignore = true, type = ConvertType.PROTOBUF_JSON)
public int getDisplay() {
return this.display;
}
@Override
public int compareTo(ForumInfo o) {
return this.display - o.display;
}
public Map<String, ForumSection> getSections() {
return sections;
}
public void setSections(Map<String, ForumSection> sections) {
this.sections = sections;
}
public String getForumBarHtml() {
return forumBarHtml;
}
public void setForumBarHtml(String forumBarHtml) {
this.forumBarHtml = forumBarHtml;
}
}

View File

@@ -1,41 +1,41 @@
/*
*
*/
package org.redkale.test.source.parser;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.Param;
import org.redkale.persistence.Sql;
/** @author zhangjx */
public interface ForumInfoMapper extends BaseMapper<ForumInfo> {
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public ForumResult findForumResult(ForumBean bean);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public CompletableFuture<ForumResult> findForumResultAsync(ForumBean bean);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public List<ForumResult> queryForumResult(@Param("bean") ForumBean bean0);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public CompletableFuture<List<ForumResult>> queryForumResultAsync(ForumBean bean);
}
/*
*
*/
package org.redkale.test.source.parser;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import org.redkale.annotation.Param;
import org.redkale.persistence.Sql;
/** @author zhangjx */
public interface ForumInfoMapper extends BaseMapper<ForumInfo> {
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public ForumResult findForumResult(ForumBean bean);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public CompletableFuture<ForumResult> findForumResultAsync(ForumBean bean);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public List<ForumResult> queryForumResult(@Param("bean") ForumBean bean0);
@Sql("SELECT f.forum_groupid, s.forum_section_color "
+ "FROM forum_info f, forum_section s "
+ " WHERE f.forumid = s.forumid AND "
+ "s.forum_sectionid = #{bean.forumSectionid} AND "
+ "f.forumid = #{bean.forumid} AND s.forum_section_color = #{bean.forumSectionColor}")
public CompletableFuture<List<ForumResult>> queryForumResultAsync(ForumBean bean);
}

View File

@@ -1,35 +1,35 @@
/*
*
*/
package org.redkale.test.source.parser;
import org.redkale.convert.json.JsonConvert;
/** @author zhangjx */
public class ForumResult {
private String forumGroupid;
private String forumSectionColor;
public String getForumGroupid() {
return forumGroupid;
}
public void setForumGroupid(String forumGroupid) {
this.forumGroupid = forumGroupid;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}
/*
*
*/
package org.redkale.test.source.parser;
import org.redkale.convert.json.JsonConvert;
/** @author zhangjx */
public class ForumResult {
private String forumGroupid;
private String forumSectionColor;
public String getForumGroupid() {
return forumGroupid;
}
public void setForumGroupid(String forumGroupid) {
this.forumGroupid = forumGroupid;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
@Override
public String toString() {
return JsonConvert.root().convertTo(this);
}
}

View File

@@ -1,130 +1,130 @@
package org.redkale.test.source.parser;
import java.util.Set;
import org.redkale.convert.*;
import org.redkale.persistence.*;
/** @author zhangjx */
@Table(name = "forum_section", comment = "论坛小版块信息表")
public class ForumSection extends BaseEntity {
@Id
@Column(name = "forum_sectionid", length = 64, comment = "论坛小版块ID")
private String forumSectionid;
@Column(length = 64, comment = "论坛ID")
private String forumid;
@Column(name = "forum_section_name", length = 128, comment = "论坛小版块的名称")
private String forumSectionName;
@Column(name = "forum_section_face_url", length = 255, comment = "论坛小版块的图标url")
private String forumSectionFaceUrl;
@Column(name = "forum_section_managerids", length = 1024, comment = "论坛小版块的ID集合")
private Set<Integer> forumSectionManagerids;
@Column(name = "forum_section_desc", length = 32, comment = "论坛小版块说明")
private String forumSectionDesc;
@Column(name = "forum_section_color", length = 255, comment = "论坛小版块小标题的背景色")
private String forumSectionColor;
@Column(name = "forum_section_bar_html", length = 1024, comment = "版块的提示栏")
private String forumSectionBarHtml;
@Column(name = "post_count", comment = "帖子数")
private long postCount;
@Column(comment = "排序顺序,值小靠前")
private int display = 1000;
public void increPostCount() {
this.postCount++;
}
public boolean containsSectionManagerid(int userid) {
return forumSectionManagerids != null && forumSectionManagerids.contains(userid);
}
public void setForumSectionid(String forumSectionid) {
this.forumSectionid = forumSectionid;
}
public String getForumSectionid() {
return this.forumSectionid;
}
public String getForumid() {
return forumid;
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
public void setForumSectionName(String forumSectionName) {
this.forumSectionName = forumSectionName;
}
public String getForumSectionName() {
return this.forumSectionName;
}
public void setForumSectionFaceUrl(String forumSectionFaceUrl) {
this.forumSectionFaceUrl = forumSectionFaceUrl;
}
public String getForumSectionFaceUrl() {
return this.forumSectionFaceUrl;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
public void setForumSectionDesc(String forumSectionDesc) {
this.forumSectionDesc = forumSectionDesc;
}
public Set<Integer> getForumSectionManagerids() {
return forumSectionManagerids;
}
public void setForumSectionManagerids(Set<Integer> forumSectionManagerids) {
this.forumSectionManagerids = forumSectionManagerids;
}
public String getForumSectionDesc() {
return this.forumSectionDesc;
}
public void setPostCount(long postCount) {
this.postCount = postCount;
}
public long getPostCount() {
return this.postCount;
}
public void setDisplay(int display) {
this.display = display;
}
@ConvertColumn(ignore = true, type = ConvertType.PROTOBUF_JSON)
public int getDisplay() {
return this.display;
}
public String getForumSectionBarHtml() {
return forumSectionBarHtml;
}
public void setForumSectionBarHtml(String forumSectionBarHtml) {
this.forumSectionBarHtml = forumSectionBarHtml;
}
}
package org.redkale.test.source.parser;
import java.util.Set;
import org.redkale.convert.*;
import org.redkale.persistence.*;
/** @author zhangjx */
@Table(name = "forum_section", comment = "论坛小版块信息表")
public class ForumSection extends BaseEntity {
@Id
@Column(name = "forum_sectionid", length = 64, comment = "论坛小版块ID")
private String forumSectionid;
@Column(length = 64, comment = "论坛ID")
private String forumid;
@Column(name = "forum_section_name", length = 128, comment = "论坛小版块的名称")
private String forumSectionName;
@Column(name = "forum_section_face_url", length = 255, comment = "论坛小版块的图标url")
private String forumSectionFaceUrl;
@Column(name = "forum_section_managerids", length = 1024, comment = "论坛小版块的ID集合")
private Set<Integer> forumSectionManagerids;
@Column(name = "forum_section_desc", length = 32, comment = "论坛小版块说明")
private String forumSectionDesc;
@Column(name = "forum_section_color", length = 255, comment = "论坛小版块小标题的背景色")
private String forumSectionColor;
@Column(name = "forum_section_bar_html", length = 1024, comment = "版块的提示栏")
private String forumSectionBarHtml;
@Column(name = "post_count", comment = "帖子数")
private long postCount;
@Column(comment = "排序顺序,值小靠前")
private int display = 1000;
public void increPostCount() {
this.postCount++;
}
public boolean containsSectionManagerid(int userid) {
return forumSectionManagerids != null && forumSectionManagerids.contains(userid);
}
public void setForumSectionid(String forumSectionid) {
this.forumSectionid = forumSectionid;
}
public String getForumSectionid() {
return this.forumSectionid;
}
public String getForumid() {
return forumid;
}
public void setForumid(String forumid) {
this.forumid = forumid;
}
public void setForumSectionName(String forumSectionName) {
this.forumSectionName = forumSectionName;
}
public String getForumSectionName() {
return this.forumSectionName;
}
public void setForumSectionFaceUrl(String forumSectionFaceUrl) {
this.forumSectionFaceUrl = forumSectionFaceUrl;
}
public String getForumSectionFaceUrl() {
return this.forumSectionFaceUrl;
}
public String getForumSectionColor() {
return forumSectionColor;
}
public void setForumSectionColor(String forumSectionColor) {
this.forumSectionColor = forumSectionColor;
}
public void setForumSectionDesc(String forumSectionDesc) {
this.forumSectionDesc = forumSectionDesc;
}
public Set<Integer> getForumSectionManagerids() {
return forumSectionManagerids;
}
public void setForumSectionManagerids(Set<Integer> forumSectionManagerids) {
this.forumSectionManagerids = forumSectionManagerids;
}
public String getForumSectionDesc() {
return this.forumSectionDesc;
}
public void setPostCount(long postCount) {
this.postCount = postCount;
}
public long getPostCount() {
return this.postCount;
}
public void setDisplay(int display) {
this.display = display;
}
@ConvertColumn(ignore = true, type = ConvertType.PROTOBUF_JSON)
public int getDisplay() {
return this.display;
}
public String getForumSectionBarHtml() {
return forumSectionBarHtml;
}
public void setForumSectionBarHtml(String forumSectionBarHtml) {
this.forumSectionBarHtml = forumSectionBarHtml;
}
}

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