格式化代码
This commit is contained in:
@@ -359,7 +359,9 @@ public final class Application {
|
||||
List<String> list = new ArrayList<>();
|
||||
reader.lines().forEach(v -> list.add(v));
|
||||
Collections.sort(list);
|
||||
if (!list.isEmpty()) cacheClasses = new LinkedHashSet<>(list);
|
||||
if (!list.isEmpty()) {
|
||||
cacheClasses = new LinkedHashSet<>(list);
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -381,7 +383,9 @@ public final class Application {
|
||||
} else if ("file".equals(confPath.getScheme())) {
|
||||
logConfFile = new File(confPath.getPath(), "logging.properties");
|
||||
logConfURI = logConfFile.toURI();
|
||||
if (!logConfFile.isFile() || !logConfFile.canRead()) logConfFile = null;
|
||||
if (!logConfFile.isFile() || !logConfFile.canRead()) {
|
||||
logConfFile = null;
|
||||
}
|
||||
} else {
|
||||
logConfURI = URI.create(confPath + (confPath.toString().endsWith("/") ? "" : "/") + "logging.properties");
|
||||
}
|
||||
@@ -456,10 +460,14 @@ public final class Application {
|
||||
AnyValue executorConf = null;
|
||||
executorConf = config.getAnyValue("executor");
|
||||
AnyValue excludelibConf = config.getAnyValue("excludelibs");
|
||||
if (excludelibConf != null) excludelib0 = excludelibConf.getValue("value");
|
||||
if (excludelibConf != null) {
|
||||
excludelib0 = excludelibConf.getValue("value");
|
||||
}
|
||||
AnyValue transportConf = config.getAnyValue("transport");
|
||||
int groupsize = config.getAnyValues("group").length;
|
||||
if (groupsize > 0 && transportConf == null) transportConf = new DefaultAnyValue();
|
||||
if (groupsize > 0 && transportConf == null) {
|
||||
transportConf = new DefaultAnyValue();
|
||||
}
|
||||
if (transportConf != null) {
|
||||
//--------------transportBufferPool-----------
|
||||
bufferCapacity = Math.max(parseLenth(transportConf.getValue("bufferCapacity"), bufferCapacity), 32 * 1024);
|
||||
@@ -478,7 +486,9 @@ public final class Application {
|
||||
RedkaleClassLoader.putServiceLoader(ClusterAgentProvider.class);
|
||||
while (it.hasNext()) {
|
||||
ClusterAgentProvider provider = it.next();
|
||||
if (provider != null) RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); //loader class
|
||||
if (provider != null) {
|
||||
RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); //loader class
|
||||
}
|
||||
if (provider != null && provider.acceptsConf(clusterConf)) {
|
||||
cluster = provider.createInstance();
|
||||
cluster.setConfig(clusterConf);
|
||||
@@ -492,7 +502,9 @@ public final class Application {
|
||||
cluster.setConfig(clusterConf);
|
||||
}
|
||||
}
|
||||
if (cluster == null) logger.log(Level.SEVERE, "load application cluster resource, but not found name='type' value error: " + clusterConf);
|
||||
if (cluster == null) {
|
||||
logger.log(Level.SEVERE, "load application cluster resource, but not found name='type' value error: " + clusterConf);
|
||||
}
|
||||
} else {
|
||||
Class type = classLoader.loadClass(classVal);
|
||||
if (!ClusterAgent.class.isAssignableFrom(type)) {
|
||||
@@ -516,13 +528,19 @@ public final class Application {
|
||||
for (int i = 0; i < mqConfs.length; i++) {
|
||||
AnyValue mqConf = mqConfs[i];
|
||||
String mqname = mqConf.getValue("name", "");
|
||||
if (mqnames.contains(mqname)) throw new RuntimeException("mq.name(" + mqname + ") is repeat");
|
||||
if (mqnames.contains(mqname)) {
|
||||
throw new RuntimeException("mq.name(" + mqname + ") is repeat");
|
||||
}
|
||||
mqnames.add(mqname);
|
||||
String namex = mqConf.getValue("names");
|
||||
if (namex != null && !namex.isEmpty()) {
|
||||
for (String n : namex.split(";")) {
|
||||
if (n.trim().isEmpty()) continue;
|
||||
if (mqnames.contains(n.trim())) throw new RuntimeException("mq.name(" + n.trim() + ") is repeat");
|
||||
if (n.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (mqnames.contains(n.trim())) {
|
||||
throw new RuntimeException("mq.name(" + n.trim() + ") is repeat");
|
||||
}
|
||||
mqnames.add(n.trim());
|
||||
}
|
||||
}
|
||||
@@ -533,14 +551,18 @@ public final class Application {
|
||||
RedkaleClassLoader.putServiceLoader(MessageAgentProvider.class);
|
||||
while (it.hasNext()) {
|
||||
MessageAgentProvider provider = it.next();
|
||||
if (provider != null) RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); //loader class
|
||||
if (provider != null) {
|
||||
RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); //loader class
|
||||
}
|
||||
if (provider != null && provider.acceptsConf(mqConf)) {
|
||||
mqs[i] = provider.createInstance();
|
||||
mqs[i].setConfig(mqConf);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mqs[i] == null) logger.log(Level.SEVERE, "load application mq resource, but not found name='value' value error: " + mqConf);
|
||||
if (mqs[i] == null) {
|
||||
logger.log(Level.SEVERE, "load application mq resource, but not found name='value' value error: " + mqConf);
|
||||
}
|
||||
} else {
|
||||
Class type = classLoader.loadClass(classVal);
|
||||
if (!MessageAgent.class.isAssignableFrom(type)) {
|
||||
@@ -561,7 +583,9 @@ public final class Application {
|
||||
ExecutorService workExecutor0 = null;
|
||||
ExecutorService clientExecutor;
|
||||
{
|
||||
if (executorConf == null) executorConf = DefaultAnyValue.create();
|
||||
if (executorConf == null) {
|
||||
executorConf = DefaultAnyValue.create();
|
||||
}
|
||||
final AtomicReference<ExecutorService> workref = new AtomicReference<>();
|
||||
final int executorThreads = executorConf.getIntValue("threads", Math.max(2, Utility.cpus()));
|
||||
boolean executorHash = executorConf.getBoolValue("hash");
|
||||
@@ -688,7 +712,9 @@ public final class Application {
|
||||
final Properties agentEnvs = new Properties();
|
||||
if (propertiesConf.getValue("load") != null) { //本地配置项文件加载
|
||||
for (String dfload : propertiesConf.getValue("load").split(";")) {
|
||||
if (dfload.trim().isEmpty()) continue;
|
||||
if (dfload.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
final URI df = RedkaleClassLoader.getConfResourceAsURI(configFromCache ? null : this.confPath.toString(), dfload.trim());
|
||||
if (df != null && (!"file".equals(df.getScheme()) || df.toString().contains("!") || new File(df).isFile())) {
|
||||
Properties ps = new Properties();
|
||||
@@ -756,7 +782,9 @@ public final class Application {
|
||||
for (AnyValue prop : propertiesConf.getAnyValues("property")) {
|
||||
String key = prop.getValue("name");
|
||||
String value = prop.getValue("value");
|
||||
if (key == null || value == null) continue;
|
||||
if (key == null || value == null) {
|
||||
continue;
|
||||
}
|
||||
oldEnvs.put(key, value);
|
||||
}
|
||||
agentEnvs.forEach((k, v) -> {
|
||||
@@ -835,7 +863,9 @@ public final class Application {
|
||||
for (AnyValue prop : propertiesConf.getAnyValues("property")) {
|
||||
String key = prop.getValue("name");
|
||||
String value = prop.getValue("value");
|
||||
if (key == null) continue;
|
||||
if (key == null) {
|
||||
continue;
|
||||
}
|
||||
value = value == null ? value : replaceValue(value);
|
||||
if (key.startsWith("system.property.")) {
|
||||
String propName = key.substring("system.property.".length());
|
||||
@@ -965,25 +995,33 @@ public final class Application {
|
||||
boolean supported = true;
|
||||
Logger l = logger;
|
||||
do {
|
||||
if (l.getHandlers() == null) break;
|
||||
if (l.getHandlers() == null) {
|
||||
break;
|
||||
}
|
||||
for (Handler handler : l.getHandlers()) {
|
||||
if (!(handler instanceof ConsoleHandler)) {
|
||||
supported = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!supported) break;
|
||||
if (!supported) {
|
||||
break;
|
||||
}
|
||||
} while ((l = l.getParent()) != null);
|
||||
//colour 颜色代号:背景颜色代号(41-46);前景色代号(31-36)
|
||||
//type 样式代号:0无;1加粗;3斜体;4下划线
|
||||
//String.format("\033[%d;%dm%s\033[0m", colour, type, content)
|
||||
if (supported) msg = "\033[" + color + (type > 0 ? (";" + type) : "") + "m" + msg + "\033[0m";
|
||||
if (supported) {
|
||||
msg = "\033[" + color + (type > 0 ? (";" + type) : "") + "m" + msg + "\033[0m";
|
||||
}
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
private String checkName(String name) { //不能含特殊字符
|
||||
if (name == null || name.isEmpty()) return name;
|
||||
if (name == null || name.isEmpty()) {
|
||||
return name;
|
||||
}
|
||||
for (char ch : name.toCharArray()) {
|
||||
if (!((ch >= '0' && ch <= '9') || ch == '_' || ch == '.' || ch == '-' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { //不能含特殊字符
|
||||
throw new RuntimeException("name only 0-9 a-z A-Z _ - . cannot begin 0-9");
|
||||
@@ -1006,10 +1044,16 @@ public final class Application {
|
||||
resName = res.name();
|
||||
} else {
|
||||
javax.annotation.Resource res2 = field.getAnnotation(javax.annotation.Resource.class);
|
||||
if (res2 != null) resName = res2.name();
|
||||
if (res2 != null) {
|
||||
resName = res2.name();
|
||||
}
|
||||
}
|
||||
if (resName == null) {
|
||||
return null;
|
||||
}
|
||||
if (srcObj instanceof Service && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不得注入
|
||||
}
|
||||
if (resName == null) return null;
|
||||
if (srcObj instanceof Service && Sncp.isRemote((Service) srcObj)) return null; //远程模式不得注入
|
||||
Class type = field.getType();
|
||||
if (type == Application.class) {
|
||||
field.set(srcObj, application);
|
||||
@@ -1025,7 +1069,9 @@ public final class Application {
|
||||
} else if (type == NodeSncpServer.class) {
|
||||
NodeServer server = null;
|
||||
for (NodeServer ns : application.getNodeServers()) {
|
||||
if (ns.getClass() != NodeSncpServer.class) continue;
|
||||
if (ns.getClass() != NodeSncpServer.class) {
|
||||
continue;
|
||||
}
|
||||
if (resName.equals(ns.server.getName())) {
|
||||
server = ns;
|
||||
break;
|
||||
@@ -1036,7 +1082,9 @@ public final class Application {
|
||||
} else if (type == NodeHttpServer.class) {
|
||||
NodeServer server = null;
|
||||
for (NodeServer ns : application.getNodeServers()) {
|
||||
if (ns.getClass() != NodeHttpServer.class) continue;
|
||||
if (ns.getClass() != NodeHttpServer.class) {
|
||||
continue;
|
||||
}
|
||||
if (resName.equals(ns.server.getName())) {
|
||||
server = ns;
|
||||
break;
|
||||
@@ -1047,7 +1095,9 @@ public final class Application {
|
||||
} else if (type == NodeWatchServer.class) {
|
||||
NodeServer server = null;
|
||||
for (NodeServer ns : application.getNodeServers()) {
|
||||
if (ns.getClass() != NodeWatchServer.class) continue;
|
||||
if (ns.getClass() != NodeWatchServer.class) {
|
||||
continue;
|
||||
}
|
||||
if (resName.equals(ns.server.getName())) {
|
||||
server = ns;
|
||||
break;
|
||||
@@ -1116,7 +1166,9 @@ public final class Application {
|
||||
((AsyncIOGroup) this.clientAsyncGroup).start();
|
||||
}
|
||||
if (this.clusterAgent != null) {
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "ClusterAgent (type = " + this.clusterAgent.getClass().getSimpleName() + ") initing");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "ClusterAgent (type = " + this.clusterAgent.getClass().getSimpleName() + ") initing");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
if (this.clusterAgent instanceof CacheClusterAgent) {
|
||||
String sourceName = ((CacheClusterAgent) clusterAgent).getSourceName(); //必须在inject前调用,需要赋值Resourcable.name
|
||||
@@ -1129,7 +1181,9 @@ public final class Application {
|
||||
logger.info("ClusterAgent (type = " + this.clusterAgent.getClass().getSimpleName() + ") init in " + (System.currentTimeMillis() - s) + " ms");
|
||||
}
|
||||
if (this.messageAgents != null) {
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "MessageAgent initing");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "MessageAgent initing");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
for (MessageAgent agent : this.messageAgents) {
|
||||
this.resourceFactory.inject(agent);
|
||||
@@ -1194,14 +1248,20 @@ public final class Application {
|
||||
synchronized (cacheSources) {
|
||||
long st = System.currentTimeMillis();
|
||||
CacheSource old = resourceFactory.find(sourceName, CacheSource.class);
|
||||
if (old != null) return old;
|
||||
if (old != null) {
|
||||
return old;
|
||||
}
|
||||
final AnyValue sourceConf = findSourceConfig(sourceName, "cachesource");
|
||||
if (sourceConf == null) {
|
||||
if (!autoMemory) return null;
|
||||
if (!autoMemory) {
|
||||
return null;
|
||||
}
|
||||
CacheSource source = new CacheMemorySource(sourceName);
|
||||
cacheSources.add(source);
|
||||
resourceFactory.register(sourceName, CacheSource.class, source);
|
||||
if (!compileMode && source instanceof Service) ((Service) source).init(sourceConf);
|
||||
if (!compileMode && source instanceof Service) {
|
||||
((Service) source).init(sourceConf);
|
||||
}
|
||||
logger.info("Load CacheSource resourceName = " + sourceName + ", source = " + source + " in " + (System.currentTimeMillis() - st) + " ms");
|
||||
return source;
|
||||
}
|
||||
@@ -1223,10 +1283,14 @@ public final class Application {
|
||||
DataSource loadDataSource(final String sourceName, boolean autoMemory) {
|
||||
synchronized (dataSources) {
|
||||
DataSource old = resourceFactory.find(sourceName, DataSource.class);
|
||||
if (old != null) return old;
|
||||
if (old != null) {
|
||||
return old;
|
||||
}
|
||||
final AnyValue sourceConf = findSourceConfig(sourceName, "datasource");
|
||||
if (sourceConf == null) {
|
||||
if (!autoMemory) return null;
|
||||
if (!autoMemory) {
|
||||
return null;
|
||||
}
|
||||
DataSource source = new DataMemorySource(sourceName);
|
||||
if (!compileMode && source instanceof Service) {
|
||||
resourceFactory.inject(sourceName, source);
|
||||
@@ -1273,9 +1337,13 @@ public final class Application {
|
||||
}
|
||||
for (AnyValue conf : config.getAnyValues("listener")) {
|
||||
final String listenClass = conf.getValue("value", "");
|
||||
if (listenClass.isEmpty()) continue;
|
||||
if (listenClass.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Class clazz = classLoader.loadClass(listenClass);
|
||||
if (!ApplicationListener.class.isAssignableFrom(clazz)) continue;
|
||||
if (!ApplicationListener.class.isAssignableFrom(clazz)) {
|
||||
continue;
|
||||
}
|
||||
RedkaleClassLoader.putReflectionDeclaredConstructors(clazz, clazz.getName());
|
||||
@SuppressWarnings("unchecked")
|
||||
ApplicationListener listener = (ApplicationListener) clazz.getDeclaredConstructor().newInstance();
|
||||
@@ -1303,7 +1371,9 @@ public final class Application {
|
||||
channel.configureBlocking(true);
|
||||
channel.socket().setSoTimeout(3000);
|
||||
channel.bind(new InetSocketAddress("127.0.0.1", config.getIntValue("port")));
|
||||
if (!singletonMode) signalShutdownHandle();
|
||||
if (!singletonMode) {
|
||||
signalShutdownHandle();
|
||||
}
|
||||
boolean loop = true;
|
||||
final ByteBuffer buffer = ByteBuffer.allocateDirect(UDP_CAPACITY);
|
||||
while (loop) {
|
||||
@@ -1332,7 +1402,9 @@ public final class Application {
|
||||
} else if ("APIDOC".equalsIgnoreCase(cmd)) {
|
||||
try {
|
||||
String rs = new ApiDocCommand(application).command(cmd, params);
|
||||
if (rs == null || rs.isEmpty()) rs = "\r\n";
|
||||
if (rs == null || rs.isEmpty()) {
|
||||
rs = "\r\n";
|
||||
}
|
||||
sendUdpData(channel, address, buffer, rs.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (Exception ex) {
|
||||
sendUdpData(channel, address, buffer, "apidoc fail".getBytes(StandardCharsets.UTF_8));
|
||||
@@ -1351,7 +1423,9 @@ public final class Application {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (sb.length() == 0) sb.append("\r\n");
|
||||
if (sb.length() == 0) {
|
||||
sb.append("\r\n");
|
||||
}
|
||||
sendUdpData(channel, address, buffer, sb.toString().getBytes(StandardCharsets.UTF_8));
|
||||
long e = System.currentTimeMillis() - s;
|
||||
logger.info(application.getClass().getSimpleName() + " command in " + e + " ms");
|
||||
@@ -1371,13 +1445,17 @@ public final class Application {
|
||||
int count = (bytes.length + 4) / UDP_CAPACITY + ((bytes.length + 4) % UDP_CAPACITY > 0 ? 1 : 0);
|
||||
int start = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
if (start == 0) buffer.putInt(bytes.length);
|
||||
if (start == 0) {
|
||||
buffer.putInt(bytes.length);
|
||||
}
|
||||
int len = Math.min(buffer.remaining(), bytes.length - start);
|
||||
buffer.put(bytes, start, len);
|
||||
buffer.flip();
|
||||
boolean first = true;
|
||||
while (buffer.hasRemaining()) {
|
||||
if (!first) Utility.sleep(10);
|
||||
if (!first) {
|
||||
Utility.sleep(10);
|
||||
}
|
||||
if (dest == null) {
|
||||
channel.write(buffer);
|
||||
} else {
|
||||
@@ -1426,7 +1504,9 @@ public final class Application {
|
||||
//命令和参数合成一个数组
|
||||
String[] args = new String[1 + (params == null ? 0 : params.length)];
|
||||
args[0] = cmd;
|
||||
if (params != null) System.arraycopy(params, 0, args, 1, params.length);
|
||||
if (params != null) {
|
||||
System.arraycopy(params, 0, args, 1, params.length);
|
||||
}
|
||||
final ByteBuffer buffer = ByteBuffer.allocateDirect(UDP_CAPACITY);
|
||||
try {
|
||||
sendUdpData(channel, dest, buffer, JsonConvert.root().convertToBytes(args));
|
||||
@@ -1434,7 +1514,9 @@ public final class Application {
|
||||
readUdpData(channel, buffer, out);
|
||||
channel.close();
|
||||
String rs = out.toString(StandardCharsets.UTF_8).trim();
|
||||
if (logger != null) logger.info("Send: " + cmd + ", Reply: " + rs);
|
||||
if (logger != null) {
|
||||
logger.info("Send: " + cmd + ", Reply: " + rs);
|
||||
}
|
||||
System.out.println(rs);
|
||||
} catch (Exception e) {
|
||||
if (e instanceof PortUnreachableException) {
|
||||
@@ -1444,7 +1526,9 @@ public final class Application {
|
||||
application.start();
|
||||
String rs = new ApiDocCommand(application).command(cmd, params);
|
||||
application.shutdown();
|
||||
if (logger != null) logger.info(rs);
|
||||
if (logger != null) {
|
||||
logger.info(rs);
|
||||
}
|
||||
System.out.println(rs);
|
||||
return;
|
||||
}
|
||||
@@ -1482,16 +1566,22 @@ public final class Application {
|
||||
others.add(entry);
|
||||
}
|
||||
}
|
||||
if (watchs.size() > 1) throw new RuntimeException("Found one more WATCH Server");
|
||||
if (watchs.size() > 1) {
|
||||
throw new RuntimeException("Found one more WATCH Server");
|
||||
}
|
||||
this.watching = !watchs.isEmpty();
|
||||
|
||||
runServers(timecd, sncps); //必须确保SNCP服务都启动后再启动其他服务
|
||||
runServers(timecd, others);
|
||||
runServers(timecd, watchs); //必须在所有服务都启动后再启动WATCH服务
|
||||
timecd.await();
|
||||
if (this.clusterAgent != null) this.clusterAgent.start();
|
||||
if (this.clusterAgent != null) {
|
||||
this.clusterAgent.start();
|
||||
}
|
||||
if (this.messageAgents != null) {
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "MessageAgent starting");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "MessageAgent starting");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
final StringBuffer sb = new StringBuffer();
|
||||
Set<String> names = new HashSet<>();
|
||||
@@ -1500,12 +1590,16 @@ public final class Application {
|
||||
Map<String, Long> map = agent.start().join();
|
||||
AtomicInteger maxlen = new AtomicInteger();
|
||||
map.keySet().forEach(str -> {
|
||||
if (str.length() > maxlen.get()) maxlen.set(str.length());
|
||||
if (str.length() > maxlen.get()) {
|
||||
maxlen.set(str.length());
|
||||
}
|
||||
});
|
||||
new TreeMap<>(map).forEach((topic, ms) -> sb.append("MessageConsumer(topic=").append(alignString(topic, maxlen.get())).append(") init and start in ").append(ms).append(" ms\r\n")
|
||||
);
|
||||
}
|
||||
if (sb.length() > 0) logger.info(sb.toString().trim());
|
||||
if (sb.length() > 0) {
|
||||
logger.info(sb.toString().trim());
|
||||
}
|
||||
logger.info("MessageAgent(names=" + JsonConvert.root().convertTo(names) + ") start in " + (System.currentTimeMillis() - s) + " ms");
|
||||
}
|
||||
long intms = System.currentTimeMillis() - startTime;
|
||||
@@ -1517,7 +1611,9 @@ public final class Application {
|
||||
for (ApplicationListener listener : this.listeners) {
|
||||
listener.postStart(this);
|
||||
}
|
||||
if (!singletonMode && !compileMode) this.shutdownLatch.await();
|
||||
if (!singletonMode && !compileMode) {
|
||||
this.shutdownLatch.await();
|
||||
}
|
||||
}
|
||||
|
||||
private static String alignString(String value, int maxlen) {
|
||||
@@ -1532,7 +1628,9 @@ public final class Application {
|
||||
//使用了nohup或使用了后台&,Runtime.getRuntime().addShutdownHook失效
|
||||
private void signalShutdownHandle() {
|
||||
Consumer<Consumer<String>> signalShutdownConsumer = Utility.signalShutdownConsumer();
|
||||
if (signalShutdownConsumer == null) return;
|
||||
if (signalShutdownConsumer == null) {
|
||||
return;
|
||||
}
|
||||
signalShutdownConsumer.accept(sig -> {
|
||||
try {
|
||||
long s = System.currentTimeMillis();
|
||||
@@ -1592,7 +1690,9 @@ public final class Application {
|
||||
final Class<? extends NodeServer> type = entry.getType();
|
||||
NodeProtocol pros = type.getAnnotation(NodeProtocol.class);
|
||||
String p = pros.value().toUpperCase();
|
||||
if ("SNCP".equals(p) || "HTTP".equals(p)) continue;
|
||||
if ("SNCP".equals(p) || "HTTP".equals(p)) {
|
||||
continue;
|
||||
}
|
||||
final Class<? extends NodeServer> old = nodeClasses.get(p);
|
||||
if (old != null && old != type) {
|
||||
throw new RuntimeException("Protocol(" + p + ") had NodeServer-Class(" + old.getName() + ") but repeat NodeServer-Class(" + type.getName() + ")");
|
||||
@@ -1658,13 +1758,17 @@ public final class Application {
|
||||
* @throws Exception 异常
|
||||
*/
|
||||
public static <T extends Service> T singleton(String name, Class<T> serviceClass, Class<? extends Service>... extServiceClasses) throws Exception {
|
||||
if (serviceClass == null) throw new IllegalArgumentException("serviceClass is null");
|
||||
if (serviceClass == null) {
|
||||
throw new IllegalArgumentException("serviceClass is null");
|
||||
}
|
||||
final Application application = Application.create(true);
|
||||
System.setProperty("red" + "kale.singleton.serviceclass", serviceClass.getName());
|
||||
if (extServiceClasses != null && extServiceClasses.length > 0) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Class clazz : extServiceClasses) {
|
||||
if (sb.length() > 0) sb.append(',');
|
||||
if (sb.length() > 0) {
|
||||
sb.append(',');
|
||||
}
|
||||
sb.append(clazz.getName());
|
||||
}
|
||||
System.setProperty("red" + "kale.singleton.extserviceclasses", sb.toString());
|
||||
@@ -1673,7 +1777,9 @@ public final class Application {
|
||||
application.start();
|
||||
for (NodeServer server : application.servers) {
|
||||
T service = server.resourceFactory.find(name, serviceClass);
|
||||
if (service != null) return service;
|
||||
if (service != null) {
|
||||
return service;
|
||||
}
|
||||
}
|
||||
if (Modifier.isAbstract(serviceClass.getModifiers())) {
|
||||
throw new IllegalArgumentException("abstract class not allowed");
|
||||
@@ -1767,7 +1873,9 @@ public final class Application {
|
||||
} else {
|
||||
conf = AnyValue.loadFromProperties(text).getAnyValue("redkale");
|
||||
}
|
||||
if (fromCache) ((DefaultAnyValue) conf).addValue("[config-from-cache]", "true");
|
||||
if (fromCache) {
|
||||
((DefaultAnyValue) conf).addValue("[config-from-cache]", "true");
|
||||
}
|
||||
|
||||
return conf;
|
||||
}
|
||||
@@ -1821,7 +1929,9 @@ public final class Application {
|
||||
boolean restart = "restart".equalsIgnoreCase(cmd);
|
||||
AnyValue config = loadAppConfig();
|
||||
Application.sendCommand(null, config.getIntValue("port"), restart ? "SHUTDOWN" : cmd, params);
|
||||
if (!restart) return;
|
||||
if (!restart) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
//PrepareCompiler.main(args); //测试代码
|
||||
@@ -1846,7 +1956,9 @@ public final class Application {
|
||||
}
|
||||
|
||||
void updateEnvironmentProperties(String namespace, List<ResourceEvent> events) {
|
||||
if (events == null || events.isEmpty()) return;
|
||||
if (events == null || events.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
synchronized (envProperties) {
|
||||
Properties envRegisterProps = new Properties();
|
||||
Set<String> envRemovedKeys = new HashSet<>();
|
||||
@@ -1998,7 +2110,9 @@ public final class Application {
|
||||
//更新缓存
|
||||
for (String sourceName : cacheSourceNames) {
|
||||
CacheSource source = Utility.find(cacheSources, s -> Objects.equals(s.resourceName(), sourceName));
|
||||
if (source == null) continue; //多余的数据源
|
||||
if (source == null) {
|
||||
continue; //多余的数据源
|
||||
}
|
||||
final DefaultAnyValue old = (DefaultAnyValue) findSourceConfig(sourceName, "cachesource");
|
||||
Properties newProps = new Properties();
|
||||
this.sourceProperties.forEach((k, v) -> {
|
||||
@@ -2009,7 +2123,9 @@ public final class Application {
|
||||
prefix = "redkale.cachesource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
});
|
||||
List<ResourceEvent> changeEvents = new ArrayList<>();
|
||||
@@ -2021,7 +2137,9 @@ public final class Application {
|
||||
prefix = "redkale.cachesource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), v, this.sourceProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2033,7 +2151,9 @@ public final class Application {
|
||||
prefix = "redkale.cachesource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return;
|
||||
if (pos < 0) {
|
||||
return;
|
||||
}
|
||||
newProps.remove(k); //不是同一name数据源配置项
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), null, this.sourceProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2051,7 +2171,9 @@ public final class Application {
|
||||
//更新数据库
|
||||
for (String sourceName : dataSourceNames) {
|
||||
DataSource source = Utility.find(dataSources, s -> Objects.equals(s.resourceName(), sourceName));
|
||||
if (source == null) continue; //多余的数据源
|
||||
if (source == null) {
|
||||
continue; //多余的数据源
|
||||
}
|
||||
DefaultAnyValue old = (DefaultAnyValue) findSourceConfig(sourceName, "datasource");
|
||||
Properties newProps = new Properties();
|
||||
this.sourceProperties.forEach((k, v) -> {
|
||||
@@ -2062,7 +2184,9 @@ public final class Application {
|
||||
prefix = "redkale.datasource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
});
|
||||
List<ResourceEvent> changeEvents = new ArrayList<>();
|
||||
@@ -2074,7 +2198,9 @@ public final class Application {
|
||||
prefix = "redkale.datasource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), v, this.sourceProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2086,7 +2212,9 @@ public final class Application {
|
||||
prefix = "redkale.datasource." + sourceName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return;
|
||||
if (pos < 0) {
|
||||
return;
|
||||
}
|
||||
newProps.remove(k); //不是同一name数据源配置项
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), null, this.sourceProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2121,7 +2249,9 @@ public final class Application {
|
||||
//更新MQ
|
||||
for (String mqName : messageNames) {
|
||||
MessageAgent agent = Utility.find(messageAgents, s -> Objects.equals(s.resourceName(), mqName));
|
||||
if (agent == null) continue; //多余的数据源
|
||||
if (agent == null) {
|
||||
continue; //多余的数据源
|
||||
}
|
||||
final DefaultAnyValue old = (DefaultAnyValue) findMQConfig(mqName);
|
||||
Properties newProps = new Properties();
|
||||
this.messageProperties.forEach((k, v) -> {
|
||||
@@ -2132,7 +2262,9 @@ public final class Application {
|
||||
prefix = "redkale.mq." + mqName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
});
|
||||
List<ResourceEvent> changeEvents = new ArrayList<>();
|
||||
@@ -2144,7 +2276,9 @@ public final class Application {
|
||||
prefix = "redkale.mq." + mqName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return; //不是同一name数据源配置项
|
||||
if (pos < 0) {
|
||||
return; //不是同一name数据源配置项
|
||||
}
|
||||
newProps.put(k, v);
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), v, this.messageProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2156,7 +2290,9 @@ public final class Application {
|
||||
prefix = "redkale.mq." + mqName + ".";
|
||||
pos = key.indexOf(prefix);
|
||||
}
|
||||
if (pos < 0) return;
|
||||
if (pos < 0) {
|
||||
return;
|
||||
}
|
||||
newProps.remove(k); //不是同一name数据源配置项
|
||||
changeEvents.add(ResourceEvent.create(key.substring(prefix.length()), null, this.messageProperties.getProperty(key)));
|
||||
});
|
||||
@@ -2251,7 +2387,9 @@ public final class Application {
|
||||
localServers.stream().forEach((server) -> {
|
||||
try {
|
||||
List<Object> rs = server.command(cmd, params);
|
||||
if (rs != null) results.addAll(rs);
|
||||
if (rs != null) {
|
||||
results.addAll(rs);
|
||||
}
|
||||
} catch (Exception t) {
|
||||
logger.log(Level.WARNING, " command server(" + server.getSocketAddress() + ") error", t);
|
||||
}
|
||||
@@ -2271,7 +2409,9 @@ public final class Application {
|
||||
Collections.reverse(localServers); //倒序, 必须让watchs先关闭,watch包含服务发现和注销逻辑
|
||||
if (isCompileMode() && this.messageAgents != null) {
|
||||
Set<String> names = new HashSet<>();
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "MessageAgent stopping");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "MessageAgent stopping");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
for (MessageAgent agent : this.messageAgents) {
|
||||
names.add(agent.getName());
|
||||
@@ -2280,7 +2420,9 @@ public final class Application {
|
||||
logger.info("MessageAgent(names=" + JsonConvert.root().convertTo(names) + ") stop in " + (System.currentTimeMillis() - s) + " ms");
|
||||
}
|
||||
if (!isCompileMode() && clusterAgent != null) {
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "ClusterAgent destroying");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "ClusterAgent destroying");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
clusterAgent.deregister(this);
|
||||
clusterAgent.destroy(clusterAgent.getConfig());
|
||||
@@ -2297,7 +2439,9 @@ public final class Application {
|
||||
});
|
||||
if (this.messageAgents != null) {
|
||||
Set<String> names = new HashSet<>();
|
||||
if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "MessageAgent destroying");
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
logger.log(Level.FINER, "MessageAgent destroying");
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
for (MessageAgent agent : this.messageAgents) {
|
||||
names.add(agent.getName());
|
||||
@@ -2306,7 +2450,9 @@ public final class Application {
|
||||
logger.info("MessageAgent(names=" + JsonConvert.root().convertTo(names) + ") destroy in " + (System.currentTimeMillis() - s) + " ms");
|
||||
}
|
||||
for (DataSource source : dataSources) {
|
||||
if (source == null) continue;
|
||||
if (source == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (source instanceof Service) {
|
||||
long s = System.currentTimeMillis();
|
||||
@@ -2321,7 +2467,9 @@ public final class Application {
|
||||
}
|
||||
}
|
||||
for (CacheSource source : cacheSources) {
|
||||
if (source == null) continue;
|
||||
if (source == null) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (source instanceof Service) {
|
||||
long s = System.currentTimeMillis();
|
||||
@@ -2369,9 +2517,13 @@ public final class Application {
|
||||
}
|
||||
|
||||
public MessageAgent getMessageAgent(String name) {
|
||||
if (messageAgents == null) return null;
|
||||
if (messageAgents == null) {
|
||||
return null;
|
||||
}
|
||||
for (MessageAgent agent : messageAgents) {
|
||||
if (agent.getName().equals(name)) return agent;
|
||||
if (agent.getName().equals(name)) {
|
||||
return agent;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -2433,11 +2585,19 @@ public final class Application {
|
||||
}
|
||||
|
||||
private static int parseLenth(String value, int defValue) {
|
||||
if (value == null) return defValue;
|
||||
if (value == null) {
|
||||
return defValue;
|
||||
}
|
||||
value = value.toUpperCase().replace("B", "");
|
||||
if (value.endsWith("G")) return Integer.decode(value.replace("G", "")) * 1024 * 1024 * 1024;
|
||||
if (value.endsWith("M")) return Integer.decode(value.replace("M", "")) * 1024 * 1024;
|
||||
if (value.endsWith("K")) return Integer.decode(value.replace("K", "")) * 1024;
|
||||
if (value.endsWith("G")) {
|
||||
return Integer.decode(value.replace("G", "")) * 1024 * 1024 * 1024;
|
||||
}
|
||||
if (value.endsWith("M")) {
|
||||
return Integer.decode(value.replace("M", "")) * 1024 * 1024;
|
||||
}
|
||||
if (value.endsWith("K")) {
|
||||
return Integer.decode(value.replace("K", "")) * 1024;
|
||||
}
|
||||
return Integer.decode(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,9 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
|
||||
@Override
|
||||
public void publish(LogRecord log) {
|
||||
if (denyRegx != null && denyRegx.matcher(log.getMessage()).find()) return;
|
||||
if (denyRegx != null && denyRegx.matcher(log.getMessage()).find()) {
|
||||
return;
|
||||
}
|
||||
fillLogRecord(log);
|
||||
super.publish(log);
|
||||
}
|
||||
@@ -136,7 +138,9 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
cal.set(Calendar.MILLISECOND, 0);
|
||||
cal.add(Calendar.DAY_OF_YEAR, 1);
|
||||
long t = cal.getTimeInMillis();
|
||||
if (this.tomorrow != t) logindex.set(0);
|
||||
if (this.tomorrow != t) {
|
||||
logindex.set(0);
|
||||
}
|
||||
this.tomorrow = t;
|
||||
}
|
||||
|
||||
@@ -162,11 +166,15 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
if (bigger) {
|
||||
for (int i = Math.min(count - 2, logindex.get() - 1); i > 0; i--) {
|
||||
File greater = new File(logfile.getPath() + "." + i);
|
||||
if (greater.exists()) Files.move(greater.toPath(), new File(logfile.getPath() + "." + (i + 1)).toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
if (greater.exists()) {
|
||||
Files.move(greater.toPath(), new File(logfile.getPath() + "." + (i + 1)).toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
}
|
||||
}
|
||||
Files.move(logfile.toPath(), new File(logfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
} else {
|
||||
if (logfile.exists() && logfile.length() < 1) logfile.delete();
|
||||
if (logfile.exists() && logfile.length() < 1) {
|
||||
logfile.delete();
|
||||
}
|
||||
}
|
||||
logstream = null;
|
||||
}
|
||||
@@ -176,11 +184,15 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
if (limit > 0 && limit <= logunusuallength.get()) {
|
||||
for (int i = Math.min(count - 2, logunusualindex.get() - 1); i > 0; i--) {
|
||||
File greater = new File(logunusualfile.getPath() + "." + i);
|
||||
if (greater.exists()) Files.move(greater.toPath(), new File(logunusualfile.getPath() + "." + (i + 1)).toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
if (greater.exists()) {
|
||||
Files.move(greater.toPath(), new File(logunusualfile.getPath() + "." + (i + 1)).toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
}
|
||||
}
|
||||
Files.move(logunusualfile.toPath(), new File(logunusualfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
|
||||
} else {
|
||||
if (logunusualfile.exists() && logunusualfile.length() < 1) logunusualfile.delete();
|
||||
if (logunusualfile.exists() && logunusualfile.length() < 1) {
|
||||
logunusualfile.delete();
|
||||
}
|
||||
}
|
||||
logunusualstream = null;
|
||||
}
|
||||
@@ -210,7 +222,9 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ErrorManager err = getErrorManager();
|
||||
if (err != null) err.error(null, e, ErrorManager.WRITE_FAILURE);
|
||||
if (err != null) {
|
||||
err.error(null, e, ErrorManager.WRITE_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,12 +288,16 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
}
|
||||
String countstr = manager.getProperty(cname + ".count");
|
||||
try {
|
||||
if (countstr != null) this.count = Math.max(1, Math.abs(Integer.decode(countstr)));
|
||||
if (countstr != null) {
|
||||
this.count = Math.max(1, Math.abs(Integer.decode(countstr)));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
String appendstr = manager.getProperty(cname + ".append");
|
||||
try {
|
||||
if (appendstr != null) this.append = "true".equalsIgnoreCase(appendstr) || "1".equals(appendstr);
|
||||
if (appendstr != null) {
|
||||
this.append = "true".equalsIgnoreCase(appendstr) || "1".equals(appendstr);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
String levelstr = manager.getProperty(cname + ".level");
|
||||
@@ -308,11 +326,15 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (getFormatter() == null) setFormatter(new SimpleFormatter());
|
||||
if (getFormatter() == null) {
|
||||
setFormatter(new SimpleFormatter());
|
||||
}
|
||||
|
||||
String encodingstr = manager.getProperty(cname + ".encoding");
|
||||
try {
|
||||
if (encodingstr != null) setEncoding(encodingstr);
|
||||
if (encodingstr != null) {
|
||||
setEncoding(encodingstr);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
@@ -327,8 +349,12 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
|
||||
@Override
|
||||
public void publish(LogRecord log) {
|
||||
if (!isLoggable(log)) return;
|
||||
if (denyregx != null && denyregx.matcher(log.getMessage()).find()) return;
|
||||
if (!isLoggable(log)) {
|
||||
return;
|
||||
}
|
||||
if (denyregx != null && denyregx.matcher(log.getMessage()).find()) {
|
||||
return;
|
||||
}
|
||||
fillLogRecord(log);
|
||||
logqueue.offer(log);
|
||||
}
|
||||
@@ -336,20 +362,28 @@ public class LoggingFileHandler extends LoggingBaseHandler {
|
||||
@Override
|
||||
public void flush() {
|
||||
try {
|
||||
if (logstream != null) logstream.flush();
|
||||
if (logstream != null) {
|
||||
logstream.flush();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ErrorManager err = getErrorManager();
|
||||
if (err != null) err.error(null, e, ErrorManager.FLUSH_FAILURE);
|
||||
if (err != null) {
|
||||
err.error(null, e, ErrorManager.FLUSH_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws SecurityException {
|
||||
try {
|
||||
if (logstream != null) logstream.close();
|
||||
if (logstream != null) {
|
||||
logstream.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
ErrorManager err = getErrorManager();
|
||||
if (err != null) err.error(null, e, ErrorManager.CLOSE_FAILURE);
|
||||
if (err != null) {
|
||||
err.error(null, e, ErrorManager.CLOSE_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -90,13 +90,17 @@ public class NodeHttpServer extends NodeServer {
|
||||
|
||||
@Override
|
||||
protected void loadFilter(ClassFilter<? extends Filter> filterFilter, ClassFilter otherFilter) throws Exception {
|
||||
if (httpServer != null) loadHttpFilter(filterFilter);
|
||||
if (httpServer != null) {
|
||||
loadHttpFilter(filterFilter);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void loadServlet(ClassFilter<? extends Servlet> servletFilter, ClassFilter otherFilter) throws Exception {
|
||||
if (httpServer != null) loadHttpServlet(servletFilter, otherFilter);
|
||||
if (httpServer != null) {
|
||||
loadHttpServlet(servletFilter, otherFilter);
|
||||
}
|
||||
}
|
||||
|
||||
private void initWebSocketService() {
|
||||
@@ -104,15 +108,23 @@ public class NodeHttpServer extends NodeServer {
|
||||
final ResourceFactory regFactory = application.getResourceFactory();
|
||||
resourceFactory.register((ResourceFactory rf, String srcResourceName, final Object srcObj, final String resourceName, Field field, Object attachment) -> { //主要用于单点的服务
|
||||
try {
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) return null;
|
||||
if (!(srcObj instanceof WebSocketServlet)) return null;
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) {
|
||||
return null;
|
||||
}
|
||||
if (!(srcObj instanceof WebSocketServlet)) {
|
||||
return null;
|
||||
}
|
||||
ResourceTypeLoader loader = null;
|
||||
ResourceFactory sncpResFactory = null;
|
||||
for (NodeServer ns : application.servers) {
|
||||
if (!ns.isSNCP()) continue;
|
||||
if (!ns.isSNCP()) {
|
||||
continue;
|
||||
}
|
||||
sncpResFactory = ns.resourceFactory;
|
||||
loader = sncpResFactory.findTypeLoader(WebSocketNode.class, field);
|
||||
if (loader != null) break;
|
||||
if (loader != null) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Service nodeService = null;
|
||||
if (loader != null) {
|
||||
@@ -158,15 +170,21 @@ public class NodeHttpServer extends NodeServer {
|
||||
List<FilterEntry<? extends Filter>> list = new ArrayList(classFilter.getFilterEntrys());
|
||||
for (FilterEntry<? extends Filter> en : list) {
|
||||
Class<HttpFilter> clazz = (Class<HttpFilter>) en.getType();
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) continue;
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
RedkaleClassLoader.putReflectionDeclaredConstructors(clazz, clazz.getName());
|
||||
final HttpFilter filter = clazz.getDeclaredConstructor().newInstance();
|
||||
resourceFactory.inject(filter, this);
|
||||
DefaultAnyValue filterConf = (DefaultAnyValue) en.getProperty();
|
||||
this.httpServer.addHttpFilter(filter, filterConf);
|
||||
if (sb != null) sb.append("Load ").append(clazz.getName()).append(LINE_SEPARATOR);
|
||||
if (sb != null) {
|
||||
sb.append("Load ").append(clazz.getName()).append(LINE_SEPARATOR);
|
||||
}
|
||||
}
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -177,8 +195,12 @@ public class NodeHttpServer extends NodeServer {
|
||||
final AnyValue servletsConf = this.serverConf.getAnyValue("servlets");
|
||||
final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
|
||||
String prefix0 = servletsConf == null ? "" : servletsConf.getValue("path", "");
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') prefix0 = prefix0.substring(0, prefix0.length() - 1);
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') prefix0 = '/' + prefix0;
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') {
|
||||
prefix0 = prefix0.substring(0, prefix0.length() - 1);
|
||||
}
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') {
|
||||
prefix0 = '/' + prefix0;
|
||||
}
|
||||
final String prefix = prefix0;
|
||||
List<FilterEntry<? extends Servlet>> list = new ArrayList(servletFilter.getFilterEntrys());
|
||||
list.sort((FilterEntry<? extends Servlet> o1, FilterEntry<? extends Servlet> o2) -> { //必须保证WebSocketServlet优先加载, 因为要确保其他的HttpServlet可以注入本地模式的WebSocketNode
|
||||
@@ -196,10 +218,16 @@ public class NodeHttpServer extends NodeServer {
|
||||
final List<AbstractMap.SimpleEntry<String, String[]>> ss = sb == null ? null : new ArrayList<>();
|
||||
for (FilterEntry<? extends Servlet> en : list) {
|
||||
Class<HttpServlet> clazz = (Class<HttpServlet>) en.getType();
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) continue;
|
||||
if (clazz.getAnnotation(Rest.RestDyn.class) != null) continue; //动态生成的跳过
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (clazz.getAnnotation(Rest.RestDyn.class) != null) {
|
||||
continue; //动态生成的跳过
|
||||
}
|
||||
WebServlet ws = clazz.getAnnotation(WebServlet.class);
|
||||
if (ws == null) continue;
|
||||
if (ws == null) {
|
||||
continue;
|
||||
}
|
||||
if (ws.value().length == 0) {
|
||||
logger.log(Level.INFO, "Not found @WebServlet.value in " + clazz.getName());
|
||||
continue;
|
||||
@@ -233,17 +261,25 @@ public class NodeHttpServer extends NodeServer {
|
||||
if (rests != null) {
|
||||
for (AbstractMap.SimpleEntry<String, String[]> en : rests) {
|
||||
int pos = en.getKey().indexOf('#');
|
||||
if (pos > maxTypeLength) maxTypeLength = pos;
|
||||
if (pos > maxTypeLength) {
|
||||
maxTypeLength = pos;
|
||||
}
|
||||
int len = en.getKey().length() - pos - 1;
|
||||
if (len > maxNameLength) maxNameLength = len;
|
||||
if (len > maxNameLength) {
|
||||
maxNameLength = len;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (webss != null) {
|
||||
for (AbstractMap.SimpleEntry<String, String[]> en : webss) {
|
||||
int pos = en.getKey().indexOf('#');
|
||||
if (pos > maxTypeLength) maxTypeLength = pos;
|
||||
if (pos > maxTypeLength) {
|
||||
maxTypeLength = pos;
|
||||
}
|
||||
int len = en.getKey().length() - pos - 1;
|
||||
if (len > maxNameLength) maxNameLength = len;
|
||||
if (len > maxNameLength) {
|
||||
maxNameLength = len;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rests != null) {
|
||||
@@ -280,7 +316,9 @@ public class NodeHttpServer extends NodeServer {
|
||||
}
|
||||
ss.sort((AbstractMap.SimpleEntry<String, String[]> o1, AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey()));
|
||||
for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
|
||||
if (as.getKey().length() > max) max = as.getKey().length();
|
||||
if (as.getKey().length() > max) {
|
||||
max = as.getKey().length();
|
||||
}
|
||||
}
|
||||
for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
|
||||
sb.append("Load ").append(as.getKey());
|
||||
@@ -291,27 +329,40 @@ public class NodeHttpServer extends NodeServer {
|
||||
}
|
||||
sb.append("All HttpServlets load in ").append(System.currentTimeMillis() - starts).append(" ms").append(LINE_SEPARATOR);
|
||||
}
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString().trim());
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString().trim());
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void loadRestServlet(final ClassFilter<? extends WebSocket> webSocketFilter, final AnyValue restConf, final List<Object> restedObjects, final StringBuilder sb,
|
||||
final List<AbstractMap.SimpleEntry<String, String[]>> rests, final List<AbstractMap.SimpleEntry<String, String[]>> webss) throws Exception {
|
||||
if (!rest) return;
|
||||
if (restConf == null) return; //不存在REST服务
|
||||
|
||||
if (!rest) {
|
||||
return;
|
||||
}
|
||||
if (restConf == null) {
|
||||
return; //不存在REST服务
|
||||
}
|
||||
String prefix0 = restConf.getValue("path", "");
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') prefix0 = prefix0.substring(0, prefix0.length() - 1);
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') prefix0 = '/' + prefix0;
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(prefix0.length() - 1) == '/') {
|
||||
prefix0 = prefix0.substring(0, prefix0.length() - 1);
|
||||
}
|
||||
if (!prefix0.isEmpty() && prefix0.charAt(0) != '/') {
|
||||
prefix0 = '/' + prefix0;
|
||||
}
|
||||
|
||||
String mqname = restConf.getValue("mq");
|
||||
MessageAgent agent0 = null;
|
||||
if (mqname != null) {
|
||||
agent0 = application.getMessageAgent(mqname);
|
||||
if (agent0 == null) throw new RuntimeException("not found " + MessageAgent.class.getSimpleName() + " config for (name=" + mqname + ")");
|
||||
if (agent0 == null) {
|
||||
throw new RuntimeException("not found " + MessageAgent.class.getSimpleName() + " config for (name=" + mqname + ")");
|
||||
}
|
||||
}
|
||||
final MessageAgent messageAgent = agent0;
|
||||
if (messageAgent != null) prefix0 = ""; //开启MQ时,prefix字段失效
|
||||
if (messageAgent != null) {
|
||||
prefix0 = ""; //开启MQ时,prefix字段失效
|
||||
}
|
||||
final String prefix = prefix0;
|
||||
final boolean autoload = restConf.getBoolValue("autoload", true);
|
||||
{ //加载RestService
|
||||
@@ -332,17 +383,25 @@ public class NodeHttpServer extends NodeServer {
|
||||
final ClassFilter restFilter = ClassFilter.create(serverClassLoader, null, application.isCompileMode() ? "" : restConf.getValue("includes", ""), application.isCompileMode() ? "" : restConf.getValue("excludes", ""), includeValues, excludeValues);
|
||||
final CountDownLatch scdl = new CountDownLatch(super.interceptorServices.size());
|
||||
Stream<Service> stream = super.interceptorServices.stream();
|
||||
if (!application.isCompileMode()) stream = stream.parallel(); //不能并行,否则在maven plugin运行环境下ClassLoader不对
|
||||
if (!application.isCompileMode()) {
|
||||
stream = stream.parallel(); //不能并行,否则在maven plugin运行环境下ClassLoader不对
|
||||
}
|
||||
stream.forEach((service) -> {
|
||||
try {
|
||||
final Class stype = Sncp.getServiceType(service);
|
||||
final String name = Sncp.getResourceName(service);
|
||||
RestService rs = (RestService) stype.getAnnotation(RestService.class);
|
||||
if (rs == null || rs.ignore()) return;
|
||||
if (rs == null || rs.ignore()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final String stypename = stype.getName();
|
||||
if (!autoload && !includeValues.contains(stypename)) return;
|
||||
if (!restFilter.accept(stypename)) return;
|
||||
if (!autoload && !includeValues.contains(stypename)) {
|
||||
return;
|
||||
}
|
||||
if (!restFilter.accept(stypename)) {
|
||||
return;
|
||||
}
|
||||
synchronized (restedObjects) {
|
||||
if (restedObjects.contains(service)) {
|
||||
logger.log(Level.WARNING, stype.getName() + " repeat create rest servlet, so ignore");
|
||||
@@ -351,13 +410,19 @@ public class NodeHttpServer extends NodeServer {
|
||||
restedObjects.add(service); //避免重复创建Rest对象
|
||||
}
|
||||
HttpServlet servlet = httpServer.addRestServlet(serverClassLoader, service, userType, baseServletType, prefix);
|
||||
if (servlet == null) return; //没有HttpMapping方法的HttpServlet调用Rest.createRestServlet就会返回null
|
||||
if (servlet == null) {
|
||||
return; //没有HttpMapping方法的HttpServlet调用Rest.createRestServlet就会返回null
|
||||
}
|
||||
String prefix2 = prefix;
|
||||
WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class);
|
||||
if (ws != null && !ws.repair()) prefix2 = "";
|
||||
if (ws != null && !ws.repair()) {
|
||||
prefix2 = "";
|
||||
}
|
||||
resourceFactory.inject(servlet, NodeHttpServer.this);
|
||||
dynServletMap.put(service, servlet);
|
||||
if (messageAgent != null) messageAgent.putService(this, service, servlet);
|
||||
if (messageAgent != null) {
|
||||
messageAgent.putService(this, service, servlet);
|
||||
}
|
||||
//if (finest) logger.finest("Create RestServlet(resource.name='" + name + "') = " + servlet);
|
||||
if (rests != null) {
|
||||
String[] mappings = servlet.getClass().getAnnotation(WebServlet.class).value();
|
||||
@@ -398,23 +463,35 @@ public class NodeHttpServer extends NodeServer {
|
||||
continue;
|
||||
}
|
||||
final Class<? extends WebSocket> stype = en.getType();
|
||||
if (stype.getAnnotation(Rest.RestDyn.class) != null) continue;
|
||||
if (stype.getAnnotation(Rest.RestDyn.class) != null) {
|
||||
continue;
|
||||
}
|
||||
RestWebSocket rs = stype.getAnnotation(RestWebSocket.class);
|
||||
if (rs == null || rs.ignore()) continue;
|
||||
if (rs == null || rs.ignore()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final String stypename = stype.getName();
|
||||
if (!autoload && !includeValues.contains(stypename)) continue;
|
||||
if (!restFilter.accept(stypename)) continue;
|
||||
if (!autoload && !includeValues.contains(stypename)) {
|
||||
continue;
|
||||
}
|
||||
if (!restFilter.accept(stypename)) {
|
||||
continue;
|
||||
}
|
||||
if (restedObjects.contains(stype)) {
|
||||
logger.log(Level.WARNING, stype.getName() + " repeat create rest websocket, so ignore");
|
||||
continue;
|
||||
}
|
||||
restedObjects.add(stype); //避免重复创建Rest对象
|
||||
WebSocketServlet servlet = httpServer.addRestWebSocketServlet(serverClassLoader, stype, messageAgent, prefix, en.getProperty());
|
||||
if (servlet == null) continue; //没有RestOnMessage方法的HttpServlet调用Rest.createRestWebSocketServlet就会返回null
|
||||
if (servlet == null) {
|
||||
continue; //没有RestOnMessage方法的HttpServlet调用Rest.createRestWebSocketServlet就会返回null
|
||||
}
|
||||
String prefix2 = prefix;
|
||||
WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class);
|
||||
if (ws != null && !ws.repair()) prefix2 = "";
|
||||
if (ws != null && !ws.repair()) {
|
||||
prefix2 = "";
|
||||
}
|
||||
resourceFactory.inject(servlet, NodeHttpServer.this);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.finest(stype.getName() + " create a RestWebSocketServlet");
|
||||
@@ -430,7 +507,9 @@ public class NodeHttpServer extends NodeServer {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (messageAgent != null) this.messageAgents.put(messageAgent.getName(), messageAgent);
|
||||
if (messageAgent != null) {
|
||||
this.messageAgents.put(messageAgent.getName(), messageAgent);
|
||||
}
|
||||
}
|
||||
|
||||
@Override //loadServlet执行之后调用
|
||||
@@ -439,8 +518,12 @@ public class NodeHttpServer extends NodeServer {
|
||||
if (!application.isCompileMode() && cluster != null) {
|
||||
NodeProtocol pros = getClass().getAnnotation(NodeProtocol.class);
|
||||
String protocol = pros.value().toUpperCase();
|
||||
if (!cluster.containsProtocol(protocol)) return;
|
||||
if (!cluster.containsPort(server.getSocketAddress().getPort())) return;
|
||||
if (!cluster.containsProtocol(protocol)) {
|
||||
return;
|
||||
}
|
||||
if (!cluster.containsPort(server.getSocketAddress().getPort())) {
|
||||
return;
|
||||
}
|
||||
cluster.register(this, protocol, dynServletMap.keySet(), new HashSet<>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,7 +139,9 @@ public abstract class NodeServer {
|
||||
this.resourceFactory.register(RESNAME_SNCP_ADDR, SocketAddress.class, this.sncpAddress);
|
||||
this.resourceFactory.register(RESNAME_SNCP_ADDR, String.class, this.sncpAddress.getHostString() + ":" + this.sncpAddress.getPort());
|
||||
}
|
||||
if (this.sncpGroup != null) this.resourceFactory.register(RESNAME_SNCP_GROUP, this.sncpGroup);
|
||||
if (this.sncpGroup != null) {
|
||||
this.resourceFactory.register(RESNAME_SNCP_GROUP, this.sncpGroup);
|
||||
}
|
||||
{
|
||||
//设置root文件夹
|
||||
String webroot = this.serverConf.getValue("root", "root");
|
||||
@@ -181,7 +183,9 @@ public abstract class NodeServer {
|
||||
sscList.add(ssc);
|
||||
if (extssc != null && !extssc.isEmpty()) {
|
||||
for (String s : extssc.split(",")) {
|
||||
if (!s.isEmpty()) sscList.add(s);
|
||||
if (!s.isEmpty()) {
|
||||
sscList.add(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
serviceFilter.setExpectPredicate(c -> !sscList.contains(c));
|
||||
@@ -200,7 +204,9 @@ public abstract class NodeServer {
|
||||
loadServlet(servletFilter, otherFilter);
|
||||
postLoadServlets();
|
||||
}
|
||||
if (this.interceptor != null) this.resourceFactory.inject(this.interceptor);
|
||||
if (this.interceptor != null) {
|
||||
this.resourceFactory.inject(this.interceptor);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void loadFilter(ClassFilter<? extends Filter> filterFilter, ClassFilter otherFilter) throws Exception;
|
||||
@@ -222,12 +228,20 @@ public abstract class NodeServer {
|
||||
resName = res.name();
|
||||
} else {
|
||||
javax.annotation.Resource res2 = field.getAnnotation(javax.annotation.Resource.class);
|
||||
if (res2 != null) resName = res2.name();
|
||||
if (res2 != null) {
|
||||
resName = res2.name();
|
||||
}
|
||||
}
|
||||
if (resName == null || !resName.startsWith("properties.")) {
|
||||
return null;
|
||||
}
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不得注入 DataSource
|
||||
}
|
||||
if (resName == null || !resName.startsWith("properties.")) return null;
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) return null; //远程模式不得注入 DataSource
|
||||
Class type = field.getType();
|
||||
if (type != AnyValue.class && type != AnyValue[].class) return null;
|
||||
if (type != AnyValue.class && type != AnyValue[].class) {
|
||||
return null;
|
||||
}
|
||||
Object resource = null;
|
||||
final AnyValue properties = application.getAppConfig().getAnyValue("properties");
|
||||
if (properties != null && type == AnyValue.class) {
|
||||
@@ -249,17 +263,31 @@ public abstract class NodeServer {
|
||||
resourceFactory.register((ResourceFactory rf, String srcResourceName, final Object srcObj, String resourceName, Field field, final Object attachment) -> {
|
||||
Class<Service> resServiceType = Service.class;
|
||||
try {
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) return null;
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) return null; //远程模式不得注入 AutoLoad Service
|
||||
if (!Service.class.isAssignableFrom(field.getType())) return null;
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) {
|
||||
return null;
|
||||
}
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不得注入 AutoLoad Service
|
||||
}
|
||||
if (!Service.class.isAssignableFrom(field.getType())) {
|
||||
return null;
|
||||
}
|
||||
resServiceType = (Class) field.getType();
|
||||
if (resServiceType.getAnnotation(Local.class) == null) return null;
|
||||
if (resServiceType.getAnnotation(Local.class) == null) {
|
||||
return null;
|
||||
}
|
||||
boolean auto = true;
|
||||
AutoLoad al = resServiceType.getAnnotation(AutoLoad.class);
|
||||
if (al != null) auto = al.value();
|
||||
if (al != null) {
|
||||
auto = al.value();
|
||||
}
|
||||
org.redkale.util.AutoLoad al2 = resServiceType.getAnnotation(org.redkale.util.AutoLoad.class);
|
||||
if (al2 != null) auto = al2.value();
|
||||
if (auto) return null;
|
||||
if (al2 != null) {
|
||||
auto = al2.value();
|
||||
}
|
||||
if (auto) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//ResourceFactory resfactory = (isSNCP() ? appResFactory : resourceFactory);
|
||||
SncpClient client = srcObj instanceof Service ? Sncp.getSncpClient((Service) srcObj) : null;
|
||||
@@ -270,7 +298,9 @@ public abstract class NodeServer {
|
||||
|
||||
field.set(srcObj, service);
|
||||
rf.inject(resourceName, service, self); // 给其可能包含@Resource的字段赋值;
|
||||
if (!application.isCompileMode()) service.init(null);
|
||||
if (!application.isCompileMode()) {
|
||||
service.init(null);
|
||||
}
|
||||
logger.info("Load Service(@Local @AutoLoad service = " + resServiceType.getSimpleName() + ", resourceName = '" + resourceName + "')");
|
||||
return service;
|
||||
} catch (Exception e) {
|
||||
@@ -282,8 +312,12 @@ public abstract class NodeServer {
|
||||
//------------------------------------- 注册 DataSource --------------------------------------------------------
|
||||
resourceFactory.register((ResourceFactory rf, String srcResourceName, final Object srcObj, String resourceName, Field field, final Object attachment) -> {
|
||||
try {
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) return null;
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) return null; //远程模式不得注入 DataSource
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) {
|
||||
return null;
|
||||
}
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不得注入 DataSource
|
||||
}
|
||||
DataSource source = application.loadDataSource(resourceName, false);
|
||||
field.set(srcObj, source);
|
||||
return source;
|
||||
@@ -298,8 +332,12 @@ public abstract class NodeServer {
|
||||
@Override
|
||||
public Object load(ResourceFactory rf, String srcResourceName, final Object srcObj, final String resourceName, Field field, final Object attachment) {
|
||||
try {
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) return null;
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) return null; //远程模式不需要注入 CacheSource
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) {
|
||||
return null;
|
||||
}
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不需要注入 CacheSource
|
||||
}
|
||||
if (!(srcObj instanceof Service)) {
|
||||
throw new RuntimeException("CacheSource must be inject in Service, cannot in " + srcObj);
|
||||
}
|
||||
@@ -336,8 +374,12 @@ public abstract class NodeServer {
|
||||
@Override
|
||||
public Object load(ResourceFactory rf, String srcResourceName, final Object srcObj, final String resourceName, Field field, final Object attachment) {
|
||||
try {
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) return null;
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) return null; //远程模式不需要注入 WebSocketNode
|
||||
if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) {
|
||||
return null;
|
||||
}
|
||||
if ((srcObj instanceof Service) && Sncp.isRemote((Service) srcObj)) {
|
||||
return null; //远程模式不需要注入 WebSocketNode
|
||||
}
|
||||
Service nodeService = (Service) rf.find(resourceName, WebSocketNode.class);
|
||||
MessageAgent messageAgent = null;
|
||||
if (srcObj instanceof Service) {
|
||||
@@ -354,7 +396,9 @@ public abstract class NodeServer {
|
||||
}
|
||||
if (nodeService == null) {
|
||||
final HashSet<String> groups = new HashSet<>();
|
||||
if (groups.isEmpty() && isSNCP() && NodeServer.this.sncpGroup != null) groups.add(NodeServer.this.sncpGroup);
|
||||
if (groups.isEmpty() && isSNCP() && NodeServer.this.sncpGroup != null) {
|
||||
groups.add(NodeServer.this.sncpGroup);
|
||||
}
|
||||
nodeService = Sncp.createLocalService(serverClassLoader, resourceName, org.redkale.net.http.WebSocketNodeService.class, messageAgent, application.getResourceFactory(), application.getSncpTransportFactory(), NodeServer.this.sncpAddress, groups, (AnyValue) null);
|
||||
(isSNCP() ? appResFactory : resourceFactory).register(resourceName, WebSocketNode.class, nodeService);
|
||||
((org.redkale.net.http.WebSocketNodeService) nodeService).setName(resourceName);
|
||||
@@ -370,7 +414,9 @@ public abstract class NodeServer {
|
||||
rf.inject(resourceName, nodeService); //动态加载的Service也存在按需加载的注入资源
|
||||
localServices.add(nodeService);
|
||||
interceptorServices.add(nodeService);
|
||||
if (consumer != null) consumer.accept(null, nodeService);
|
||||
if (consumer != null) {
|
||||
consumer.accept(null, nodeService);
|
||||
}
|
||||
}
|
||||
return nodeService;
|
||||
} catch (Exception e) {
|
||||
@@ -388,7 +434,9 @@ public abstract class NodeServer {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected void loadService(ClassFilter<? extends Service> serviceFilter, ClassFilter otherFilter) throws Exception {
|
||||
if (serviceFilter == null) return;
|
||||
if (serviceFilter == null) {
|
||||
return;
|
||||
}
|
||||
final long starts = System.currentTimeMillis();
|
||||
final Set<FilterEntry<? extends Service>> entrys = (Set) serviceFilter.getAllFilterEntrys();
|
||||
ResourceFactory regFactory = isSNCP() ? application.getResourceFactory() : resourceFactory;
|
||||
@@ -397,28 +445,48 @@ public abstract class NodeServer {
|
||||
final AtomicInteger serviceCount = new AtomicInteger();
|
||||
for (FilterEntry<? extends Service> entry : entrys) { //service实现类
|
||||
final Class<? extends Service> serviceImplClass = entry.getType();
|
||||
if (Modifier.isFinal(serviceImplClass.getModifiers())) continue; //修饰final的类跳过
|
||||
if (!Modifier.isPublic(serviceImplClass.getModifiers())) continue;
|
||||
if (serviceImplClass.getAnnotation(SncpDyn.class) != null) continue; //动态生成的跳过
|
||||
if (entry.isExpect()) {
|
||||
if (Modifier.isAbstract(serviceImplClass.getModifiers())) continue; //修饰abstract的类跳过
|
||||
if (DataSource.class.isAssignableFrom(serviceImplClass)) continue;
|
||||
if (CacheSource.class.isAssignableFrom(serviceImplClass)) continue;
|
||||
if (Modifier.isFinal(serviceImplClass.getModifiers())) {
|
||||
continue; //修饰final的类跳过
|
||||
}
|
||||
if (!Modifier.isPublic(serviceImplClass.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (serviceImplClass.getAnnotation(SncpDyn.class) != null) {
|
||||
continue; //动态生成的跳过
|
||||
}
|
||||
if (entry.isExpect()) {
|
||||
if (Modifier.isAbstract(serviceImplClass.getModifiers())) {
|
||||
continue; //修饰abstract的类跳过
|
||||
}
|
||||
if (DataSource.class.isAssignableFrom(serviceImplClass)) {
|
||||
continue;
|
||||
}
|
||||
if (CacheSource.class.isAssignableFrom(serviceImplClass)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (entry.getName().contains("$")) {
|
||||
throw new RuntimeException("<name> value cannot contains '$' in " + entry.getProperty());
|
||||
}
|
||||
if (entry.getName().contains("$")) throw new RuntimeException("<name> value cannot contains '$' in " + entry.getProperty());
|
||||
Service oldother = resourceFactory.find(entry.getName(), serviceImplClass);
|
||||
if (oldother != null) { //Server加载Service时需要判断是否已经加载过了。
|
||||
if (!Sncp.isRemote(oldother)) interceptorServices.add(oldother);
|
||||
if (!Sncp.isRemote(oldother)) {
|
||||
interceptorServices.add(oldother);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
final HashSet<String> groups = entry.getGroups(); //groups.isEmpty()表示<services>没有配置groups属性。
|
||||
if (groups.isEmpty() && isSNCP() && this.sncpGroup != null) groups.add(this.sncpGroup);
|
||||
if (groups.isEmpty() && isSNCP() && this.sncpGroup != null) {
|
||||
groups.add(this.sncpGroup);
|
||||
}
|
||||
|
||||
final boolean localed = (this.sncpAddress == null && entry.isEmptyGroups() && !serviceImplClass.isInterface() && !Modifier.isAbstract(serviceImplClass.getModifiers())) //非SNCP的Server,通常是单点服务
|
||||
|| groups.contains(this.sncpGroup) //本地IP含在内的
|
||||
|| (this.sncpGroup == null && entry.isEmptyGroups()) //空的SNCP配置
|
||||
|| serviceImplClass.getAnnotation(Local.class) != null;//本地模式
|
||||
if (localed && (serviceImplClass.isInterface() || Modifier.isAbstract(serviceImplClass.getModifiers()))) continue; //本地模式不能实例化接口和抽象类的Service类
|
||||
if (localed && (serviceImplClass.isInterface() || Modifier.isAbstract(serviceImplClass.getModifiers()))) {
|
||||
continue; //本地模式不能实例化接口和抽象类的Service类
|
||||
}
|
||||
final ResourceTypeLoader resourceLoader = (ResourceFactory rf, String srcResourceName, final Object srcObj, final String resourceName, Field field, final Object attachment) -> {
|
||||
try {
|
||||
if (SncpClient.parseMethod(serviceImplClass).isEmpty()
|
||||
@@ -432,7 +500,9 @@ public abstract class NodeServer {
|
||||
MessageAgent agent = null;
|
||||
if (entry.getProperty() != null && entry.getProperty().getValue("mq") != null) {
|
||||
agent = application.getMessageAgent(entry.getProperty().getValue("mq"));
|
||||
if (agent != null) messageAgents.put(agent.getName(), agent);
|
||||
if (agent != null) {
|
||||
messageAgents.put(agent.getName(), agent);
|
||||
}
|
||||
}
|
||||
|
||||
Service service;
|
||||
@@ -444,7 +514,9 @@ public abstract class NodeServer {
|
||||
}
|
||||
if (service instanceof org.redkale.net.http.WebSocketNodeService) {
|
||||
((org.redkale.net.http.WebSocketNodeService) service).setName(resourceName);
|
||||
if (agent != null) Sncp.setMessageAgent(service, agent);
|
||||
if (agent != null) {
|
||||
Sncp.setMessageAgent(service, agent);
|
||||
}
|
||||
}
|
||||
final Class restype = Sncp.getResourceType(service);
|
||||
if (rf.find(resourceName, restype) == null) {
|
||||
@@ -454,12 +526,18 @@ public abstract class NodeServer {
|
||||
}
|
||||
if (Sncp.isRemote(service)) {
|
||||
remoteServices.add(service);
|
||||
if (agent != null) sncpRemoteAgents.put(agent.getName(), agent);
|
||||
if (agent != null) {
|
||||
sncpRemoteAgents.put(agent.getName(), agent);
|
||||
}
|
||||
} else {
|
||||
if (field != null) rf.inject(resourceName, service); //动态加载的Service也存在按需加载的注入资源
|
||||
if (field != null) {
|
||||
rf.inject(resourceName, service); //动态加载的Service也存在按需加载的注入资源
|
||||
}
|
||||
localServices.add(service);
|
||||
interceptorServices.add(service);
|
||||
if (consumer != null) consumer.accept(agent, service);
|
||||
if (consumer != null) {
|
||||
consumer.accept(agent, service);
|
||||
}
|
||||
}
|
||||
serviceCount.incrementAndGet();
|
||||
return service;
|
||||
@@ -512,9 +590,13 @@ public abstract class NodeServer {
|
||||
Priority p1 = o1.getClass().getAnnotation(Priority.class);
|
||||
Priority p2 = o2.getClass().getAnnotation(Priority.class);
|
||||
int v = (p2 == null ? 0 : p2.value()) - (p1 == null ? 0 : p1.value());
|
||||
if (v != 0) return v;
|
||||
if (v != 0) {
|
||||
return v;
|
||||
}
|
||||
int rs = Sncp.getResourceType(o1).getName().compareTo(Sncp.getResourceType(o2).getName());
|
||||
if (rs == 0) rs = Sncp.getResourceName(o1).compareTo(Sncp.getResourceName(o2));
|
||||
if (rs == 0) {
|
||||
rs = Sncp.getResourceName(o1).compareTo(Sncp.getResourceName(o2));
|
||||
}
|
||||
return rs;
|
||||
});
|
||||
localServices.clear();
|
||||
@@ -527,7 +609,9 @@ public abstract class NodeServer {
|
||||
if (application.isCompileMode()) {
|
||||
localServices.stream().forEach(y -> {
|
||||
String serstr = Sncp.toSimpleString(y, maxNameLength, maxTypeLength);
|
||||
if (slist != null) slist.add(new StringBuilder().append(serstr).append(" load").append(LINE_SEPARATOR).toString());
|
||||
if (slist != null) {
|
||||
slist.add(new StringBuilder().append(serstr).append(" load").append(LINE_SEPARATOR).toString());
|
||||
}
|
||||
});
|
||||
} else {
|
||||
localServices.stream().forEach(y -> {
|
||||
@@ -535,7 +619,9 @@ public abstract class NodeServer {
|
||||
y.init(Sncp.getConf(y));
|
||||
long e = System.currentTimeMillis() - s;
|
||||
String serstr = Sncp.toSimpleString(y, maxNameLength, maxTypeLength);
|
||||
if (slist != null) slist.add(new StringBuilder().append(serstr).append(" load and init in ").append(e < 10 ? " " : (e < 100 ? " " : "")).append(e).append(" ms").append(LINE_SEPARATOR).toString());
|
||||
if (slist != null) {
|
||||
slist.add(new StringBuilder().append(serstr).append(" load and init in ").append(e < 10 ? " " : (e < 100 ? " " : "")).append(e).append(" ms").append(LINE_SEPARATOR).toString());
|
||||
}
|
||||
});
|
||||
}
|
||||
if (slist != null && sb != null) {
|
||||
@@ -545,8 +631,12 @@ public abstract class NodeServer {
|
||||
}
|
||||
sb.append("All " + localServices.size() + " Services load in ").append(System.currentTimeMillis() - starts).append(" ms");
|
||||
}
|
||||
if (sb != null && preinite > 10) sb.append(ClusterAgent.class.getSimpleName()).append(" register in ").append(preinite).append(" ms" + LINE_SEPARATOR);
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
|
||||
if (sb != null && preinite > 10) {
|
||||
sb.append(ClusterAgent.class.getSimpleName()).append(" register in ").append(preinite).append(" ms" + LINE_SEPARATOR);
|
||||
}
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
}
|
||||
|
||||
private void calcMaxLength(Service y) { //计算toString中的长度
|
||||
@@ -560,8 +650,12 @@ public abstract class NodeServer {
|
||||
if (!application.isCompileMode() && cluster != null) {
|
||||
NodeProtocol pros = getClass().getAnnotation(NodeProtocol.class);
|
||||
String protocol = pros.value().toUpperCase();
|
||||
if (!cluster.containsProtocol(protocol)) return;
|
||||
if (!cluster.containsPort(server.getSocketAddress().getPort())) return;
|
||||
if (!cluster.containsProtocol(protocol)) {
|
||||
return;
|
||||
}
|
||||
if (!cluster.containsPort(server.getSocketAddress().getPort())) {
|
||||
return;
|
||||
}
|
||||
cluster.register(this, protocol, localServices, remoteServices);
|
||||
}
|
||||
}
|
||||
@@ -628,13 +722,21 @@ public abstract class NodeServer {
|
||||
String mq = list.getValue("mq");
|
||||
if (sc != null) {
|
||||
sc = sc.trim();
|
||||
if (sc.endsWith(";")) sc = sc.substring(0, sc.length() - 1);
|
||||
if (sc.endsWith(";")) {
|
||||
sc = sc.substring(0, sc.length() - 1);
|
||||
}
|
||||
}
|
||||
if (sc == null) {
|
||||
sc = localGroup;
|
||||
}
|
||||
if (sc == null) sc = localGroup;
|
||||
if (sc != null || mq != null) {
|
||||
prop = new AnyValue.DefaultAnyValue();
|
||||
if (sc != null) prop.addValue("groups", sc);
|
||||
if (mq != null) prop.addValue("mq", mq);
|
||||
if (sc != null) {
|
||||
prop.addValue("groups", sc);
|
||||
}
|
||||
if (mq != null) {
|
||||
prop.addValue("mq", mq);
|
||||
}
|
||||
}
|
||||
ClassFilter filter = new ClassFilter(this.serverClassLoader, ref, inter, excludeSuperClasses, prop);
|
||||
for (AnyValue av : list.getAnyValues(property)) { // <service>、<filter>、<servlet> 节点
|
||||
@@ -650,7 +752,9 @@ public abstract class NodeServer {
|
||||
final AnyValue.Entry<AnyValue>[] anys = av.getAnyEntrys();
|
||||
if (anys != null) {
|
||||
for (AnyValue.Entry<AnyValue> en : anys) { //将<service>、<filter>、<servlet>节点的非property属性节点传给dav
|
||||
if (!"property".equals(en.name)) dav.addValue(en.name, en.getValue());
|
||||
if (!"property".equals(en.name)) {
|
||||
dav.addValue(en.name, en.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
AnyValue.DefaultAnyValue ps = AnyValue.DefaultAnyValue.create();
|
||||
@@ -724,27 +828,37 @@ public abstract class NodeServer {
|
||||
}
|
||||
|
||||
public void start() throws IOException {
|
||||
if (interceptor != null) interceptor.preStart(this);
|
||||
if (interceptor != null) {
|
||||
interceptor.preStart(this);
|
||||
}
|
||||
server.start();
|
||||
postStartServer(localServices, remoteServices);
|
||||
}
|
||||
|
||||
public void shutdown() throws IOException {
|
||||
if (interceptor != null) interceptor.preShutdown(this);
|
||||
if (interceptor != null) {
|
||||
interceptor.preShutdown(this);
|
||||
}
|
||||
final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
|
||||
final boolean finest = logger.isLoggable(Level.FINEST);
|
||||
preDestroyServices(localServices, remoteServices);
|
||||
localServices.forEach(y -> {
|
||||
long s = System.currentTimeMillis();
|
||||
if (finest) logger.finest(y + " is destroying");
|
||||
if (finest) {
|
||||
logger.finest(y + " is destroying");
|
||||
}
|
||||
y.destroy(Sncp.getConf(y));
|
||||
if (finest) logger.finest(y + " was destroyed");
|
||||
if (finest) {
|
||||
logger.finest(y + " was destroyed");
|
||||
}
|
||||
long e = System.currentTimeMillis() - s;
|
||||
if (e > 2 && sb != null) {
|
||||
sb.append(Sncp.toSimpleString(y, maxNameLength, maxTypeLength)).append(" destroy ").append(e).append("ms").append(LINE_SEPARATOR);
|
||||
}
|
||||
});
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
server.shutdown();
|
||||
}
|
||||
|
||||
@@ -758,7 +872,9 @@ public abstract class NodeServer {
|
||||
for (Method m : loop.getMethods()) {
|
||||
Command c = m.getAnnotation(Command.class);
|
||||
org.redkale.util.Command c2 = m.getAnnotation(org.redkale.util.Command.class);
|
||||
if (c == null && c2 == null) continue;
|
||||
if (c == null && c2 == null) {
|
||||
continue;
|
||||
}
|
||||
if (Modifier.isStatic(m.getModifiers())) {
|
||||
logger.log(Level.WARNING, m + " is static on @Command");
|
||||
continue;
|
||||
@@ -775,18 +891,24 @@ public abstract class NodeServer {
|
||||
logger.log(Level.WARNING, m + " parameters[1] type is not String[].class on @Command");
|
||||
continue;
|
||||
}
|
||||
if (!c.value().isEmpty() && !c.value().equalsIgnoreCase(cmd)) continue;
|
||||
if (!c.value().isEmpty() && !c.value().equalsIgnoreCase(cmd)) {
|
||||
continue;
|
||||
}
|
||||
methods.add(m);
|
||||
}
|
||||
//} while ((loop = loop.getSuperclass()) != Object.class);
|
||||
if (methods.isEmpty()) return;
|
||||
if (methods.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
long s = System.currentTimeMillis();
|
||||
Method one = null;
|
||||
try {
|
||||
for (Method method : methods) {
|
||||
one = method;
|
||||
Object r = method.getParameterCount() == 2 ? method.invoke(y, cmd, params) : method.invoke(y, cmd);
|
||||
if (r != null) results.add(r);
|
||||
if (r != null) {
|
||||
results.add(r);
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.log(Level.SEVERE, one + " run error, cmd = " + cmd, ex);
|
||||
@@ -796,7 +918,9 @@ public abstract class NodeServer {
|
||||
sb.append(Sncp.toSimpleString(y, maxNameLength, maxTypeLength)).append(" command (").append(cmd).append(") ").append(e).append("ms").append(LINE_SEPARATOR);
|
||||
}
|
||||
});
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,10 +34,14 @@ public class NodeSncpServer extends NodeServer {
|
||||
super(application, createServer(application, serconf));
|
||||
this.sncpServer = (SncpServer) this.server;
|
||||
this.consumer = sncpServer == null || application.isSingletonMode() ? null : (agent, x) -> {//singleton模式下不生成SncpServlet
|
||||
if (x.getClass().getAnnotation(Local.class) != null) return; //本地模式的Service不生成SncpServlet
|
||||
if (x.getClass().getAnnotation(Local.class) != null) {
|
||||
return; //本地模式的Service不生成SncpServlet
|
||||
}
|
||||
SncpDynServlet servlet = sncpServer.addSncpServlet(x);
|
||||
dynServletMap.put(x, servlet);
|
||||
if (agent != null) agent.putService(this, x, servlet);
|
||||
if (agent != null) {
|
||||
agent.putService(this, x, servlet);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,21 +59,29 @@ public class NodeSncpServer extends NodeServer {
|
||||
}
|
||||
|
||||
public void consumerAccept(MessageAgent messageAgent, Service service) {
|
||||
if (this.consumer != null) this.consumer.accept(messageAgent, service);
|
||||
if (this.consumer != null) {
|
||||
this.consumer.accept(messageAgent, service);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init(AnyValue config) throws Exception {
|
||||
super.init(config);
|
||||
//-------------------------------------------------------------------
|
||||
if (sncpServer == null) return; //调试时server才可能为null
|
||||
if (sncpServer == null) {
|
||||
return; //调试时server才可能为null
|
||||
}
|
||||
final StringBuilder sb = logger.isLoggable(Level.FINE) ? new StringBuilder() : null;
|
||||
List<SncpServlet> servlets = sncpServer.getSncpServlets();
|
||||
Collections.sort(servlets);
|
||||
for (SncpServlet en : servlets) {
|
||||
if (sb != null) sb.append("Load ").append(en).append(LINE_SEPARATOR);
|
||||
if (sb != null) {
|
||||
sb.append("Load ").append(en).append(LINE_SEPARATOR);
|
||||
}
|
||||
}
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.FINE, sb.toString());
|
||||
}
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.FINE, sb.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -83,7 +95,9 @@ public class NodeSncpServer extends NodeServer {
|
||||
|
||||
@Override
|
||||
protected void loadFilter(ClassFilter<? extends Filter> filterFilter, ClassFilter otherFilter) throws Exception {
|
||||
if (sncpServer != null) loadSncpFilter(this.serverConf.getAnyValue("fliters"), filterFilter);
|
||||
if (sncpServer != null) {
|
||||
loadSncpFilter(this.serverConf.getAnyValue("fliters"), filterFilter);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -92,15 +106,21 @@ public class NodeSncpServer extends NodeServer {
|
||||
List<FilterEntry<? extends Filter>> list = new ArrayList(classFilter.getFilterEntrys());
|
||||
for (FilterEntry<? extends Filter> en : list) {
|
||||
Class<SncpFilter> clazz = (Class<SncpFilter>) en.getType();
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) continue;
|
||||
if (Modifier.isAbstract(clazz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
RedkaleClassLoader.putReflectionDeclaredConstructors(clazz, clazz.getName());
|
||||
final SncpFilter filter = clazz.getDeclaredConstructor().newInstance();
|
||||
resourceFactory.inject(filter, this);
|
||||
DefaultAnyValue filterConf = (DefaultAnyValue) en.getProperty();
|
||||
this.sncpServer.addSncpFilter(filter, filterConf);
|
||||
if (sb != null) sb.append("Load ").append(clazz.getName()).append(LINE_SEPARATOR);
|
||||
if (sb != null) {
|
||||
sb.append("Load ").append(clazz.getName()).append(LINE_SEPARATOR);
|
||||
}
|
||||
}
|
||||
if (sb != null && sb.length() > 0) {
|
||||
logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -51,57 +51,83 @@ public class PrepareCompiler {
|
||||
|
||||
for (FilterEntry en : entityFilter.getFilterEntrys()) {
|
||||
Class clz = en.getType();
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
application.dataSources.forEach(source -> source.compile(clz));
|
||||
JsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadEncoder(clz);
|
||||
}
|
||||
Decodeable decoder = JsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadDecoder(clz);
|
||||
}
|
||||
decoder.convertFrom(new JsonReader("{}"));
|
||||
} catch (Exception e) { //JsonFactory.loadDecoder可能会失败,因为class可能包含抽象类字段,如ColumnValue.value字段
|
||||
}
|
||||
}
|
||||
for (FilterEntry en : entityFilter2.getFilterEntrys()) {
|
||||
Class clz = en.getType();
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
application.dataSources.forEach(source -> source.compile(clz));
|
||||
JsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadEncoder(clz);
|
||||
}
|
||||
Decodeable decoder = JsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadDecoder(clz);
|
||||
}
|
||||
decoder.convertFrom(new JsonReader("{}"));
|
||||
} catch (Exception e) { //JsonFactory.loadDecoder可能会失败,因为class可能包含抽象类字段,如ColumnValue.value字段
|
||||
}
|
||||
}
|
||||
for (FilterEntry en : beanFilter.getFilterEntrys()) {
|
||||
Class clz = en.getType();
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
JsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadEncoder(clz);
|
||||
}
|
||||
Decodeable decoder = JsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadDecoder(clz);
|
||||
}
|
||||
decoder.convertFrom(new JsonReader("{}"));
|
||||
} catch (Exception e) { //JsonFactory.loadDecoder可能会失败,因为class可能包含抽象类字段,如ColumnValue.value字段
|
||||
}
|
||||
}
|
||||
for (FilterEntry en : beanFilter2.getFilterEntrys()) {
|
||||
Class clz = en.getType();
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
JsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadEncoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadEncoder(clz);
|
||||
}
|
||||
Decodeable decoder = JsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) BsonFactory.root().loadDecoder(clz);
|
||||
if (hasSncp) {
|
||||
BsonFactory.root().loadDecoder(clz);
|
||||
}
|
||||
decoder.convertFrom(new JsonReader("{}"));
|
||||
} catch (Exception e) { //JsonFactory.loadDecoder可能会失败,因为class可能包含抽象类字段,如ColumnValue.value字段
|
||||
}
|
||||
}
|
||||
for (FilterEntry en : filterFilter.getFilterEntrys()) {
|
||||
Class clz = en.getType();
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
|
||||
if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
FilterNodeBean.load(clz);
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -7,11 +7,10 @@ package org.redkale.boot.watch;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import org.redkale.annotation.Resource;
|
||||
import org.redkale.annotation.*;
|
||||
import org.redkale.boot.*;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.service.RetResult;
|
||||
import org.redkale.annotation.Comment;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -39,11 +38,17 @@ public class FilterWatchService extends AbstractWatchService {
|
||||
public RetResult addFilter(@RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameRegx = "\\.jar$") byte[] jar,
|
||||
@RestParam(name = "server", comment = "Server节点名") final String serverName,
|
||||
@RestParam(name = "type", comment = "Filter类名") final String filterType) throws IOException {
|
||||
if (filterType == null) return new RetResult(RET_FILTER_TYPE_NOT_EXISTS, "Not found Filter Type (" + filterType + ")");
|
||||
if (jar == null) return new RetResult(RET_FILTER_JAR_ILLEGAL, "Not found jar file");
|
||||
if (filterType == null) {
|
||||
return new RetResult(RET_FILTER_TYPE_NOT_EXISTS, "Not found Filter Type (" + filterType + ")");
|
||||
}
|
||||
if (jar == null) {
|
||||
return new RetResult(RET_FILTER_JAR_ILLEGAL, "Not found jar file");
|
||||
}
|
||||
List<NodeServer> nodes = application.getNodeServers();
|
||||
for (NodeServer node : nodes) {
|
||||
if (node.getServer().containsFilter(filterType)) return new RetResult(RET_FILTER_EXISTS, "Filter(" + filterType + ") exists");
|
||||
if (node.getServer().containsFilter(filterType)) {
|
||||
return new RetResult(RET_FILTER_EXISTS, "Filter(" + filterType + ") exists");
|
||||
}
|
||||
}
|
||||
return RetResult.success();
|
||||
}
|
||||
|
||||
@@ -9,12 +9,11 @@ import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
import org.redkale.annotation.Resource;
|
||||
import org.redkale.annotation.*;
|
||||
import org.redkale.boot.*;
|
||||
import org.redkale.net.Server;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.service.RetResult;
|
||||
import org.redkale.annotation.Comment;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -36,7 +35,9 @@ public class ServerWatchService extends AbstractWatchService {
|
||||
public RetResult info(@RestParam(name = "#port:") final int port) {
|
||||
Stream<NodeServer> stream = application.getNodeServers().stream();
|
||||
NodeServer node = stream.filter(ns -> ns.getServer().getSocketAddress().getPort() == port).findFirst().orElse(null);
|
||||
if (node == null) return new RetResult(RET_SERVER_NOT_EXISTS, "Server(port=" + port + ") not found");
|
||||
if (node == null) {
|
||||
return new RetResult(RET_SERVER_NOT_EXISTS, "Server(port=" + port + ") not found");
|
||||
}
|
||||
return new RetResult(formatToMap(node));
|
||||
}
|
||||
|
||||
@@ -53,11 +54,17 @@ public class ServerWatchService extends AbstractWatchService {
|
||||
@RestMapping(name = "changeAddress", comment = "更改Server的监听地址和端口")
|
||||
public RetResult changeAddress(@RestParam(name = "#port:") final int oldport,
|
||||
@RestParam(name = "#newhost:") final String newhost, @RestParam(name = "#newport:") final int newport) {
|
||||
if (oldport < 1) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `oldport`");
|
||||
if (newport < 1) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `newport`");
|
||||
if (oldport < 1) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `oldport`");
|
||||
}
|
||||
if (newport < 1) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `newport`");
|
||||
}
|
||||
Stream<NodeServer> stream = application.getNodeServers().stream();
|
||||
NodeServer node = stream.filter(ns -> ns.getServer().getSocketAddress().getPort() == oldport).findFirst().orElse(null);
|
||||
if (node == null) return new RetResult(RET_SERVER_NOT_EXISTS, "Server(port=" + oldport + ") not found");
|
||||
if (node == null) {
|
||||
return new RetResult(RET_SERVER_NOT_EXISTS, "Server(port=" + oldport + ") not found");
|
||||
}
|
||||
final Server server = node.getServer();
|
||||
InetSocketAddress newAddr = new InetSocketAddress(newhost == null || newhost.isEmpty() ? server.getSocketAddress().getHostString() : newhost, newport);
|
||||
try {
|
||||
|
||||
@@ -6,15 +6,14 @@
|
||||
package org.redkale.boot.watch;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
import java.util.List;
|
||||
import org.redkale.annotation.Comment;
|
||||
import org.redkale.annotation.Resource;
|
||||
import org.redkale.annotation.*;
|
||||
import org.redkale.boot.*;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.service.RetResult;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.ResourceFactory;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
@@ -37,13 +36,23 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
@RestParam(name = "type", comment = "Service的类名") String type,
|
||||
@RestParam(name = "field", comment = "字段名") String field,
|
||||
@RestParam(name = "value", comment = "字段值") String value) {
|
||||
if (name == null) name = "";
|
||||
if (type == null) type = "";
|
||||
if (field == null) field = "";
|
||||
if (name == null) {
|
||||
name = "";
|
||||
}
|
||||
if (type == null) {
|
||||
type = "";
|
||||
}
|
||||
if (field == null) {
|
||||
field = "";
|
||||
}
|
||||
type = type.trim();
|
||||
field = field.trim();
|
||||
if (type.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
if (field.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `field`");
|
||||
if (type.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
}
|
||||
if (field.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `field`");
|
||||
}
|
||||
Object dest = findService(name, type);
|
||||
Class clazz = dest.getClass();
|
||||
Throwable t = null;
|
||||
@@ -54,10 +63,14 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
fieldObj = clazz.getDeclaredField(field);
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
if (t == null) t = e;
|
||||
if (t == null) {
|
||||
t = e;
|
||||
}
|
||||
}
|
||||
} while ((clazz = clazz.getSuperclass()) != Object.class);
|
||||
if (fieldObj == null) return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + String.valueOf(t) + ")");
|
||||
if (fieldObj == null) {
|
||||
return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + String.valueOf(t) + ")");
|
||||
}
|
||||
fieldObj.setAccessible(true);
|
||||
fieldObj.set(dest, JsonConvert.root().convertFrom(fieldObj.getGenericType(), value));
|
||||
return RetResult.success();
|
||||
@@ -71,13 +84,23 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
public RetResult getField(@RestParam(name = "name", comment = "Service的资源名") String name,
|
||||
@RestParam(name = "type", comment = "Service的类名") String type,
|
||||
@RestParam(name = "field", comment = "字段名") String field) {
|
||||
if (name == null) name = "";
|
||||
if (type == null) type = "";
|
||||
if (field == null) field = "";
|
||||
if (name == null) {
|
||||
name = "";
|
||||
}
|
||||
if (type == null) {
|
||||
type = "";
|
||||
}
|
||||
if (field == null) {
|
||||
field = "";
|
||||
}
|
||||
type = type.trim();
|
||||
field = field.trim();
|
||||
if (type.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
if (field.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `field`");
|
||||
if (type.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
}
|
||||
if (field.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `field`");
|
||||
}
|
||||
Object dest = findService(name, type);
|
||||
Class clazz = dest.getClass();
|
||||
Throwable t = null;
|
||||
@@ -88,10 +111,14 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
fieldObj = clazz.getDeclaredField(field);
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
if (t == null) t = e;
|
||||
if (t == null) {
|
||||
t = e;
|
||||
}
|
||||
}
|
||||
} while ((clazz = clazz.getSuperclass()) != Object.class);
|
||||
if (fieldObj == null) return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + String.valueOf(t) + ")");
|
||||
if (fieldObj == null) {
|
||||
return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + String.valueOf(t) + ")");
|
||||
}
|
||||
fieldObj.setAccessible(true);
|
||||
return new RetResult(fieldObj.get(dest));
|
||||
} catch (Throwable t2) {
|
||||
@@ -106,18 +133,30 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
@RestParam(name = "method", comment = "Service的方法名") String method,
|
||||
@RestParam(name = "params", comment = "方法的参数值") List<String> params,
|
||||
@RestParam(name = "paramtypes", comment = "方法的参数数据类型") List<String> paramtypes) {
|
||||
if (name == null) name = "";
|
||||
if (type == null) type = "";
|
||||
if (method == null) method = "";
|
||||
if (name == null) {
|
||||
name = "";
|
||||
}
|
||||
if (type == null) {
|
||||
type = "";
|
||||
}
|
||||
if (method == null) {
|
||||
method = "";
|
||||
}
|
||||
type = type.trim();
|
||||
method = method.trim();
|
||||
if (type.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
if (method.isEmpty()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `method`");
|
||||
if (type.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `type`");
|
||||
}
|
||||
if (method.isEmpty()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "not found param `method`");
|
||||
}
|
||||
Object dest = findService(name, type);
|
||||
Class clazz = dest.getClass();
|
||||
Throwable t = null;
|
||||
final int paramcount = params == null ? 0 : params.size();
|
||||
if (paramtypes != null && paramcount != paramtypes.size()) return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "params.size not equals to paramtypes.size");
|
||||
if (paramtypes != null && paramcount != paramtypes.size()) {
|
||||
return new RetResult(RET_WATCH_PARAMS_ILLEGAL, "params.size not equals to paramtypes.size");
|
||||
}
|
||||
try {
|
||||
Method methodObj = null;
|
||||
do {
|
||||
@@ -140,14 +179,22 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (methodObj != null) break;
|
||||
if (methodObj != null) {
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (t == null) t = e;
|
||||
if (t == null) {
|
||||
t = e;
|
||||
}
|
||||
}
|
||||
} while ((clazz = clazz.getSuperclass()) != Object.class);
|
||||
if (methodObj == null) return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + (t == null ? ("not found method(" + method + ")") : String.valueOf(t)) + ")");
|
||||
if (methodObj == null) {
|
||||
return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + (t == null ? ("not found method(" + method + ")") : String.valueOf(t)) + ")");
|
||||
}
|
||||
methodObj.setAccessible(true);
|
||||
if (paramcount < 1) return new RetResult(methodObj.invoke(dest));
|
||||
if (paramcount < 1) {
|
||||
return new RetResult(methodObj.invoke(dest));
|
||||
}
|
||||
Object[] paramObjs = new Object[paramcount];
|
||||
Type[] pts = methodObj.getGenericParameterTypes();
|
||||
for (int i = 0; i < paramObjs.length; i++) {
|
||||
@@ -164,10 +211,14 @@ public class ServiceWatchService extends AbstractWatchService {
|
||||
for (NodeServer ns : application.getNodeServers()) {
|
||||
ResourceFactory resFactory = ns.getResourceFactory();
|
||||
List list = resFactory.query((n, s) -> name.equals(n) && s != null && s.getClass().getName().endsWith(type));
|
||||
if (list == null || list.isEmpty()) continue;
|
||||
if (list == null || list.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
dest = list.get(0);
|
||||
}
|
||||
if (dest == null) return new RetResult(RET_SERVICE_DEST_NOT_EXISTS, "not found servie (name=" + name + ", type=" + type + ")");
|
||||
if (dest == null) {
|
||||
return new RetResult(RET_SERVICE_DEST_NOT_EXISTS, "not found servie (name=" + name + ", type=" + type + ")");
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,19 +6,18 @@
|
||||
package org.redkale.boot.watch;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.channels.AsynchronousSocketChannel;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.redkale.annotation.Comment;
|
||||
import org.redkale.annotation.Resource;
|
||||
import org.redkale.annotation.*;
|
||||
import org.redkale.boot.Application;
|
||||
import org.redkale.net.*;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.net.sncp.*;
|
||||
import org.redkale.service.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.AnyValue;
|
||||
import org.redkale.util.AnyValue.DefaultAnyValue;
|
||||
|
||||
/**
|
||||
@@ -61,14 +60,18 @@ public class TransportWatchService extends AbstractWatchService {
|
||||
} catch (Exception e) {
|
||||
return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") is illegal or cannot connect");
|
||||
}
|
||||
if (transportFactory.findGroupName(address) != null) return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") is exists");
|
||||
if (transportFactory.findGroupName(address) != null) {
|
||||
return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") is exists");
|
||||
}
|
||||
synchronized (this) {
|
||||
if (transportFactory.findGroupInfo(group) == null) {
|
||||
return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
|
||||
}
|
||||
transportFactory.addGroupInfo(group, address);
|
||||
for (Service service : transportFactory.getServices()) {
|
||||
if (!Sncp.isSncpDyn(service)) continue;
|
||||
if (!Sncp.isSncpDyn(service)) {
|
||||
continue;
|
||||
}
|
||||
SncpClient client = Sncp.getSncpClient(service);
|
||||
if (Sncp.isRemote(service)) {
|
||||
if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
|
||||
@@ -92,16 +95,22 @@ public class TransportWatchService extends AbstractWatchService {
|
||||
public RetResult removeNode(@RestParam(name = "group", comment = "Group节点名") final String group,
|
||||
@RestParam(name = "addr", comment = "节点IP") final String addr,
|
||||
@RestParam(name = "port", comment = "节点端口") final int port) throws IOException {
|
||||
if (group == null) return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
|
||||
if (group == null) {
|
||||
return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
|
||||
}
|
||||
final InetSocketAddress address = new InetSocketAddress(addr, port);
|
||||
if (!group.equals(transportFactory.findGroupName(address))) return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") not belong to group(" + group + ")");
|
||||
if (!group.equals(transportFactory.findGroupName(address))) {
|
||||
return new RetResult(RET_TRANSPORT_ADDR_ILLEGAL, "InetSocketAddress(addr=" + addr + ", port=" + port + ") not belong to group(" + group + ")");
|
||||
}
|
||||
synchronized (this) {
|
||||
if (transportFactory.findGroupInfo(group) == null) {
|
||||
return new RetResult(RET_TRANSPORT_GROUP_NOT_EXISTS, "not found group (" + group + ")");
|
||||
}
|
||||
transportFactory.removeGroupInfo(group, address);
|
||||
for (Service service : transportFactory.getServices()) {
|
||||
if (!Sncp.isSncpDyn(service)) continue;
|
||||
if (!Sncp.isSncpDyn(service)) {
|
||||
continue;
|
||||
}
|
||||
SncpClient client = Sncp.getSncpClient(service);
|
||||
if (Sncp.isRemote(service)) {
|
||||
if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
|
||||
|
||||
@@ -51,7 +51,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
super.init(factory, config);
|
||||
this.sourceName = getSourceName();
|
||||
this.ttls = config.getIntValue("ttls", 10);
|
||||
if (this.ttls < 5) this.ttls = 10;
|
||||
if (this.ttls < 5) {
|
||||
this.ttls = 10;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -88,7 +90,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
|
||||
@Override
|
||||
public void destroy(AnyValue config) {
|
||||
if (scheduler != null) scheduler.shutdownNow();
|
||||
if (scheduler != null) {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
public String getSourceName() {
|
||||
@@ -102,7 +106,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
|
||||
@Override //ServiceLoader时判断配置是否符合当前实现类
|
||||
public boolean acceptsConf(AnyValue config) {
|
||||
if (config == null) return false;
|
||||
if (config == null) {
|
||||
return false;
|
||||
}
|
||||
return config.getValue("source") != null;
|
||||
}
|
||||
|
||||
@@ -186,7 +192,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
public CompletableFuture<Collection<InetSocketAddress>> queryHttpAddress(String protocol, String module, String resname) {
|
||||
final String serviceName = generateHttpServiceName(protocol, module, resname);
|
||||
Collection<InetSocketAddress> rs = httpAddressMap.get(serviceName);
|
||||
if (rs != null) return CompletableFuture.completedFuture(rs);
|
||||
if (rs != null) {
|
||||
return CompletableFuture.completedFuture(rs);
|
||||
}
|
||||
return queryAddress(serviceName).thenApply(t -> {
|
||||
httpAddressMap.put(serviceName, t);
|
||||
return t;
|
||||
@@ -203,7 +211,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
return future.thenApply(map -> {
|
||||
final Set<InetSocketAddress> set = new HashSet<>();
|
||||
map.forEach((n, v) -> {
|
||||
if (v != null && (System.currentTimeMillis() - v.time) / 1000 < ttls) set.add(v.addr);
|
||||
if (v != null && (System.currentTimeMillis() - v.time) / 1000 < ttls) {
|
||||
set.add(v.addr);
|
||||
}
|
||||
});
|
||||
return set;
|
||||
});
|
||||
@@ -228,7 +238,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
|
||||
@Override
|
||||
public void register(Application application) {
|
||||
if (isApplicationHealth()) throw new RuntimeException("application.nodeid=" + nodeid + " exists in cluster");
|
||||
if (isApplicationHealth()) {
|
||||
throw new RuntimeException("application.nodeid=" + nodeid + " exists in cluster");
|
||||
}
|
||||
deregister(application);
|
||||
|
||||
String serviceid = generateApplicationServiceId();
|
||||
@@ -283,7 +295,9 @@ public class CacheClusterAgent extends ClusterAgent implements Resourcable {
|
||||
}
|
||||
}
|
||||
source.hdel(serviceName, serviceid);
|
||||
if (realcanceled && currEntry != null) currEntry.canceled = true;
|
||||
if (realcanceled && currEntry != null) {
|
||||
currEntry.canceled = true;
|
||||
}
|
||||
if (!"mqtp".equals(protocol) && currEntry != null && currEntry.submqtp) {
|
||||
deregister(ns, "mqtp", service, realcanceled);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ import org.redkale.annotation.*;
|
||||
import org.redkale.annotation.ResourceListener;
|
||||
import static org.redkale.boot.Application.*;
|
||||
import org.redkale.boot.*;
|
||||
import static org.redkale.boot.Application.*;
|
||||
import org.redkale.convert.ConvertDisabled;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.mq.MessageMultiConsumer;
|
||||
@@ -73,7 +72,9 @@ public abstract class ClusterAgent {
|
||||
this.waits = config.getBoolValue("waits", false);
|
||||
{
|
||||
String ps = config.getValue("protocols", "").toUpperCase();
|
||||
if (ps == null || ps.isEmpty()) ps = "SNCP;HTTP";
|
||||
if (ps == null || ps.isEmpty()) {
|
||||
ps = "SNCP;HTTP";
|
||||
}
|
||||
this.protocols = ps.split(";");
|
||||
}
|
||||
String ts = config.getValue("ports", "");
|
||||
@@ -81,7 +82,9 @@ public abstract class ClusterAgent {
|
||||
String[] its = ts.split(";");
|
||||
List<Integer> list = new ArrayList<>();
|
||||
for (String str : its) {
|
||||
if (str.trim().isEmpty()) continue;
|
||||
if (str.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
list.add(Integer.parseInt(str.trim()));
|
||||
}
|
||||
if (!list.isEmpty()) {
|
||||
@@ -115,12 +118,16 @@ public abstract class ClusterAgent {
|
||||
public abstract boolean acceptsConf(AnyValue config);
|
||||
|
||||
public boolean containsProtocol(String protocol) {
|
||||
if (protocol == null || protocol.isEmpty()) return false;
|
||||
if (protocol == null || protocol.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
return protocols == null || Utility.contains(protocols, protocol.toUpperCase());
|
||||
}
|
||||
|
||||
public boolean containsPort(int port) {
|
||||
if (ports == null || ports.length == 0) return true;
|
||||
if (ports == null || ports.length == 0) {
|
||||
return true;
|
||||
}
|
||||
return Utility.contains(ports, port);
|
||||
}
|
||||
|
||||
@@ -130,10 +137,14 @@ public abstract class ClusterAgent {
|
||||
|
||||
//注册服务, 在NodeService调用Service.init方法之前调用
|
||||
public void register(NodeServer ns, String protocol, Set<Service> localServices, Set<Service> remoteServices) {
|
||||
if (localServices.isEmpty()) return;
|
||||
if (localServices.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
//注册本地模式
|
||||
for (Service service : localServices) {
|
||||
if (!canRegister(ns, protocol, service)) continue;
|
||||
if (!canRegister(ns, protocol, service)) {
|
||||
continue;
|
||||
}
|
||||
ClusterEntry htentry = register(ns, protocol, service);
|
||||
localEntrys.put(htentry.serviceid, htentry);
|
||||
if (protocol.toLowerCase().startsWith("http")) {
|
||||
@@ -159,23 +170,35 @@ public abstract class ClusterAgent {
|
||||
public void deregister(NodeServer ns, String protocol, Set<Service> localServices, Set<Service> remoteServices) {
|
||||
//注销本地模式 远程模式不注册
|
||||
for (Service service : localServices) {
|
||||
if (!canRegister(ns, protocol, service)) continue;
|
||||
if (!canRegister(ns, protocol, service)) {
|
||||
continue;
|
||||
}
|
||||
deregister(ns, protocol, service);
|
||||
}
|
||||
afterDeregister(ns, protocol);
|
||||
}
|
||||
|
||||
protected boolean canRegister(NodeServer ns, String protocol, Service service) {
|
||||
if ("SNCP".equalsIgnoreCase(protocol) && service.getClass().getAnnotation(Local.class) != null) return false;
|
||||
if ("SNCP".equalsIgnoreCase(protocol) && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return false;
|
||||
}
|
||||
AutoLoad al = service.getClass().getAnnotation(AutoLoad.class);
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) return false;
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return false;
|
||||
}
|
||||
org.redkale.util.AutoLoad al2 = service.getClass().getAnnotation(org.redkale.util.AutoLoad.class);
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) return false;
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return false;
|
||||
}
|
||||
if (service instanceof WebSocketNode) {
|
||||
if (((WebSocketNode) service).getLocalWebSocketEngine() == null) return false;
|
||||
if (((WebSocketNode) service).getLocalWebSocketEngine() == null) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
ClusterEntry entry = new ClusterEntry(ns, protocol, service);
|
||||
if (entry.serviceName.trim().endsWith(serviceSeparator())) return false;
|
||||
if (entry.serviceName.trim().endsWith(serviceSeparator())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -183,7 +206,9 @@ public abstract class ClusterAgent {
|
||||
}
|
||||
|
||||
protected void afterDeregister(NodeServer ns, String protocol) {
|
||||
if (!this.waits) return;
|
||||
if (!this.waits) {
|
||||
return;
|
||||
}
|
||||
int s = intervalCheckSeconds();
|
||||
if (s > 0) { //暂停,弥补其他依赖本进程服务的周期偏差
|
||||
try {
|
||||
@@ -216,7 +241,9 @@ public abstract class ClusterAgent {
|
||||
//格式: protocol:classtype-resourcename
|
||||
protected void updateSncpTransport(ClusterEntry entry) {
|
||||
Service service = entry.serviceRef.get();
|
||||
if (service == null) return;
|
||||
if (service == null) {
|
||||
return;
|
||||
}
|
||||
Collection<InetSocketAddress> addrs = ClusterAgent.this.queryAddress(entry).join();
|
||||
Sncp.updateTransport(service, transportFactory, Sncp.getResourceType(service).getName() + "-" + Sncp.getResourceName(service), entry.netProtocol, entry.address, null, addrs);
|
||||
}
|
||||
@@ -274,7 +301,9 @@ public abstract class ClusterAgent {
|
||||
String selfmodule = Rest.getRestModule(service).toLowerCase();
|
||||
return protocol.toLowerCase() + serviceSeparator() + mmc.module() + serviceSeparator() + selfmodule;
|
||||
}
|
||||
if (!Sncp.isSncpDyn(service)) return protocol.toLowerCase() + serviceSeparator() + service.getClass().getName();
|
||||
if (!Sncp.isSncpDyn(service)) {
|
||||
return protocol.toLowerCase() + serviceSeparator() + service.getClass().getName();
|
||||
}
|
||||
String resname = Sncp.getResourceName(service);
|
||||
return protocol.toLowerCase() + serviceSeparator() + Sncp.getResourceType(service).getName() + (resname.isEmpty() ? "" : ("-" + resname));
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ package org.redkale.convert;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.convert.Reader.ValueType;
|
||||
import static org.redkale.convert.Reader.ValueType.MAP;
|
||||
import org.redkale.util.*;
|
||||
|
||||
/**
|
||||
* 对不明类型的对象进行反序列化。 <br>
|
||||
@@ -51,7 +51,9 @@ public class AnyDecoder implements Decodeable<Reader, Object> {
|
||||
@Override
|
||||
public Object convertFrom(Reader in) {
|
||||
ValueType vt = in.readType();
|
||||
if (vt == null) return null;
|
||||
if (vt == null) {
|
||||
return null;
|
||||
}
|
||||
switch (vt) {
|
||||
case ARRAY:
|
||||
return this.collectionDecoder.convertFrom(in);
|
||||
|
||||
@@ -36,7 +36,9 @@ public final class AnyEncoder<T> implements Encodeable<Writer, T> {
|
||||
out.writeObjectE(value);
|
||||
return;
|
||||
}
|
||||
if (out.needWriteClassName()) out.writeClassName(factory.getEntityAlias(clazz));
|
||||
if (out.needWriteClassName()) {
|
||||
out.writeClassName(factory.getEntityAlias(clazz));
|
||||
}
|
||||
factory.loadEncoder(clazz).convertTo(out, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,7 +74,9 @@ public class ArrayDecoder<T> implements Decodeable<Reader, T[]> {
|
||||
byte[] typevals = new byte[1];
|
||||
int len = in.readArrayB(member, typevals, componentDecoder);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(member, componentDecoder);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
@@ -97,7 +99,9 @@ public class ArrayDecoder<T> implements Decodeable<Reader, T[]> {
|
||||
int startPosition = in.position();
|
||||
while (hasNext(in, member, startPosition, contentLength, first)) {
|
||||
Reader itemReader = getItemReader(in, member, first);
|
||||
if (itemReader == null) break;
|
||||
if (itemReader == null) {
|
||||
break;
|
||||
}
|
||||
result.add(readMemberValue(itemReader, member, localdecoder, first));
|
||||
first = false;
|
||||
}
|
||||
@@ -124,7 +128,9 @@ public class ArrayDecoder<T> implements Decodeable<Reader, T[]> {
|
||||
}
|
||||
|
||||
protected T readMemberValue(Reader in, DeMember member, Decodeable<Reader, T> decoder, boolean first) {
|
||||
if (in == null) return null;
|
||||
if (in == null) {
|
||||
return null;
|
||||
}
|
||||
return decoder.convertFrom(in);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,10 +5,9 @@
|
||||
*/
|
||||
package org.redkale.convert;
|
||||
|
||||
import org.redkale.util.Creator;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import org.redkale.util.Creator;
|
||||
|
||||
/**
|
||||
* Collection的反序列化操作类 <br>
|
||||
@@ -80,7 +79,9 @@ public class CollectionDecoder<T> implements Decodeable<Reader, Collection<T>> {
|
||||
byte[] typevals = new byte[1];
|
||||
int len = in.readArrayB(member, typevals, componentDecoder);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(member, componentDecoder);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
@@ -103,7 +104,9 @@ public class CollectionDecoder<T> implements Decodeable<Reader, Collection<T>> {
|
||||
int startPosition = in.position();
|
||||
while (hasNext(in, member, startPosition, contentLength, first)) {
|
||||
Reader itemReader = getItemReader(in, member, first);
|
||||
if (itemReader == null) break;
|
||||
if (itemReader == null) {
|
||||
break;
|
||||
}
|
||||
result.add(readMemberValue(itemReader, member, localdecoder, first));
|
||||
first = false;
|
||||
}
|
||||
@@ -129,7 +132,9 @@ public class CollectionDecoder<T> implements Decodeable<Reader, Collection<T>> {
|
||||
}
|
||||
|
||||
protected T readMemberValue(Reader in, DeMember member, Decodeable<Reader, T> decoder, boolean first) {
|
||||
if (in == null) return null;
|
||||
if (in == null) {
|
||||
return null;
|
||||
}
|
||||
return decoder.convertFrom(in);
|
||||
}
|
||||
|
||||
|
||||
@@ -79,9 +79,13 @@ public class CollectionEncoder<T> implements Encodeable<Writer, Collection<T>> {
|
||||
if (out.writeArrayB(value.size(), this, componentEncoder, value) < 0) {
|
||||
boolean first = true;
|
||||
for (Object v : value) {
|
||||
if (!first) out.writeArrayMark();
|
||||
if (!first) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
writeMemberValue(out, member, v, first);
|
||||
if (first) first = false;
|
||||
if (first) {
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.writeArrayE();
|
||||
|
||||
@@ -156,17 +156,29 @@ public final class DeMember<R extends Reader, T, F> {
|
||||
}
|
||||
|
||||
public int compareTo(boolean fieldSort, DeMember<R, T, F> o) {
|
||||
if (o == null) return -1;
|
||||
if (this.position != o.position) return (this.position == 0 ? Integer.MAX_VALUE : this.position) - (o.position == 0 ? Integer.MAX_VALUE : o.position);
|
||||
if (this.index != o.index) return (this.index == 0 ? Integer.MAX_VALUE : this.index) - (o.index == 0 ? Integer.MAX_VALUE : o.index);
|
||||
if (this.index != 0) throw new ConvertException("fields (" + attribute.field() + ", " + o.attribute.field() + ") have same ConvertColumn.index(" + this.index + ") in " + attribute.declaringClass());
|
||||
if (o == null) {
|
||||
return -1;
|
||||
}
|
||||
if (this.position != o.position) {
|
||||
return (this.position == 0 ? Integer.MAX_VALUE : this.position) - (o.position == 0 ? Integer.MAX_VALUE : o.position);
|
||||
}
|
||||
if (this.index != o.index) {
|
||||
return (this.index == 0 ? Integer.MAX_VALUE : this.index) - (o.index == 0 ? Integer.MAX_VALUE : o.index);
|
||||
}
|
||||
if (this.index != 0) {
|
||||
throw new ConvertException("fields (" + attribute.field() + ", " + o.attribute.field() + ") have same ConvertColumn.index(" + this.index + ") in " + attribute.declaringClass());
|
||||
}
|
||||
return fieldSort ? this.attribute.field().compareTo(o.attribute.field()) : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (!(obj instanceof DeMember)) return false;
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof DeMember)) {
|
||||
return false;
|
||||
}
|
||||
DeMember other = (DeMember) obj;
|
||||
return compareTo(true, other) == 0;
|
||||
}
|
||||
|
||||
@@ -175,17 +175,29 @@ public final class EnMember<W extends Writer, T, F> {
|
||||
}
|
||||
|
||||
public int compareTo(boolean fieldSort, EnMember<W, T, F> o) {
|
||||
if (o == null) return -1;
|
||||
if (this.position != o.position) return (this.position == 0 ? Integer.MAX_VALUE : this.position) - (o.position == 0 ? Integer.MAX_VALUE : o.position);
|
||||
if (this.index != o.index) return (this.index == 0 ? Integer.MAX_VALUE : this.index) - (o.index == 0 ? Integer.MAX_VALUE : o.index);
|
||||
if (this.index != 0) throw new ConvertException("fields (" + attribute.field() + ", " + o.attribute.field() + ") have same ConvertColumn.index(" + this.index + ") in " + attribute.declaringClass());
|
||||
if (o == null) {
|
||||
return -1;
|
||||
}
|
||||
if (this.position != o.position) {
|
||||
return (this.position == 0 ? Integer.MAX_VALUE : this.position) - (o.position == 0 ? Integer.MAX_VALUE : o.position);
|
||||
}
|
||||
if (this.index != o.index) {
|
||||
return (this.index == 0 ? Integer.MAX_VALUE : this.index) - (o.index == 0 ? Integer.MAX_VALUE : o.index);
|
||||
}
|
||||
if (this.index != 0) {
|
||||
throw new ConvertException("fields (" + attribute.field() + ", " + o.attribute.field() + ") have same ConvertColumn.index(" + this.index + ") in " + attribute.declaringClass());
|
||||
}
|
||||
return fieldSort ? this.attribute.field().compareTo(o.attribute.field()) : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) return true;
|
||||
if (!(obj instanceof EnMember)) return false;
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (!(obj instanceof EnMember)) {
|
||||
return false;
|
||||
}
|
||||
EnMember other = (EnMember) obj;
|
||||
return compareTo(true, other) == 0;
|
||||
}
|
||||
|
||||
@@ -5,10 +5,9 @@
|
||||
*/
|
||||
package org.redkale.convert;
|
||||
|
||||
import org.redkale.util.Creator;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import org.redkale.util.Creator;
|
||||
|
||||
/**
|
||||
* Map的反序列化操作类 <br>
|
||||
@@ -108,7 +107,9 @@ public class MapDecoder<K, V> implements Decodeable<Reader, Map<K, V>> {
|
||||
byte[] typevals = new byte[2];
|
||||
int len = in.readMapB(member, typevals, this.keyDecoder, this.valueDecoder);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(member, null);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
@@ -121,7 +122,9 @@ public class MapDecoder<K, V> implements Decodeable<Reader, Map<K, V>> {
|
||||
int startPosition = in.position();
|
||||
while (hasNext(in, member, startPosition, contentLength, first)) {
|
||||
Reader entryReader = getEntryReader(in, member, first);
|
||||
if (entryReader == null) break;
|
||||
if (entryReader == null) {
|
||||
break;
|
||||
}
|
||||
K key = readKeyMember(entryReader, member, kdecoder, first);
|
||||
entryReader.readBlank();
|
||||
V value = readValueMember(entryReader, member, vdecoder, first);
|
||||
|
||||
@@ -5,8 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
@@ -85,11 +84,17 @@ public class MapEncoder<K, V> implements Encodeable<Writer, Map<K, V>> {
|
||||
if (out.writeMapB(values.size(), (Encodeable) keyEncoder, (Encodeable) valueEncoder, value) < 0) {
|
||||
boolean first = true;
|
||||
for (Map.Entry<K, V> en : values.entrySet()) {
|
||||
if (ignoreColumns != null && ignoreColumns.contains(en.getKey())) continue;
|
||||
if (ignoreColumns != null && ignoreColumns.contains(en.getKey())) {
|
||||
continue;
|
||||
}
|
||||
V v = mapFieldFunc == null ? en.getValue() : mapFieldFunc.apply(en.getKey(), en.getValue());
|
||||
if (!first) out.writeArrayMark();
|
||||
if (!first) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
writeMemberValue(out, member, en.getKey(), v, first);
|
||||
if (first) first = false;
|
||||
if (first) {
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.writeMapE();
|
||||
|
||||
@@ -89,7 +89,9 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
}
|
||||
if (!clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers())) {
|
||||
this.creator = factory.loadCreator(clazz);
|
||||
if (this.creator == null) throw new ConvertException("Cannot create a creator for " + clazz);
|
||||
if (this.creator == null) {
|
||||
throw new ConvertException("Cannot create a creator for " + clazz);
|
||||
}
|
||||
}
|
||||
final Set<DeMember> list = new LinkedHashSet();
|
||||
final String[] cps = ObjectEncoder.findConstructorProperties(this.creator);
|
||||
@@ -98,10 +100,16 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
ConvertFactory colFactory;
|
||||
RedkaleClassLoader.putReflectionPublicFields(clazz.getName());
|
||||
for (final Field field : clazz.getFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (factory.isConvertDisabled(field)) continue;
|
||||
if (Modifier.isStatic(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(field)) {
|
||||
continue;
|
||||
}
|
||||
ref = factory.findRef(clazz, field);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
ConvertSmallString small = field.getAnnotation(ConvertSmallString.class);
|
||||
colFactory = factory.columnFactory(field.getType(), field.getAnnotationsByType(ConvertCoder.class), false);
|
||||
Decodeable<R, ?> fieldCoder;
|
||||
@@ -115,25 +123,45 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
fieldCoder = colFactory.loadDecoder(t);
|
||||
}
|
||||
DeMember member = new DeMember(ObjectEncoder.createAttribute(colFactory, type, clazz, field, null, null), fieldCoder, field, null);
|
||||
if (ref != null) member.index = ref.getIndex();
|
||||
if (ref != null) {
|
||||
member.index = ref.getIndex();
|
||||
}
|
||||
list.add(member);
|
||||
}
|
||||
final boolean reversible = factory.isReversible();
|
||||
RedkaleClassLoader.putReflectionPublicMethods(clazz.getName());
|
||||
for (final Method method : clazz.getMethods()) {
|
||||
if (Modifier.isStatic(method.getModifiers())) continue;
|
||||
if (Modifier.isAbstract(method.getModifiers())) continue;
|
||||
if (method.isSynthetic()) continue;
|
||||
if (method.getParameterCount() != 1) continue;
|
||||
if (method.getName().length() < 4) continue;
|
||||
if (!method.getName().startsWith("set")) continue;
|
||||
if (method.getReturnType() != void.class && method.getReturnType() != clazz) continue;
|
||||
if (factory.isConvertDisabled(method)) continue;
|
||||
if (Modifier.isStatic(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (Modifier.isAbstract(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (method.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if (method.getParameterCount() != 1) {
|
||||
continue;
|
||||
}
|
||||
if (method.getName().length() < 4) {
|
||||
continue;
|
||||
}
|
||||
if (!method.getName().startsWith("set")) {
|
||||
continue;
|
||||
}
|
||||
if (method.getReturnType() != void.class && method.getReturnType() != clazz) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(method)) {
|
||||
continue;
|
||||
}
|
||||
if (reversible && (cps == null || !ObjectEncoder.contains(cps, ConvertFactory.readGetSetFieldName(method)))) {
|
||||
boolean is = method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0] == Boolean.class;
|
||||
try {
|
||||
Method getter = clazz.getMethod(method.getName().replaceFirst("set", is ? "is" : "get"));
|
||||
if (getter.getReturnType() != method.getParameterTypes()[0]) continue;
|
||||
if (getter.getReturnType() != method.getParameterTypes()[0]) {
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
continue;
|
||||
}
|
||||
@@ -142,20 +170,26 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
Field f = null;
|
||||
try {
|
||||
f = clazz.getDeclaredField(fieldname);
|
||||
if (f.getType() != method.getParameterTypes()[0]) continue;
|
||||
if (f.getType() != method.getParameterTypes()[0]) {
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
if (f == null) {
|
||||
boolean is = method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0] == Boolean.class;
|
||||
try {
|
||||
Method getter = clazz.getMethod(method.getName().replaceFirst("set", is ? "is" : "get"));
|
||||
if (getter.getReturnType() != method.getParameterTypes()[0]) continue;
|
||||
if (getter.getReturnType() != method.getParameterTypes()[0]) {
|
||||
continue;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
ref = factory.findRef(clazz, method);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
ConvertSmallString small = method.getAnnotation(ConvertSmallString.class);
|
||||
Field maybeField = ConvertFactory.readGetSetField(method);
|
||||
@@ -174,7 +208,9 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
fieldCoder = colFactory.loadDecoder(t);
|
||||
}
|
||||
DeMember member = new DeMember(ObjectEncoder.createAttribute(colFactory, type, clazz, null, null, method), fieldCoder, maybeField, method);
|
||||
if (ref != null) member.index = ref.getIndex();
|
||||
if (ref != null) {
|
||||
member.index = ref.getIndex();
|
||||
}
|
||||
list.add(member);
|
||||
}
|
||||
if (cps != null) { //可能存在某些构造函数中的字段名不存在setter方法
|
||||
@@ -186,7 +222,9 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flag) continue;
|
||||
if (flag) {
|
||||
continue;
|
||||
}
|
||||
//不存在setter方法
|
||||
try {
|
||||
Field f = clazz.getDeclaredField(constructorField);
|
||||
@@ -212,7 +250,9 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
Collections.sort(sorts, (a, b) -> a.compareTo(factory.isFieldSort(), b));
|
||||
Set<Integer> pos = new HashSet<>();
|
||||
for (DeMember member : sorts) {
|
||||
if (member.index > 0) pos.add(member.index);
|
||||
if (member.index > 0) {
|
||||
pos.add(member.index);
|
||||
}
|
||||
}
|
||||
int pidx = 0;
|
||||
for (DeMember member : sorts) {
|
||||
@@ -271,8 +311,12 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
public T convertFrom(final R in) {
|
||||
R objin = objectReader(in);
|
||||
final String clazz = objin.readObjectB(typeClass);
|
||||
if (clazz == null) return null;
|
||||
if (!clazz.isEmpty()) return (T) factory.loadDecoder(factory.getEntityAlias(clazz)).convertFrom(objin);
|
||||
if (clazz == null) {
|
||||
return null;
|
||||
}
|
||||
if (!clazz.isEmpty()) {
|
||||
return (T) factory.loadDecoder(factory.getEntityAlias(clazz)).convertFrom(objin);
|
||||
}
|
||||
if (!this.inited) {
|
||||
synchronized (lock) {
|
||||
try {
|
||||
@@ -327,13 +371,17 @@ public class ObjectDecoder<R extends Reader, T> implements Decodeable<R, T> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flag) otherParams[oc++] = new Object[]{member.attribute, val};
|
||||
if (flag) {
|
||||
otherParams[oc++] = new Object[]{member.attribute, val};
|
||||
}
|
||||
|
||||
}
|
||||
first = false;
|
||||
}
|
||||
objin.readObjectE(typeClass);
|
||||
if (this.creator == null) return null;
|
||||
if (this.creator == null) {
|
||||
return null;
|
||||
}
|
||||
final T result = this.creator.create(constructorParams);
|
||||
for (int i = 0; i < oc; i++) {
|
||||
((Attribute) otherParams[i][0]).set(result, otherParams[i][1]);
|
||||
|
||||
@@ -60,7 +60,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
public void init(final ConvertFactory factory) {
|
||||
this.factory = factory;
|
||||
try {
|
||||
if (type == Object.class) return;
|
||||
if (type == Object.class) {
|
||||
return;
|
||||
}
|
||||
//if (!(type instanceof Class)) throw new ConvertException("[" + type + "] is no a class");
|
||||
final Class clazz = this.typeClass;
|
||||
final Set<EnMember> list = new LinkedHashSet();
|
||||
@@ -69,7 +71,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
try {
|
||||
creator = factory.loadCreator(this.typeClass);
|
||||
} catch (RuntimeException e) {
|
||||
if (reversible && !Modifier.isAbstract(this.typeClass.getModifiers())) throw e;
|
||||
if (reversible && !Modifier.isAbstract(this.typeClass.getModifiers())) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
final String[] cps = creator == null ? null : ObjectEncoder.findConstructorProperties(creator);
|
||||
try {
|
||||
@@ -77,10 +81,16 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
ConvertFactory colFactory;
|
||||
RedkaleClassLoader.putReflectionPublicFields(clazz.getName());
|
||||
for (final Field field : clazz.getFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (factory.isConvertDisabled(field)) continue;
|
||||
if (Modifier.isStatic(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(field)) {
|
||||
continue;
|
||||
}
|
||||
ref = factory.findRef(clazz, field);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
ConvertSmallString small = field.getAnnotation(ConvertSmallString.class);
|
||||
colFactory = factory.columnFactory(field.getType(), field.getAnnotationsByType(ConvertCoder.class), true);
|
||||
Encodeable<W, ?> fieldCoder;
|
||||
@@ -94,22 +104,40 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
fieldCoder = colFactory.loadEncoder(t);
|
||||
}
|
||||
EnMember member = new EnMember(createAttribute(colFactory, type, clazz, field, null, null), fieldCoder, field, null);
|
||||
if (ref != null) member.index = ref.getIndex();
|
||||
if (ref != null) {
|
||||
member.index = ref.getIndex();
|
||||
}
|
||||
list.add(member);
|
||||
}
|
||||
|
||||
RedkaleClassLoader.putReflectionPublicMethods(clazz.getName());
|
||||
for (final Method method : clazz.getMethods()) {
|
||||
if (Modifier.isStatic(method.getModifiers())) continue;
|
||||
if (Modifier.isAbstract(method.getModifiers())) continue;
|
||||
if (method.isSynthetic()) continue;
|
||||
if (method.getName().equals("getClass")) continue;
|
||||
if (method.getReturnType() == void.class) continue;
|
||||
if (method.getParameterCount() != 0) continue;
|
||||
if (Modifier.isStatic(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (Modifier.isAbstract(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (method.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if (method.getName().equals("getClass")) {
|
||||
continue;
|
||||
}
|
||||
if (method.getReturnType() == void.class) {
|
||||
continue;
|
||||
}
|
||||
if (method.getParameterCount() != 0) {
|
||||
continue;
|
||||
}
|
||||
if (!(method.getName().startsWith("is") && method.getName().length() > 2)
|
||||
&& !(method.getName().startsWith("get") && method.getName().length() > 3)
|
||||
&& !Utility.isRecordGetter(clazz, method)) continue;
|
||||
if (factory.isConvertDisabled(method)) continue;
|
||||
&& !Utility.isRecordGetter(clazz, method)) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(method)) {
|
||||
continue;
|
||||
}
|
||||
String convertname = ConvertFactory.readGetSetFieldName(method);
|
||||
if (reversible && (cps == null || !contains(cps, convertname))) {
|
||||
boolean is = method.getName().startsWith("is");
|
||||
@@ -120,12 +148,16 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
}
|
||||
}
|
||||
ref = factory.findRef(clazz, method);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
ConvertSmallString small = method.getAnnotation(ConvertSmallString.class);
|
||||
if (small == null) {
|
||||
try {
|
||||
Field f = clazz.getDeclaredField(convertname);
|
||||
if (f != null) small = f.getAnnotation(ConvertSmallString.class);
|
||||
if (f != null) {
|
||||
small = f.getAnnotation(ConvertSmallString.class);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
@@ -145,7 +177,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
fieldCoder = colFactory.loadEncoder(t);
|
||||
}
|
||||
EnMember member = new EnMember(createAttribute(colFactory, type, clazz, null, method, null), fieldCoder, maybeField, method);
|
||||
if (ref != null) member.index = ref.getIndex();
|
||||
if (ref != null) {
|
||||
member.index = ref.getIndex();
|
||||
}
|
||||
list.add(member);
|
||||
}
|
||||
List<EnMember> sorts = new ArrayList<>(list);
|
||||
@@ -159,7 +193,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (flag) continue;
|
||||
if (flag) {
|
||||
continue;
|
||||
}
|
||||
//不存在setter方法
|
||||
try {
|
||||
Field f = clazz.getDeclaredField(constructorField);
|
||||
@@ -185,12 +221,16 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dissorts.size() != list.size()) sorts = new ArrayList<>(dissorts);
|
||||
if (dissorts.size() != list.size()) {
|
||||
sorts = new ArrayList<>(dissorts);
|
||||
}
|
||||
}
|
||||
Collections.sort(sorts, (a, b) -> a.compareTo(factory.isFieldSort(), b));
|
||||
Set<Integer> pos = new HashSet<>();
|
||||
for (EnMember member : sorts) {
|
||||
if (member.index > 0) pos.add(member.index);
|
||||
if (member.index > 0) {
|
||||
pos.add(member.index);
|
||||
}
|
||||
}
|
||||
int pidx = 0;
|
||||
for (EnMember member : sorts) {
|
||||
@@ -235,7 +275,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
}
|
||||
if (value.getClass() != this.typeClass && !this.type.equals(out.specify())) {
|
||||
final Class clz = value.getClass();
|
||||
if (out.needWriteClassName()) out.writeClassName(factory.getEntityAlias(clz));
|
||||
if (out.needWriteClassName()) {
|
||||
out.writeClassName(factory.getEntityAlias(clz));
|
||||
}
|
||||
factory.loadEncoder(clz).convertTo(out, value);
|
||||
return;
|
||||
}
|
||||
@@ -251,7 +293,9 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
if (extFields != null) {
|
||||
Encodeable<W, ?> anyEncoder = factory.getAnyEncoder();
|
||||
for (ConvertField en : extFields) {
|
||||
if (en == null) continue;
|
||||
if (en == null) {
|
||||
continue;
|
||||
}
|
||||
maxPosition++;
|
||||
objout.writeObjectField(en.getName(), en.getType(), Math.max(en.getPosition(), maxPosition), anyEncoder, en.getValue());
|
||||
}
|
||||
@@ -305,13 +349,17 @@ public class ObjectEncoder<W extends Writer, T> implements Encodeable<W, T> {
|
||||
|
||||
static boolean contains(String[] values, String value) {
|
||||
for (String str : values) {
|
||||
if (str.equals(value)) return true;
|
||||
if (str.equals(value)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static String[] findConstructorProperties(Creator creator) {
|
||||
if (creator == null) return null;
|
||||
if (creator == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Method method = creator.getClass().getMethod("create", Object[].class);
|
||||
ConstructorParameters cps = method.getAnnotation(ConstructorParameters.class);
|
||||
|
||||
@@ -80,9 +80,13 @@ public class StreamEncoder<T> implements Encodeable<Writer, Stream<T>> {
|
||||
if (out.writeArrayB(array.length, this, componentEncoder, array) < 0) {
|
||||
boolean first = true;
|
||||
for (Object v : array) {
|
||||
if (!first) out.writeArrayMark();
|
||||
if (!first) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
writeMemberValue(out, member, v, first);
|
||||
if (first) first = false;
|
||||
if (first) {
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.writeArrayE();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.bson;
|
||||
|
||||
import java.nio.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.redkale.convert.*;
|
||||
import static org.redkale.convert.Reader.SIGN_NULL;
|
||||
@@ -31,7 +31,9 @@ public class BsonByteBufferReader extends BsonReader {
|
||||
protected BsonByteBufferReader(ConvertMask mask, ByteBuffer... buffers) {
|
||||
this.mask = mask;
|
||||
this.buffers = buffers;
|
||||
if (buffers != null && buffers.length > 0) this.currentBuffer = buffers[currentIndex];
|
||||
if (buffers != null && buffers.length > 0) {
|
||||
this.currentBuffer = buffers[currentIndex];
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -52,7 +54,9 @@ public class BsonByteBufferReader extends BsonReader {
|
||||
@Override
|
||||
public int readMapB(DeMember member, byte[] typevals, Decodeable keyDecoder, Decodeable valueDecoder) {
|
||||
short bt = readShort();
|
||||
if (bt == Reader.SIGN_NULL) return bt;
|
||||
if (bt == Reader.SIGN_NULL) {
|
||||
return bt;
|
||||
}
|
||||
short lt = readShort();
|
||||
byte kt = readByte();
|
||||
byte vt = readByte();
|
||||
@@ -75,11 +79,15 @@ public class BsonByteBufferReader extends BsonReader {
|
||||
@Override
|
||||
public final int readArrayB(DeMember member, byte[] typevals, Decodeable componentDecoder) {
|
||||
short bt = readShort();
|
||||
if (bt == Reader.SIGN_NULL) return bt;
|
||||
if (bt == Reader.SIGN_NULL) {
|
||||
return bt;
|
||||
}
|
||||
short lt = readShort();
|
||||
if (componentDecoder != null && componentDecoder != ByteSimpledCoder.instance) {
|
||||
byte comval = readByte();
|
||||
if (typevals != null) typevals[0] = comval;
|
||||
if (typevals != null) {
|
||||
typevals[0] = comval;
|
||||
}
|
||||
}
|
||||
return (bt & 0xffff) << 16 | (lt & 0xffff);
|
||||
}
|
||||
@@ -224,15 +232,21 @@ public class BsonByteBufferReader extends BsonReader {
|
||||
@Override
|
||||
public final String readSmallString() {
|
||||
int len = 0xff & readByte();
|
||||
if (len == 0) return "";
|
||||
if (len == 0) {
|
||||
return "";
|
||||
}
|
||||
return new String(read(len));
|
||||
}
|
||||
|
||||
@Override
|
||||
public final String readString() {
|
||||
int len = readInt();
|
||||
if (len == SIGN_NULL) return null;
|
||||
if (len == 0) return "";
|
||||
if (len == SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == 0) {
|
||||
return "";
|
||||
}
|
||||
return new String(read(len), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
*/
|
||||
package org.redkale.convert.bson;
|
||||
|
||||
import java.nio.*;
|
||||
import java.util.function.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.function.Supplier;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
/**
|
||||
@@ -37,17 +37,23 @@ public class BsonByteBufferWriter extends BsonWriter {
|
||||
|
||||
@Override
|
||||
public ByteBuffer[] toBuffers() {
|
||||
if (buffers == null) return new ByteBuffer[0];
|
||||
if (buffers == null) {
|
||||
return new ByteBuffer[0];
|
||||
}
|
||||
for (int i = index; i < this.buffers.length; i++) {
|
||||
ByteBuffer buf = this.buffers[i];
|
||||
if (buf.position() != 0) buf.flip();
|
||||
if (buf.position() != 0) {
|
||||
buf.flip();
|
||||
}
|
||||
}
|
||||
return this.buffers;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] toArray() {
|
||||
if (buffers == null) return new byte[0];
|
||||
if (buffers == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
int pos = 0;
|
||||
byte[] bytes = new byte[this.count];
|
||||
for (ByteBuffer buf : toBuffers()) {
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
package org.redkale.convert.bson;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.*;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.function.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.util.*;
|
||||
@@ -120,14 +120,18 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
//------------------------------ convertFrom -----------------------------------------------------------
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final byte[] bytes) {
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(type, bytes, 0, bytes.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T convertFrom(final Type type, final byte[] bytes, final int offset, final int len) {
|
||||
if (type == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
final BsonReader in = new BsonReader(bytes, offset, len);
|
||||
@SuppressWarnings("unchecked")
|
||||
T rs = (T) factory.loadDecoder(type).convertFrom(in);
|
||||
@@ -136,27 +140,35 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T convertFrom(final Type type, final InputStream in) {
|
||||
if (type == null || in == null) return null;
|
||||
if (type == null || in == null) {
|
||||
return null;
|
||||
}
|
||||
return (T) factory.loadDecoder(type).convertFrom(new BsonStreamReader(in));
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T convertFrom(final Type type, final ByteBuffer... buffers) {
|
||||
if (type == null || buffers.length < 1) return null;
|
||||
if (type == null || buffers.length < 1) {
|
||||
return null;
|
||||
}
|
||||
return (T) factory.loadDecoder(type).convertFrom(new BsonByteBufferReader((ConvertMask) null, buffers));
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T convertFrom(final Type type, final ConvertMask mask, final ByteBuffer... buffers) {
|
||||
if (type == null || buffers.length < 1) return null;
|
||||
if (type == null || buffers.length < 1) {
|
||||
return null;
|
||||
}
|
||||
return (T) factory.loadDecoder(type).convertFrom(new BsonByteBufferReader(mask, buffers));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T convertFrom(final Type type, final BsonReader reader) {
|
||||
if (type == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
T rs = (T) factory.loadDecoder(type).convertFrom(reader);
|
||||
return rs;
|
||||
@@ -177,7 +189,9 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
|
||||
@Override
|
||||
public byte[] convertTo(final Type type, final Object value) {
|
||||
if (type == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
final BsonWriter writer = pollBsonWriter();
|
||||
factory.loadEncoder(type).convertTo(writer, value);
|
||||
byte[] result = writer.toArray();
|
||||
@@ -236,7 +250,9 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
}
|
||||
|
||||
public void convertTo(final OutputStream out, final Type type, final Object value) {
|
||||
if (type == null) return;
|
||||
if (type == null) {
|
||||
return;
|
||||
}
|
||||
if (value == null) {
|
||||
pollBsonWriter(out).writeNull();
|
||||
} else {
|
||||
@@ -246,7 +262,9 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
|
||||
@Override
|
||||
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, final Object value) {
|
||||
if (supplier == null) return null;
|
||||
if (supplier == null) {
|
||||
return null;
|
||||
}
|
||||
BsonByteBufferWriter out = pollBsonWriter(supplier);
|
||||
if (value == null) {
|
||||
out.writeNull();
|
||||
@@ -258,7 +276,9 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
|
||||
@Override
|
||||
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, final Type type, final Object value) {
|
||||
if (supplier == null || type == null) return null;
|
||||
if (supplier == null || type == null) {
|
||||
return null;
|
||||
}
|
||||
BsonByteBufferWriter writer = pollBsonWriter(supplier);
|
||||
if (value == null) {
|
||||
writer.writeNull();
|
||||
@@ -279,17 +299,23 @@ public class BsonConvert extends BinaryConvert<BsonReader, BsonWriter> {
|
||||
|
||||
@Override
|
||||
public void convertTo(final BsonWriter writer, final Type type, final Object value) {
|
||||
if (type == null) return;
|
||||
if (type == null) {
|
||||
return;
|
||||
}
|
||||
factory.loadEncoder(type).convertTo(writer, value);
|
||||
}
|
||||
|
||||
public BsonWriter convertToWriter(final Object value) {
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return convertToWriter(value.getClass(), value);
|
||||
}
|
||||
|
||||
public BsonWriter convertToWriter(final Type type, final Object value) {
|
||||
if (type == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
final BsonWriter writer = writerPool.get().tiny(tiny);
|
||||
factory.loadEncoder(type).convertTo(writer, value);
|
||||
return writer;
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.ext.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.TypeToken;
|
||||
|
||||
/**
|
||||
* BSON的ConvertFactory
|
||||
@@ -78,7 +78,9 @@ public final class BsonFactory extends ConvertFactory<BsonReader, BsonWriter> {
|
||||
|
||||
@Override
|
||||
public final BsonConvert getConvert() {
|
||||
if (convert == null) convert = new BsonConvert(this, tiny);
|
||||
if (convert == null) {
|
||||
convert = new BsonConvert(this, tiny);
|
||||
}
|
||||
return (BsonConvert) convert;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,8 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import org.redkale.convert.*;
|
||||
import static org.redkale.convert.Reader.SIGN_NULL;
|
||||
import org.redkale.convert.ext.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.convert.ext.ByteSimpledCoder;
|
||||
import org.redkale.util.ObjectPool;
|
||||
|
||||
/**
|
||||
* BSON数据源
|
||||
@@ -91,7 +91,9 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public final void skipValue() {
|
||||
if (typeval == 0) return;
|
||||
if (typeval == 0) {
|
||||
return;
|
||||
}
|
||||
final byte val = this.typeval;
|
||||
this.typeval = 0;
|
||||
switch (val) {
|
||||
@@ -115,7 +117,9 @@ public class BsonReader extends Reader {
|
||||
break;
|
||||
default:
|
||||
Decodeable decoder = BsonFactory.typeEnum(val);
|
||||
if (decoder != null) decoder.convertFrom(this);
|
||||
if (decoder != null) {
|
||||
decoder.convertFrom(this);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -124,9 +128,13 @@ public class BsonReader extends Reader {
|
||||
public final String readObjectB(final Class clazz) {
|
||||
this.fieldIndex = 0; //必须要重置为0
|
||||
final String newcls = readClassName();
|
||||
if (newcls != null && !newcls.isEmpty()) return newcls;
|
||||
if (newcls != null && !newcls.isEmpty()) {
|
||||
return newcls;
|
||||
}
|
||||
short bt = readShort();
|
||||
if (bt == Reader.SIGN_NULL) return null;
|
||||
if (bt == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (bt != SIGN_OBJECTB) {
|
||||
throw new ConvertException("a bson object must begin with " + (SIGN_OBJECTB)
|
||||
+ " (position = " + position + ") but '" + currentByte() + "'");
|
||||
@@ -149,7 +157,9 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
public int readMapB(DeMember member, byte[] typevals, Decodeable keyDecoder, Decodeable valueDecoder) {
|
||||
short bt = readShort();
|
||||
if (bt == Reader.SIGN_NULL) return bt;
|
||||
if (bt == Reader.SIGN_NULL) {
|
||||
return bt;
|
||||
}
|
||||
int rs = (bt & 0xffff) << 16 | ((content[++this.position] & 0xff) << 8) | (content[++this.position] & 0xff);
|
||||
byte kt = readByte();
|
||||
byte vt = readByte();
|
||||
@@ -172,11 +182,15 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
public int readArrayB(DeMember member, byte[] typevals, Decodeable componentDecoder) { //componentDecoder可能为null
|
||||
short bt = readShort();
|
||||
if (bt == Reader.SIGN_NULL) return bt;
|
||||
if (bt == Reader.SIGN_NULL) {
|
||||
return bt;
|
||||
}
|
||||
int rs = (bt & 0xffff) << 16 | ((content[++this.position] & 0xff) << 8) | (content[++this.position] & 0xff);
|
||||
if (componentDecoder != null && componentDecoder != ByteSimpledCoder.instance) {
|
||||
byte comval = readByte();
|
||||
if (typevals != null) typevals[0] = comval;
|
||||
if (typevals != null) {
|
||||
typevals[0] = comval;
|
||||
}
|
||||
}
|
||||
return rs;
|
||||
}
|
||||
@@ -213,9 +227,13 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
public boolean hasNext(int startPosition, int contentLength) {
|
||||
byte b = readByte();
|
||||
if (b == SIGN_HASNEXT) return true;
|
||||
if (b != SIGN_NONEXT) throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT)
|
||||
if (b == SIGN_HASNEXT) {
|
||||
return true;
|
||||
}
|
||||
if (b != SIGN_NONEXT) {
|
||||
throw new ConvertException("hasNext option must be (" + (SIGN_HASNEXT)
|
||||
+ " or " + (SIGN_NONEXT) + ") but '" + b + "' at position(" + this.position + ")");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -224,7 +242,9 @@ public class BsonReader extends Reader {
|
||||
final String exceptedField = readSmallString();
|
||||
this.typeval = readByte();
|
||||
final int len = members.length;
|
||||
if (this.fieldIndex >= len) this.fieldIndex = 0;
|
||||
if (this.fieldIndex >= len) {
|
||||
this.fieldIndex = 0;
|
||||
}
|
||||
for (int k = this.fieldIndex; k < len; k++) {
|
||||
if (exceptedField.equals(members[k].getAttribute().field())) {
|
||||
this.fieldIndex = k;
|
||||
@@ -255,7 +275,9 @@ public class BsonReader extends Reader {
|
||||
public final byte[] readByteArray() {
|
||||
int len = readArrayB(null, null, null);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = readMemberContentLength(null, null);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
@@ -332,7 +354,9 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
public String readSmallString() {
|
||||
int len = 0xff & readByte();
|
||||
if (len == 0) return "";
|
||||
if (len == 0) {
|
||||
return "";
|
||||
}
|
||||
String value = new String(content, ++this.position, len);
|
||||
this.position += len - 1; //上一行已经++this.position,所以此处要-1
|
||||
return value;
|
||||
@@ -341,8 +365,12 @@ public class BsonReader extends Reader {
|
||||
@Override
|
||||
public String readString() {
|
||||
int len = readInt();
|
||||
if (len == SIGN_NULL) return null;
|
||||
if (len == 0) return "";
|
||||
if (len == SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == 0) {
|
||||
return "";
|
||||
}
|
||||
String value = new String(content, ++this.position, len, StandardCharsets.UTF_8);
|
||||
this.position += len - 1;//上一行已经++this.position,所以此处要-1
|
||||
return value;
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
package org.redkale.convert.bson;
|
||||
|
||||
import java.io.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.ConvertException;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* @author zhangjx
|
||||
|
||||
@@ -75,7 +75,9 @@ public class BsonWriter extends Writer implements ByteTuple {
|
||||
}
|
||||
|
||||
public byte[] toArray() {
|
||||
if (count == content.length) return content;
|
||||
if (count == content.length) {
|
||||
return content;
|
||||
}
|
||||
byte[] newdata = new byte[count];
|
||||
System.arraycopy(content, 0, newdata, 0, count);
|
||||
return newdata;
|
||||
@@ -123,7 +125,9 @@ public class BsonWriter extends Writer implements ByteTuple {
|
||||
*/
|
||||
protected int expand(int len) {
|
||||
int newcount = count + len;
|
||||
if (newcount <= content.length) return 0;
|
||||
if (newcount <= content.length) {
|
||||
return 0;
|
||||
}
|
||||
byte[] newdata = new byte[Math.max(content.length * 3 / 2, newcount)];
|
||||
System.arraycopy(content, 0, newdata, 0, count);
|
||||
this.content = newdata;
|
||||
@@ -185,7 +189,9 @@ public class BsonWriter extends Writer implements ByteTuple {
|
||||
writeArrayB(values.length, null, null, values);
|
||||
boolean flag = false;
|
||||
for (byte v : values) {
|
||||
if (flag) writeArrayMark();
|
||||
if (flag) {
|
||||
writeArrayMark();
|
||||
}
|
||||
writeByte(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -266,11 +272,15 @@ public class BsonWriter extends Writer implements ByteTuple {
|
||||
return;
|
||||
}
|
||||
char[] chars = Utility.charArray(value);
|
||||
if (chars.length > 255) throw new ConvertException("'" + value + "' have very long length");
|
||||
if (chars.length > 255) {
|
||||
throw new ConvertException("'" + value + "' have very long length");
|
||||
}
|
||||
byte[] bytes = new byte[chars.length + 1];
|
||||
bytes[0] = (byte) chars.length;
|
||||
for (int i = 0; i < chars.length; i++) {
|
||||
if (chars[i] > Byte.MAX_VALUE) throw new ConvertException("'" + value + "' have double-word");
|
||||
if (chars[i] > Byte.MAX_VALUE) {
|
||||
throw new ConvertException("'" + value + "' have double-word");
|
||||
}
|
||||
bytes[i + 1] = (byte) chars[i];
|
||||
}
|
||||
writeTo(bytes);
|
||||
|
||||
@@ -27,7 +27,9 @@ public class SkipArrayDecoder<T> extends ArrayDecoder<T> {
|
||||
|
||||
@Override
|
||||
protected Decodeable<Reader, T> getComponentDecoder(Decodeable<Reader, T> decoder, byte[] typevals) {
|
||||
if (typevals != null) return BsonFactory.typeEnum(typevals[0]);
|
||||
if (typevals != null) {
|
||||
return BsonFactory.typeEnum(typevals[0]);
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,9 @@ public class SkipCollectionDecoder<T> extends CollectionDecoder<T> {
|
||||
|
||||
@Override
|
||||
protected Decodeable<Reader, T> getComponentDecoder(Decodeable<Reader, T> decoder, byte[] typevals) {
|
||||
if (typevals != null) return BsonFactory.typeEnum(typevals[0]);
|
||||
if (typevals != null) {
|
||||
return BsonFactory.typeEnum(typevals[0]);
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,13 +26,17 @@ public class SkipMapDecoder<K, V> extends MapDecoder<K, V> {
|
||||
|
||||
@Override
|
||||
protected Decodeable<Reader, K> getKeyDecoder(Decodeable<Reader, K> decoder, byte[] typevals) {
|
||||
if (typevals != null) return BsonFactory.typeEnum(typevals[0]);
|
||||
if (typevals != null) {
|
||||
return BsonFactory.typeEnum(typevals[0]);
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Decodeable<Reader, V> getValueDecoder(Decodeable<Reader, V> decoder, byte[] typevals) {
|
||||
if (typevals != null) return BsonFactory.typeEnum(typevals[1]);
|
||||
if (typevals != null) {
|
||||
return BsonFactory.typeEnum(typevals[1]);
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,9 @@ public class SkipStreamDecoder<T> extends StreamDecoder<T> {
|
||||
|
||||
@Override
|
||||
protected Decodeable<Reader, T> getComponentDecoder(Decodeable<Reader, T> decoder, byte[] typevals) {
|
||||
if (typevals != null) return BsonFactory.typeEnum(typevals[0]);
|
||||
if (typevals != null) {
|
||||
return BsonFactory.typeEnum(typevals[0]);
|
||||
}
|
||||
return decoder;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.Reader;
|
||||
import java.math.BigDecimal;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
@@ -38,7 +36,9 @@ public final class BigDecimalSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
@Override
|
||||
public BigDecimal convertFrom(R in) {
|
||||
String value = in.readSmallString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return new BigDecimal(Utility.charArray(value));
|
||||
}
|
||||
|
||||
@@ -64,7 +64,9 @@ public final class BigDecimalSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
@Override
|
||||
public BigDecimal convertFrom(R in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return new BigDecimal(str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.Reader;
|
||||
import java.math.BigInteger;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
/**
|
||||
@@ -64,7 +62,9 @@ public final class BigIntegerSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
@Override
|
||||
public BigInteger convertFrom(R in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return new BigInteger(str);
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,9 @@ public final class BigIntegerSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
@Override
|
||||
public BigInteger convertFrom(R in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
if (str.length() > 2) {
|
||||
if (str.charAt(0) == '0' && (str.charAt(1) == 'x' || str.charAt(1) == 'X')) {
|
||||
return new BigInteger(str.substring(2), 16);
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* boolean[] 的SimpledCoder实现
|
||||
@@ -32,7 +30,9 @@ public final class BoolArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
if (out.writeArrayB(values.length, this, BoolSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (boolean v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeBoolean(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -44,7 +44,9 @@ public final class BoolArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
public boolean[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, BoolSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, BoolSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,13 +5,11 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* boolean 的SimpledCoder实现
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* ByteBuffer 的SimpledCoder实现
|
||||
@@ -33,7 +31,9 @@ public final class ByteBufferSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
if (out.writeArrayB(value.remaining(), this, ByteSimpledCoder.instance, value) < 0) {
|
||||
boolean flag = false;
|
||||
for (byte v : value.array()) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeByte(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -45,7 +45,9 @@ public final class ByteBufferSimpledCoder<R extends Reader, W extends Writer> ex
|
||||
public ByteBuffer convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, ByteSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, ByteSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,13 +5,11 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* byte 的SimpledCoder实现
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* char[] 的SimpledCoder实现
|
||||
@@ -32,7 +30,9 @@ public final class CharArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
if (out.writeArrayB(values.length, this, CharSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (char v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeChar(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -44,7 +44,9 @@ public final class CharArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
public char[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, CharSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, CharSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -3,17 +3,16 @@
|
||||
* To change this template file, choose Tools | Templates
|
||||
* and open the template in the editor.
|
||||
*/
|
||||
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* char 的SimpledCoder实现
|
||||
*
|
||||
* <p> 详情见: https://redkale.org
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* @author zhangjx
|
||||
* @param <R> Reader输入的子类型
|
||||
* @param <W> Writer输出的子类型
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
import org.redkale.util.*;
|
||||
|
||||
@@ -41,7 +39,9 @@ public final class DLongSimpledCoder<R extends Reader, W extends Writer> extends
|
||||
@SuppressWarnings("unchecked")
|
||||
public DLong convertFrom(R in) {
|
||||
byte[] bs = bsSimpledCoder.convertFrom(in);
|
||||
if (bs == null) return null;
|
||||
if (bs == null) {
|
||||
return null;
|
||||
}
|
||||
return DLong.create(bs);
|
||||
}
|
||||
|
||||
@@ -67,7 +67,9 @@ public final class DLongSimpledCoder<R extends Reader, W extends Writer> extends
|
||||
@Override
|
||||
public DLong convertFrom(R in) {
|
||||
final String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return DLong.create(Utility.hexToBin(str));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.util.stream.DoubleStream;
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* double[] 的SimpledCoder实现
|
||||
@@ -33,7 +31,9 @@ public final class DoubleArraySimpledCoder<R extends Reader, W extends Writer> e
|
||||
if (out.writeArrayB(values.length, this, DoubleSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (double v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeDouble(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -45,7 +45,9 @@ public final class DoubleArraySimpledCoder<R extends Reader, W extends Writer> e
|
||||
public double[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, DoubleSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, DoubleSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* double 的SimpledCoder实现
|
||||
*
|
||||
* <p> 详情见: https://redkale.org
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* @author zhangjx
|
||||
* @param <R> Reader输入的子类型
|
||||
* @param <W> Writer输出的子类型
|
||||
|
||||
@@ -34,7 +34,9 @@ public class DurationSimpledCoder<R extends Reader, W extends Writer> extends Si
|
||||
@Override
|
||||
public Duration convertFrom(R in) {
|
||||
String value = in.readSmallString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return Duration.ofNanos(Long.parseLong(value));
|
||||
}
|
||||
|
||||
|
||||
@@ -76,7 +76,9 @@ public final class EnumSimpledCoder<R extends Reader, W extends Writer, E extend
|
||||
@SuppressWarnings("unchecked")
|
||||
public E convertFrom(final R in) {
|
||||
String value = in.readSmallString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
if (valueToEnums != null) {
|
||||
return valueToEnums.get(value);
|
||||
} else {
|
||||
|
||||
@@ -34,7 +34,9 @@ public class FileSimpledCoder<R extends Reader, W extends Writer> extends Simple
|
||||
@Override
|
||||
public File convertFrom(R in) {
|
||||
String value = in.readString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return new File(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* float[] 的SimpledCoder实现
|
||||
@@ -32,7 +30,9 @@ public final class FloatArraySimpledCoder<R extends Reader, W extends Writer> ex
|
||||
if (out.writeArrayB(values.length, this, FloatSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (float v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeFloat(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -44,7 +44,9 @@ public final class FloatArraySimpledCoder<R extends Reader, W extends Writer> ex
|
||||
public float[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, FloatSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, FloatSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* float 的SimpledCoder实现
|
||||
*
|
||||
* <p> 详情见: https://redkale.org
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* @author zhangjx
|
||||
* @param <R> Reader输入的子类型
|
||||
* @param <W> Writer输出的子类型
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.Reader;
|
||||
import java.net.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
import org.redkale.util.StringWrapper;
|
||||
|
||||
@@ -39,7 +37,9 @@ public final class InetAddressSimpledCoder<R extends Reader, W extends Writer> e
|
||||
@Override
|
||||
public InetAddress convertFrom(R in) {
|
||||
byte[] bytes = ByteArraySimpledCoder.instance.convertFrom(in);
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return InetAddress.getByAddress(bytes);
|
||||
} catch (Exception ex) {
|
||||
@@ -71,7 +71,9 @@ public final class InetAddressSimpledCoder<R extends Reader, W extends Writer> e
|
||||
@Override
|
||||
public InetSocketAddress convertFrom(R in) {
|
||||
byte[] bytes = ByteArraySimpledCoder.instance.convertFrom(in);
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
int port = in.readInt();
|
||||
try {
|
||||
return new InetSocketAddress(InetAddress.getByAddress(bytes), port);
|
||||
@@ -104,7 +106,9 @@ public final class InetAddressSimpledCoder<R extends Reader, W extends Writer> e
|
||||
@Override
|
||||
public InetAddress convertFrom(R in) {
|
||||
String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return InetAddress.getByName(str);
|
||||
} catch (Exception ex) {
|
||||
@@ -136,7 +140,9 @@ public final class InetAddressSimpledCoder<R extends Reader, W extends Writer> e
|
||||
@Override
|
||||
public InetSocketAddress convertFrom(R in) {
|
||||
String str = StringSimpledCoder.instance.convertFrom(in);
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
int pos = str.indexOf(':');
|
||||
return new InetSocketAddress(str.substring(0, pos), Integer.parseInt(str.substring(pos + 1)));
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.Instant;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
@@ -50,7 +50,9 @@ public class InstantSimpledCoder<R extends Reader, W extends Writer> extends Sim
|
||||
@Override
|
||||
public Instant convertFrom(R in) {
|
||||
final String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return Instant.parse(str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.util.stream.IntStream;
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* int[] 的SimpledCoder实现
|
||||
@@ -33,7 +31,9 @@ public final class IntArraySimpledCoder<R extends Reader, W extends Writer> exte
|
||||
if (out.writeArrayB(values.length, this, IntSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (int v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeInt(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -45,7 +45,9 @@ public final class IntArraySimpledCoder<R extends Reader, W extends Writer> exte
|
||||
public int[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, IntSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, IntSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
/**
|
||||
@@ -49,7 +47,9 @@ public final class IntSimpledCoder<R extends Reader, W extends Writer> extends S
|
||||
if (value == null) {
|
||||
out.writeSmallString("0x0");
|
||||
} else {
|
||||
if (value < 0) throw new NumberFormatException("Negative values (" + value + ") are not supported");
|
||||
if (value < 0) {
|
||||
throw new NumberFormatException("Negative values (" + value + ") are not supported");
|
||||
}
|
||||
out.writeSmallString("0x" + Integer.toHexString(value));
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,9 @@ public final class IntSimpledCoder<R extends Reader, W extends Writer> extends S
|
||||
@Override
|
||||
public Integer convertFrom(R in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return 0;
|
||||
if (str == null) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
if (str.length() > 2 && str.charAt(0) == '0' && (str.charAt(1) == 'x' || str.charAt(1) == 'X')) {
|
||||
return Integer.parseInt(str.substring(2), 16);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.LocalDate;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
@@ -43,7 +43,6 @@ public final class LocalDateSimpledCoder<R extends Reader, W extends Writer> ext
|
||||
// BsonReader reader = new BsonReader(writer.toArray());
|
||||
// System.out.println(LocalDateSimpledCoder.instance.convertFrom(reader));
|
||||
// }
|
||||
|
||||
/**
|
||||
* java.time.LocalDate 的JsonSimpledCoder实现
|
||||
*
|
||||
@@ -66,7 +65,9 @@ public final class LocalDateSimpledCoder<R extends Reader, W extends Writer> ext
|
||||
@Override
|
||||
public LocalDate convertFrom(R in) {
|
||||
final String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return LocalDate.parse(str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,9 @@ public final class LocalDateTimeSimpledCoder<R extends Reader, W extends Writer>
|
||||
@Override
|
||||
public LocalDateTime convertFrom(R in) {
|
||||
byte[] bs = bsSimpledCoder.convertFrom(in);
|
||||
if (bs == null) return null;
|
||||
if (bs == null) {
|
||||
return null;
|
||||
}
|
||||
long v1 = (((long) bs[0] & 0xff) << 56) | (((long) bs[1] & 0xff) << 48) | (((long) bs[2] & 0xff) << 40) | (((long) bs[3] & 0xff) << 32)
|
||||
| (((long) bs[4] & 0xff) << 24) | (((long) bs[5] & 0xff) << 16) | (((long) bs[6] & 0xff) << 8) | ((long) bs[7] & 0xff);
|
||||
int v2 = ((bs[8] & 0xff) << 24) | ((bs[9] & 0xff) << 16) | ((bs[10] & 0xff) << 8) | (bs[11] & 0xff);
|
||||
@@ -79,7 +81,9 @@ public final class LocalDateTimeSimpledCoder<R extends Reader, W extends Writer>
|
||||
@Override
|
||||
public LocalDateTime convertFrom(R in) {
|
||||
final String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return LocalDateTime.parse(str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.time.*;
|
||||
import java.time.LocalTime;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
@@ -64,7 +64,9 @@ public final class LocalTimeSimpledCoder<R extends Reader, W extends Writer> ext
|
||||
@Override
|
||||
public LocalTime convertFrom(R in) {
|
||||
final String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return LocalTime.parse(str);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.util.stream.LongStream;
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* long[] 的SimpledCoder实现
|
||||
@@ -33,7 +31,9 @@ public final class LongArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
if (out.writeArrayB(values.length, this, LongSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (long v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeLong(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -45,7 +45,9 @@ public final class LongArraySimpledCoder<R extends Reader, W extends Writer> ext
|
||||
public long[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, LongSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, LongSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.json.*;
|
||||
|
||||
/**
|
||||
@@ -49,7 +47,9 @@ public final class LongSimpledCoder<R extends Reader, W extends Writer> extends
|
||||
if (value == null) {
|
||||
out.writeSmallString("0x0");
|
||||
} else {
|
||||
if (value < 0) throw new NumberFormatException("Negative values (" + value + ") are not supported");
|
||||
if (value < 0) {
|
||||
throw new NumberFormatException("Negative values (" + value + ") are not supported");
|
||||
}
|
||||
out.writeSmallString("0x" + Long.toHexString(value));
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,9 @@ public final class LongSimpledCoder<R extends Reader, W extends Writer> extends
|
||||
@Override
|
||||
public Long convertFrom(R in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return 0L;
|
||||
if (str == null) {
|
||||
return 0L;
|
||||
}
|
||||
try {
|
||||
if (str.length() > 2 && str.charAt(0) == '0' && (str.charAt(1) == 'x' || str.charAt(1) == 'X')) {
|
||||
return Long.parseLong(str.substring(2), 16);
|
||||
|
||||
@@ -5,13 +5,15 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.util.regex.*;
|
||||
import java.util.regex.Pattern;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* Pattern 的SimpledCoder实现
|
||||
* Pattern 的SimpledCoder实现
|
||||
*
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* <p> 详情见: https://redkale.org
|
||||
* @author zhangjx
|
||||
* @param <R> Reader输入的子类型
|
||||
* @param <W> Writer输出的子类型
|
||||
@@ -32,7 +34,9 @@ public class PatternSimpledCoder<R extends Reader, W extends Writer> extends Sim
|
||||
@Override
|
||||
public Pattern convertFrom(R in) {
|
||||
String value = in.readString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
int pos = value.indexOf(',');
|
||||
return Pattern.compile(value.substring(pos + 1), Integer.parseInt(value.substring(0, pos)));
|
||||
}
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* short[] 的SimpledCoder实现
|
||||
@@ -32,7 +30,9 @@ public final class ShortArraySimpledCoder<R extends Reader, W extends Writer> ex
|
||||
if (out.writeArrayB(values.length, this, ShortSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (short v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeShort(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -44,7 +44,9 @@ public final class ShortArraySimpledCoder<R extends Reader, W extends Writer> ex
|
||||
public short[] convertFrom(R in) {
|
||||
int len = in.readArrayB(null, null, ShortSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, ShortSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -5,14 +5,14 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* short 的SimpledCoder实现
|
||||
*
|
||||
* <p> 详情见: https://redkale.org
|
||||
* <p>
|
||||
* 详情见: https://redkale.org
|
||||
*
|
||||
* @author zhangjx
|
||||
* @param <R> Reader输入的子类型
|
||||
* @param <W> Writer输出的子类型
|
||||
|
||||
@@ -30,7 +30,9 @@ public final class StringArraySimpledCoder<R extends Reader, W extends Writer> e
|
||||
if (out.writeArrayB(values.length, this, StringSimpledCoder.instance, values) < 0) {
|
||||
boolean flag = false;
|
||||
for (String v : values) {
|
||||
if (flag) out.writeArrayMark();
|
||||
if (flag) {
|
||||
out.writeArrayMark();
|
||||
}
|
||||
out.writeString(v);
|
||||
flag = true;
|
||||
}
|
||||
@@ -46,7 +48,9 @@ public final class StringArraySimpledCoder<R extends Reader, W extends Writer> e
|
||||
public String[] convertFrom(R in, DeMember member) {
|
||||
int len = in.readArrayB(member, null, StringSimpledCoder.instance);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = in.readMemberContentLength(null, StringSimpledCoder.instance);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
|
||||
@@ -33,7 +33,9 @@ public class ThrowableSimpledCoder<R extends Reader, W extends Writer> extends S
|
||||
@Override
|
||||
public Throwable convertFrom(R in) {
|
||||
String value = in.readString();
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return new Exception(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import org.redkale.convert.Reader;
|
||||
import org.redkale.convert.Writer;
|
||||
import org.redkale.convert.SimpledCoder;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
* Type 的SimpledCoder实现 只支持Type的子类Class
|
||||
@@ -35,7 +33,9 @@ public class TypeSimpledCoder<R extends Reader, W extends Writer> extends Simple
|
||||
@Override
|
||||
public Class convertFrom(R in) {
|
||||
String str = in.readSmallString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Thread.currentThread().getContextClassLoader().loadClass(str);
|
||||
} catch (Throwable e) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.net.*;
|
||||
import java.net.URI;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
@@ -33,7 +33,9 @@ public class URISimpledCoder<R extends Reader, W extends Writer> extends Simpled
|
||||
@Override
|
||||
public URI convertFrom(Reader in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new URI(str);
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
*/
|
||||
package org.redkale.convert.ext;
|
||||
|
||||
import java.net.*;
|
||||
import java.net.URL;
|
||||
import org.redkale.convert.*;
|
||||
|
||||
/**
|
||||
@@ -33,7 +33,9 @@ public class URLSimpledCoder<R extends Reader, W extends Writer> extends Simpled
|
||||
@Override
|
||||
public URL convertFrom(Reader in) {
|
||||
final String str = in.readString();
|
||||
if (str == null) return null;
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new URL(str);
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
*/
|
||||
package org.redkale.convert.json;
|
||||
|
||||
import java.nio.*;
|
||||
import java.nio.charset.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.UnmappableCharacterException;
|
||||
import org.redkale.convert.*;
|
||||
import static org.redkale.convert.Reader.*;
|
||||
|
||||
@@ -34,7 +34,9 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
protected JsonByteBufferReader(ConvertMask mask, ByteBuffer... buffers) {
|
||||
this.mask = mask;
|
||||
this.buffers = buffers;
|
||||
if (buffers != null && buffers.length > 0) this.currentBuffer = buffers[currentIndex];
|
||||
if (buffers != null && buffers.length > 0) {
|
||||
this.currentBuffer = buffers[currentIndex];
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -80,7 +82,9 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
}
|
||||
if (this.currentBuffer != null) {
|
||||
int remain = this.currentBuffer.remaining();
|
||||
if (remain == 0 && this.currentIndex + 1 >= this.buffers.length) return 0;
|
||||
if (remain == 0 && this.currentIndex + 1 >= this.buffers.length) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
byte b = nextByte();
|
||||
if (b >= 0) {// 1 byte, 7 bits: 0xxxxxxx
|
||||
@@ -91,7 +95,9 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
return (char) ((b << 12) ^ (nextByte() << 6) ^ (nextByte() ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80))));
|
||||
} else if ((b >> 3) == -2) {// 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
|
||||
int uc = ((b << 18) ^ (nextByte() << 12) ^ (nextByte() << 6) ^ (nextByte() ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80))));
|
||||
if (sb != null) sb.append(Character.highSurrogate(uc));
|
||||
if (sb != null) {
|
||||
sb.append(Character.highSurrogate(uc));
|
||||
}
|
||||
return Character.lowSurrogate(uc);
|
||||
} else {
|
||||
throw new RuntimeException(new UnmappableCharacterException(4));
|
||||
@@ -117,9 +123,15 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
public final String readObjectB(final Class clazz) {
|
||||
this.fieldIndex = 0; //必须要重置为0
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == '{') return "";
|
||||
if (ch == 'n' && nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') return null;
|
||||
if (ch == 'N' && nextChar() == 'U' && nextChar() == 'L' && nextChar() == 'L') return null;
|
||||
if (ch == '{') {
|
||||
return "";
|
||||
}
|
||||
if (ch == 'n' && nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') {
|
||||
return null;
|
||||
}
|
||||
if (ch == 'N' && nextChar() == 'U' && nextChar() == 'L' && nextChar() == 'L') {
|
||||
return null;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(ch);
|
||||
char one;
|
||||
@@ -142,9 +154,15 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
@Override
|
||||
public final int readArrayB(DeMember member, byte[] typevals, Decodeable decoder) {
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == '[' || ch == '{') return SIGN_NOLENGTH;
|
||||
if (ch == 'n' && nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') return SIGN_NULL;
|
||||
if (ch == 'N' && nextChar() == 'U' && nextChar() == 'L' && nextChar() == 'L') return SIGN_NULL;
|
||||
if (ch == '[' || ch == '{') {
|
||||
return SIGN_NOLENGTH;
|
||||
}
|
||||
if (ch == 'n' && nextChar() == 'u' && nextChar() == 'l' && nextChar() == 'l') {
|
||||
return SIGN_NULL;
|
||||
}
|
||||
if (ch == 'N' && nextChar() == 'U' && nextChar() == 'L' && nextChar() == 'L') {
|
||||
return SIGN_NULL;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(ch);
|
||||
char one;
|
||||
@@ -161,7 +179,9 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
@Override
|
||||
public final void readBlank() {
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == ':') return;
|
||||
if (ch == ':') {
|
||||
return;
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(ch);
|
||||
char one;
|
||||
@@ -180,7 +200,9 @@ public class JsonByteBufferReader extends JsonReader {
|
||||
@Override
|
||||
public final String readSmallString() {
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == 0) return null;
|
||||
if (ch == 0) {
|
||||
return null;
|
||||
}
|
||||
final StringBuilder sb = new StringBuilder();
|
||||
if (ch == '"' || ch == '\'') {
|
||||
final char quote = ch;
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
package org.redkale.convert.json;
|
||||
|
||||
import java.nio.*;
|
||||
import java.nio.charset.*;
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.util.*;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Supplier;
|
||||
import org.redkale.convert.ConvertException;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
/**
|
||||
* 以ByteBuffer为数据载体的JsonWriter
|
||||
@@ -61,16 +61,22 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
}
|
||||
|
||||
public ByteBuffer[] toBuffers() {
|
||||
if (buffers == null) return new ByteBuffer[0];
|
||||
if (buffers == null) {
|
||||
return new ByteBuffer[0];
|
||||
}
|
||||
for (int i = index; i < this.buffers.length; i++) {
|
||||
ByteBuffer buf = this.buffers[i];
|
||||
if (buf.position() != 0) buf.flip();
|
||||
if (buf.position() != 0) {
|
||||
buf.flip();
|
||||
}
|
||||
}
|
||||
return this.buffers;
|
||||
}
|
||||
|
||||
public int count() {
|
||||
if (this.buffers == null) return 0;
|
||||
if (this.buffers == null) {
|
||||
return 0;
|
||||
}
|
||||
int len = 0;
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
len += buffer.remaining();
|
||||
@@ -103,7 +109,9 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
|
||||
@Override
|
||||
public void writeTo(final char ch) {
|
||||
if (ch > Byte.MAX_VALUE) throw new ConvertException("writeTo char(int.value = " + (int) ch + ") must be less 127");
|
||||
if (ch > Byte.MAX_VALUE) {
|
||||
throw new ConvertException("writeTo char(int.value = " + (int) ch + ") must be less 127");
|
||||
}
|
||||
expand(1);
|
||||
this.buffers[index].put((byte) ch);
|
||||
}
|
||||
@@ -133,7 +141,9 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
buffer.put(chs, offset, bsize);
|
||||
offset += bsize;
|
||||
remain -= bsize;
|
||||
if (remain < 1) break;
|
||||
if (remain < 1) {
|
||||
break;
|
||||
}
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
}
|
||||
@@ -148,10 +158,14 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
bb = charset.encode(CharBuffer.wrap(chs, start, len));
|
||||
byteLength += bb.remaining();
|
||||
}
|
||||
if (expandsize < 0) expandsize = expand(byteLength);
|
||||
if (expandsize < 0) {
|
||||
expandsize = expand(byteLength);
|
||||
}
|
||||
if (expandsize == 0) { // 只需要一个buffer
|
||||
final ByteBuffer buffer = this.buffers[index];
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
|
||||
if (charset == null) { //UTF-8
|
||||
final int limit = start + len;
|
||||
@@ -179,12 +193,16 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
buffer.put(bb);
|
||||
}
|
||||
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
return;
|
||||
}
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
if (quote) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
if (charset == null) { //UTF-8
|
||||
@@ -192,41 +210,65 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
for (int i = start; i < limit; i++) {
|
||||
char c = chs[i];
|
||||
if (c < 0x80) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) c);
|
||||
} else if (c < 0x800) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0xc0 | (c >> 6)));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | (c & 0x3f)));
|
||||
} else if (Character.isSurrogate(c)) { //连取两个
|
||||
int uc = Character.toCodePoint(c, chs[i + 1]);
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0xf0 | ((uc >> 18))));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | ((uc >> 12) & 0x3f)));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | ((uc >> 6) & 0x3f)));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | (uc & 0x3f)));
|
||||
i++;
|
||||
} else {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0xe0 | ((c >> 12))));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | ((c >> 6) & 0x3f)));
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) (0x80 | (c & 0x3f)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
while (bb.hasRemaining()) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(bb.get());
|
||||
}
|
||||
}
|
||||
if (quote) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
}
|
||||
@@ -274,21 +316,31 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
int expandsize = expand(bs.length + (quote ? 2 : 0));
|
||||
if (expandsize == 0) {// 只需要一个buffer
|
||||
final ByteBuffer buffer = this.buffers[index];
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
buffer.put(bs);
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
if (quote) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
for (byte b : bs) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
if (quote) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
}
|
||||
@@ -306,11 +358,15 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
}
|
||||
@@ -328,11 +384,15 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
}
|
||||
@@ -350,11 +410,15 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
}
|
||||
@@ -374,19 +438,27 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
}
|
||||
@@ -405,15 +477,21 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -432,15 +510,21 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -459,15 +543,21 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -492,23 +582,33 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -543,23 +643,33 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -583,23 +693,33 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
} else {
|
||||
ByteBuffer buffer = this.buffers[index];
|
||||
for (byte b : bs1) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs2) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs3) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
for (byte b : bs4) {
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put(b);
|
||||
}
|
||||
{
|
||||
if (!buffer.hasRemaining()) buffer = nextByteBuffer();
|
||||
if (!buffer.hasRemaining()) {
|
||||
buffer = nextByteBuffer();
|
||||
}
|
||||
buffer.put((byte) '}');
|
||||
}
|
||||
}
|
||||
@@ -659,7 +779,9 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
expandsize = expand(byteLength);
|
||||
if (expandsize == 0) { // 只需要一个buffer
|
||||
final ByteBuffer buffer = this.buffers[index];
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
for (int i = 0; i < chs.length; i++) {
|
||||
char c = chs[i];
|
||||
switch (c) {
|
||||
@@ -694,7 +816,9 @@ public class JsonByteBufferWriter extends JsonWriter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (quote) buffer.put((byte) '"');
|
||||
if (quote) {
|
||||
buffer.put((byte) '"');
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
|
||||
protected byte[] expand(int len) {
|
||||
int newcount = count + len;
|
||||
if (newcount <= content.length) return content;
|
||||
if (newcount <= content.length) {
|
||||
return content;
|
||||
}
|
||||
byte[] newdata = new byte[Math.max(content.length * 3 / 2, newcount)];
|
||||
System.arraycopy(content, 0, newdata, 0, count);
|
||||
this.content = newdata;
|
||||
@@ -96,7 +98,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
|
||||
@Override
|
||||
public final void writeFieldName(EnMember member, String fieldName, Type fieldType, int fieldPos) {
|
||||
if (this.comma) writeTo(',');
|
||||
if (this.comma) {
|
||||
writeTo(',');
|
||||
}
|
||||
if (member != null) {
|
||||
byte[] bs = member.getJsonFieldNameBytes();
|
||||
expand(bs.length);
|
||||
@@ -366,7 +370,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
private void writeEscapeLatinString(final boolean quote, byte[] value) {
|
||||
byte[] bytes = expand(value.length * 2 + 2);
|
||||
int curr = count;
|
||||
if (quote) bytes[curr++] = '"';
|
||||
if (quote) {
|
||||
bytes[curr++] = '"';
|
||||
}
|
||||
for (byte b : value) {
|
||||
if (b == '"') {
|
||||
bytes[curr++] = '\\';
|
||||
@@ -391,7 +397,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
bytes[curr++] = b;
|
||||
}
|
||||
}
|
||||
if (quote) bytes[curr++] = '"';
|
||||
if (quote) {
|
||||
bytes[curr++] = '"';
|
||||
}
|
||||
count = curr;
|
||||
}
|
||||
|
||||
@@ -412,7 +420,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
}
|
||||
byte[] bytes = expand(value.length() * 4 + 2);
|
||||
int curr = count;
|
||||
if (quote) bytes[curr++] = '"';
|
||||
if (quote) {
|
||||
bytes[curr++] = '"';
|
||||
}
|
||||
int len = value.length();
|
||||
for (int i = 0; i < len; i++) {
|
||||
char ch = value.charAt(i);
|
||||
@@ -457,7 +467,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (quote) bytes[curr++] = '"';
|
||||
if (quote) {
|
||||
bytes[curr++] = '"';
|
||||
}
|
||||
count = curr;
|
||||
}
|
||||
|
||||
@@ -485,7 +497,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
return;
|
||||
}
|
||||
final char sign = value >= 0 ? 0 : '-';
|
||||
if (value < 0) value = -value;
|
||||
if (value < 0) {
|
||||
value = -value;
|
||||
}
|
||||
int size;
|
||||
for (int i = 0;; i++) {
|
||||
if (value <= sizeTable[i]) {
|
||||
@@ -493,7 +507,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) size++; //负数
|
||||
if (sign != 0) {
|
||||
size++; //负数
|
||||
}
|
||||
byte[] bytes = expand(size);
|
||||
|
||||
int q, r;
|
||||
@@ -516,9 +532,13 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
r = value - ((q << 3) + (q << 1)); // r = i-(q*10) ...
|
||||
bytes[--charPos] = (byte) digits[r];
|
||||
value = q;
|
||||
if (value == 0) break;
|
||||
if (value == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) {
|
||||
bytes[--charPos] = (byte) sign;
|
||||
}
|
||||
if (sign != 0) bytes[--charPos] = (byte) sign;
|
||||
count += size;
|
||||
}
|
||||
|
||||
@@ -532,7 +552,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
return;
|
||||
}
|
||||
final char sign = value >= 0 ? 0 : '-';
|
||||
if (value < 0) value = -value;
|
||||
if (value < 0) {
|
||||
value = -value;
|
||||
}
|
||||
int size = 19;
|
||||
long p = 10;
|
||||
for (int i = 1; i < 19; i++) {
|
||||
@@ -542,7 +564,9 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
}
|
||||
p = 10 * p;
|
||||
}
|
||||
if (sign != 0) size++; //负数
|
||||
if (sign != 0) {
|
||||
size++; //负数
|
||||
}
|
||||
byte[] bytes = expand(size);
|
||||
|
||||
long q;
|
||||
@@ -578,9 +602,13 @@ public class JsonBytesWriter extends JsonWriter implements ByteTuple {
|
||||
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
|
||||
bytes[--charPos] = (byte) digits[r];
|
||||
i2 = q2;
|
||||
if (i2 == 0) break;
|
||||
if (i2 == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) {
|
||||
bytes[--charPos] = (byte) sign;
|
||||
}
|
||||
if (sign != 0) bytes[--charPos] = (byte) sign;
|
||||
count += size;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
package org.redkale.convert.json;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -59,7 +59,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
*/
|
||||
private char[] expand(int len) {
|
||||
int newcount = count + len;
|
||||
if (newcount <= content.length) return content;
|
||||
if (newcount <= content.length) {
|
||||
return content;
|
||||
}
|
||||
char[] newdata = new char[Math.max(content.length * 3 / 2, newcount)];
|
||||
System.arraycopy(content, 0, newdata, 0, count);
|
||||
this.content = newdata;
|
||||
@@ -104,10 +106,14 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
public void writeLatin1To(final boolean quote, final String value) {
|
||||
int len = value.length();
|
||||
expand(len + (quote ? 2 : 0));
|
||||
if (quote) content[count++] = '"';
|
||||
if (quote) {
|
||||
content[count++] = '"';
|
||||
}
|
||||
value.getChars(0, len, content, count);
|
||||
count += len;
|
||||
if (quote) content[count++] = '"';
|
||||
if (quote) {
|
||||
content[count++] = '"';
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -318,7 +324,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
return;
|
||||
}
|
||||
expand(value.length() * 2 + 2);
|
||||
if (quote) content[count++] = '"';
|
||||
if (quote) {
|
||||
content[count++] = '"';
|
||||
}
|
||||
for (char ch : Utility.charArray(value)) {
|
||||
switch (ch) {
|
||||
case '\n':
|
||||
@@ -346,7 +354,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (quote) content[count++] = '"';
|
||||
if (quote) {
|
||||
content[count++] = '"';
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -367,7 +377,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
return;
|
||||
}
|
||||
final char sign = value >= 0 ? 0 : '-';
|
||||
if (value < 0) value = -value;
|
||||
if (value < 0) {
|
||||
value = -value;
|
||||
}
|
||||
int size;
|
||||
for (int i = 0;; i++) {
|
||||
if (value <= sizeTable[i]) {
|
||||
@@ -375,7 +387,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) size++; //负数
|
||||
if (sign != 0) {
|
||||
size++; //负数
|
||||
}
|
||||
expand(size);
|
||||
|
||||
int q, r;
|
||||
@@ -398,9 +412,13 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
r = value - ((q << 3) + (q << 1)); // r = i-(q*10) ...
|
||||
content[--charPos] = digits[r];
|
||||
value = q;
|
||||
if (value == 0) break;
|
||||
if (value == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) {
|
||||
content[--charPos] = sign;
|
||||
}
|
||||
if (sign != 0) content[--charPos] = sign;
|
||||
count += size;
|
||||
}
|
||||
|
||||
@@ -411,7 +429,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
return;
|
||||
}
|
||||
final char sign = value >= 0 ? 0 : '-';
|
||||
if (value < 0) value = -value;
|
||||
if (value < 0) {
|
||||
value = -value;
|
||||
}
|
||||
int size = 19;
|
||||
long p = 10;
|
||||
for (int i = 1; i < 19; i++) {
|
||||
@@ -421,7 +441,9 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
}
|
||||
p = 10 * p;
|
||||
}
|
||||
if (sign != 0) size++; //负数
|
||||
if (sign != 0) {
|
||||
size++; //负数
|
||||
}
|
||||
expand(size);
|
||||
|
||||
long q;
|
||||
@@ -457,9 +479,13 @@ public class JsonCharsWriter extends JsonWriter {
|
||||
r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ...
|
||||
content[--charPos] = digits[r];
|
||||
i2 = q2;
|
||||
if (i2 == 0) break;
|
||||
if (i2 == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sign != 0) {
|
||||
content[--charPos] = sign;
|
||||
}
|
||||
if (sign != 0) content[--charPos] = sign;
|
||||
count += size;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
package org.redkale.convert.json;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.*;
|
||||
import java.nio.charset.*;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.function.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.service.RetResult;
|
||||
@@ -102,29 +102,39 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
//------------------------------ convertFrom -----------------------------------------------------------
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final byte[] bytes) {
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(type, new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final byte[] bytes, final int offset, final int length) {
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(type, new String(bytes, offset, length, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final String text) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(type, Utility.charArray(text));
|
||||
}
|
||||
|
||||
public <T> T convertFrom(final Type type, final char[] text) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(type, text, 0, text.length);
|
||||
}
|
||||
|
||||
public <T> T convertFrom(final Type type, final char[] text, final int offset, final int length) {
|
||||
if (text == null || type == null) return null;
|
||||
if (text == null || type == null) {
|
||||
return null;
|
||||
}
|
||||
Decodeable decoder = this.lastConvertDecodeable;
|
||||
if (decoder == null || decoder.getType() != type) {
|
||||
decoder = factory.loadDecoder(type);
|
||||
@@ -135,7 +145,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
}
|
||||
|
||||
public <T> T convertFrom(final Type type, final InputStream in) {
|
||||
if (type == null || in == null) return null;
|
||||
if (type == null || in == null) {
|
||||
return null;
|
||||
}
|
||||
Decodeable decoder = this.lastConvertDecodeable;
|
||||
if (decoder == null || decoder.getType() != type) {
|
||||
decoder = factory.loadDecoder(type);
|
||||
@@ -146,7 +158,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final ByteBuffer... buffers) {
|
||||
if (type == null || buffers == null || buffers.length == 0) return null;
|
||||
if (type == null || buffers == null || buffers.length == 0) {
|
||||
return null;
|
||||
}
|
||||
Decodeable decoder = this.lastConvertDecodeable;
|
||||
if (decoder == null || decoder.getType() != type) {
|
||||
decoder = factory.loadDecoder(type);
|
||||
@@ -157,7 +171,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
@Override
|
||||
public <T> T convertFrom(final Type type, final ConvertMask mask, final ByteBuffer... buffers) {
|
||||
if (type == null || buffers == null || buffers.length == 0) return null;
|
||||
if (type == null || buffers == null || buffers.length == 0) {
|
||||
return null;
|
||||
}
|
||||
Decodeable decoder = this.lastConvertDecodeable;
|
||||
if (decoder == null || decoder.getType() != type) {
|
||||
decoder = factory.loadDecoder(type);
|
||||
@@ -167,7 +183,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
}
|
||||
|
||||
public <T> T convertFrom(final Type type, final JsonReader reader) {
|
||||
if (type == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
Decodeable decoder = this.lastConvertDecodeable;
|
||||
if (decoder == null || decoder.getType() != type) {
|
||||
decoder = factory.loadDecoder(type);
|
||||
@@ -180,19 +198,25 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final String text) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
return (V) convertFrom(Utility.charArray(text));
|
||||
}
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final char[] text) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
return (V) convertFrom(text, 0, text.length);
|
||||
}
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final char[] text, final int offset, final int length) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
//final JsonReader in = readerPool.get();
|
||||
//in.setText(text, offset, length);
|
||||
Object rs = new AnyDecoder(factory).convertFrom(new JsonReader(text, offset, length));
|
||||
@@ -202,64 +226,86 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final InputStream in) {
|
||||
if (in == null) return null;
|
||||
if (in == null) {
|
||||
return null;
|
||||
}
|
||||
return (V) new AnyDecoder(factory).convertFrom(new JsonStreamReader(in));
|
||||
}
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final ByteBuffer... buffers) {
|
||||
if (buffers == null || buffers.length == 0) return null;
|
||||
if (buffers == null || buffers.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return (V) new AnyDecoder(factory).convertFrom(new JsonByteBufferReader((ConvertMask) null, buffers));
|
||||
}
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final ConvertMask mask, final ByteBuffer... buffers) {
|
||||
if (buffers == null || buffers.length == 0) return null;
|
||||
if (buffers == null || buffers.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return (V) new AnyDecoder(factory).convertFrom(new JsonByteBufferReader(mask, buffers));
|
||||
}
|
||||
|
||||
//返回非null的值是由String、ArrayList、HashMap任意组合的对象
|
||||
public <V> V convertFrom(final JsonReader reader) {
|
||||
if (reader == null) return null;
|
||||
if (reader == null) {
|
||||
return null;
|
||||
}
|
||||
return (V) new AnyDecoder(factory).convertFrom(reader);
|
||||
}
|
||||
|
||||
//json数据的数组长度必须和types个数相同
|
||||
public Object[] convertFrom(final Type[] types, final String text) {
|
||||
if (text == null) return null;
|
||||
if (text == null) {
|
||||
return null;
|
||||
}
|
||||
return new JsonMultiArrayDecoder(getFactory(), types).convertFrom(new JsonReader(text));
|
||||
}
|
||||
|
||||
//json数据的数组长度必须和types个数相同
|
||||
public Object[] convertFrom(final Type[] types, final byte[] bytes) {
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(types, new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
//json数据的数组长度必须和types个数相同
|
||||
public Object[] convertFrom(final Type[] types, final byte[] bytes, final int offset, final int length) {
|
||||
if (bytes == null) return null;
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return convertFrom(types, new String(bytes, offset, length, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
//------------------------------ convertTo -----------------------------------------------------------
|
||||
@Override
|
||||
public String convertTo(final Object value) {
|
||||
if (value == null) return "null";
|
||||
if (value == null) {
|
||||
return "null";
|
||||
}
|
||||
return convertTo(value.getClass(), value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String convertTo(final Type type, final Object value) {
|
||||
if (type == null) return null;
|
||||
if (value == null) return "null";
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
if (value == null) {
|
||||
return "null";
|
||||
}
|
||||
JsonBytesWriter writer = pollJsonBytesWriter();
|
||||
Encodeable encoder = this.lastConvertEncodeable;
|
||||
if (encoder == null || encoder.getType() != type) {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
|
||||
String result = writer.toString();
|
||||
@@ -269,21 +315,29 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
@Override
|
||||
public byte[] convertToBytes(final Object value) {
|
||||
if (value == null) return null;
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return convertToBytes(value.getClass(), value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] convertToBytes(final Type type, final Object value) {
|
||||
if (type == null) return null;
|
||||
if (value == null) return null;
|
||||
if (type == null) {
|
||||
return null;
|
||||
}
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
JsonBytesWriter writer = pollJsonBytesWriter();
|
||||
Encodeable encoder = this.lastConvertEncodeable;
|
||||
if (encoder == null || encoder.getType() != type) {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
|
||||
byte[] result = writer.toBytes();
|
||||
@@ -307,7 +361,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
}
|
||||
writer.completed(handler, offerBytesConsumer);
|
||||
@@ -329,7 +385,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
}
|
||||
writer.directTo(array);
|
||||
@@ -344,7 +402,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
}
|
||||
|
||||
public void convertTo(final OutputStream out, final Type type, final Object value) {
|
||||
if (type == null) return;
|
||||
if (type == null) {
|
||||
return;
|
||||
}
|
||||
if (value == null) {
|
||||
configWrite(new JsonStreamWriter(tiny, out)).writeNull();
|
||||
} else {
|
||||
@@ -354,14 +414,18 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, final Object value) {
|
||||
if (supplier == null) return null;
|
||||
if (supplier == null) {
|
||||
return null;
|
||||
}
|
||||
JsonByteBufferWriter out = configWrite(new JsonByteBufferWriter(tiny, supplier));
|
||||
if (value == null) {
|
||||
out.writeNull();
|
||||
@@ -373,7 +437,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
|
||||
@Override
|
||||
public ByteBuffer[] convertTo(final Supplier<ByteBuffer> supplier, final Type type, final Object value) {
|
||||
if (supplier == null || type == null) return null;
|
||||
if (supplier == null || type == null) {
|
||||
return null;
|
||||
}
|
||||
JsonByteBufferWriter out = configWrite(new JsonByteBufferWriter(tiny, supplier));
|
||||
if (value == null) {
|
||||
out.writeNull();
|
||||
@@ -395,14 +461,18 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void convertTo(final JsonWriter writer, final Type type, final Object value) {
|
||||
if (type == null) return;
|
||||
if (type == null) {
|
||||
return;
|
||||
}
|
||||
if (value == null) {
|
||||
writer.writeNull();
|
||||
} else {
|
||||
@@ -411,7 +481,9 @@ public class JsonConvert extends TextConvert<JsonReader, JsonWriter> {
|
||||
encoder = factory.loadEncoder(type);
|
||||
this.lastConvertEncodeable = encoder;
|
||||
}
|
||||
if (encoder.specifyable()) writer.specify(type);
|
||||
if (encoder.specifyable()) {
|
||||
writer.specify(type);
|
||||
}
|
||||
encoder.convertTo(writer, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,35 +45,79 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
}
|
||||
|
||||
private static boolean checkMemberType(final JsonFactory factory, final Class declaringClass, Type type, Class clazz) {
|
||||
if (type == String.class) return true;
|
||||
if (clazz.isPrimitive()) return true;
|
||||
if (clazz.isEnum()) return true;
|
||||
if (type == boolean[].class) return true;
|
||||
if (type == byte[].class) return true;
|
||||
if (type == short[].class) return true;
|
||||
if (type == char[].class) return true;
|
||||
if (type == int[].class) return true;
|
||||
if (type == float[].class) return true;
|
||||
if (type == long[].class) return true;
|
||||
if (type == double[].class) return true;
|
||||
if (type == Boolean[].class) return true;
|
||||
if (type == Byte[].class) return true;
|
||||
if (type == Short[].class) return true;
|
||||
if (type == Character[].class) return true;
|
||||
if (type == Integer[].class) return true;
|
||||
if (type == Float[].class) return true;
|
||||
if (type == Long[].class) return true;
|
||||
if (type == Double[].class) return true;
|
||||
if (type == String[].class) return true;
|
||||
if (type == String.class) {
|
||||
return true;
|
||||
}
|
||||
if (clazz.isPrimitive()) {
|
||||
return true;
|
||||
}
|
||||
if (clazz.isEnum()) {
|
||||
return true;
|
||||
}
|
||||
if (type == boolean[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == byte[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == short[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == char[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == int[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == float[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == long[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == double[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Boolean[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Byte[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Short[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Character[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Integer[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Float[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Long[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == Double[].class) {
|
||||
return true;
|
||||
}
|
||||
if (type == String[].class) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (declaringClass == clazz) return false;
|
||||
if (declaringClass == clazz) {
|
||||
return false;
|
||||
}
|
||||
if (Collection.class.isAssignableFrom(clazz) && type instanceof ParameterizedType) {
|
||||
Type[] ts = ((ParameterizedType) type).getActualTypeArguments();
|
||||
if (ts.length == 1) {
|
||||
Type t = ts[0];
|
||||
if (t == Boolean.class || t == Byte.class || t == Short.class || t == Character.class
|
||||
|| t == Integer.class || t == Float.class || t == Long.class || t == Double.class
|
||||
|| t == String.class || ((t instanceof Class) && ((Class) t).isEnum())) return true;
|
||||
|| t == String.class || ((t instanceof Class) && ((Class) t).isEnum())) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -82,27 +126,65 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
|
||||
//字段全部是primitive或String类型,且没有泛型的类才能动态生成JsonDynEncoder, 不支持的返回null
|
||||
public static JsonDynEncoder createDyncEncoder(final JsonFactory factory, final Type type) {
|
||||
if (!(type instanceof Class)) return null;
|
||||
if (!(type instanceof Class)) {
|
||||
return null;
|
||||
}
|
||||
//发现有自定义的基础数据类型Encoder就不动态生成JsonDynEncoder了
|
||||
if (factory.loadEncoder(boolean.class) != BoolSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(byte.class) != ByteSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(short.class) != ShortSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(char.class) != CharSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(int.class) != IntSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(float.class) != FloatSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(long.class) != LongSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(double.class) != DoubleSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(String.class) != StringSimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(boolean.class) != BoolSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(byte.class) != ByteSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(short.class) != ShortSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(char.class) != CharSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(int.class) != IntSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(float.class) != FloatSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(long.class) != LongSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(double.class) != DoubleSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(String.class) != StringSimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
//array
|
||||
if (factory.loadEncoder(boolean[].class) != BoolArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(byte[].class) != ByteArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(short[].class) != ShortArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(char[].class) != CharArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(int[].class) != IntArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(float[].class) != FloatArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(long[].class) != LongArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(double[].class) != DoubleArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(String[].class) != StringArraySimpledCoder.instance) return null;
|
||||
if (factory.loadEncoder(boolean[].class) != BoolArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(byte[].class) != ByteArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(short[].class) != ShortArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(char[].class) != CharArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(int[].class) != IntArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(float[].class) != FloatArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(long[].class) != LongArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(double[].class) != DoubleArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
if (factory.loadEncoder(String[].class) != StringArraySimpledCoder.instance) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final Class clazz = (Class) type;
|
||||
List<AccessibleObject> members = null;
|
||||
@@ -111,52 +193,100 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
ConvertColumnEntry ref;
|
||||
RedkaleClassLoader.putReflectionPublicFields(clazz.getName());
|
||||
for (final Field field : clazz.getFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers())) continue;
|
||||
if (factory.isConvertDisabled(field)) continue;
|
||||
if (Modifier.isStatic(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(field)) {
|
||||
continue;
|
||||
}
|
||||
ref = factory.findRef(clazz, field);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (!(checkMemberType(factory, clazz, field.getGenericType(), field.getType()))) return null;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
if (!(checkMemberType(factory, clazz, field.getGenericType(), field.getType()))) {
|
||||
return null;
|
||||
}
|
||||
String name = convertFieldName(factory, clazz, field);
|
||||
if (names.contains(name)) continue;
|
||||
if (names.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
names.add(name);
|
||||
if (members == null) members = new ArrayList<>();
|
||||
if (members == null) {
|
||||
members = new ArrayList<>();
|
||||
}
|
||||
members.add(field);
|
||||
}
|
||||
RedkaleClassLoader.putReflectionPublicMethods(clazz.getName());
|
||||
for (final Method method : clazz.getMethods()) {
|
||||
if (Modifier.isStatic(method.getModifiers())) continue;
|
||||
if (Modifier.isAbstract(method.getModifiers())) continue;
|
||||
if (method.isSynthetic()) continue;
|
||||
if (method.getName().length() < 3) continue;
|
||||
if (method.getName().equals("getClass")) continue;
|
||||
if (Modifier.isStatic(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (Modifier.isAbstract(method.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
if (method.isSynthetic()) {
|
||||
continue;
|
||||
}
|
||||
if (method.getName().length() < 3) {
|
||||
continue;
|
||||
}
|
||||
if (method.getName().equals("getClass")) {
|
||||
continue;
|
||||
}
|
||||
if (!(method.getName().startsWith("is") && method.getName().length() > 2)
|
||||
&& !(method.getName().startsWith("get") && method.getName().length() > 3)) continue;
|
||||
if (factory.isConvertDisabled(method)) continue;
|
||||
if (method.getParameterTypes().length != 0) continue;
|
||||
if (method.getReturnType() == void.class) continue;
|
||||
&& !(method.getName().startsWith("get") && method.getName().length() > 3)) {
|
||||
continue;
|
||||
}
|
||||
if (factory.isConvertDisabled(method)) {
|
||||
continue;
|
||||
}
|
||||
if (method.getParameterTypes().length != 0) {
|
||||
continue;
|
||||
}
|
||||
if (method.getReturnType() == void.class) {
|
||||
continue;
|
||||
}
|
||||
ref = factory.findRef(clazz, method);
|
||||
if (ref != null && ref.ignore()) continue;
|
||||
if (!(checkMemberType(factory, clazz, method.getGenericReturnType(), method.getReturnType()))) return null;
|
||||
if (ref != null && ref.ignore()) {
|
||||
continue;
|
||||
}
|
||||
if (!(checkMemberType(factory, clazz, method.getGenericReturnType(), method.getReturnType()))) {
|
||||
return null;
|
||||
}
|
||||
String name = convertFieldName(factory, clazz, method);
|
||||
if (names.contains(name)) continue;
|
||||
if (names.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
names.add(name);
|
||||
if (members == null) members = new ArrayList<>();
|
||||
if (members == null) {
|
||||
members = new ArrayList<>();
|
||||
}
|
||||
members.add(method);
|
||||
}
|
||||
if (members == null) return null;
|
||||
if (members == null) {
|
||||
return null;
|
||||
}
|
||||
Collections.sort(members, (o1, o2) -> {
|
||||
ConvertColumnEntry ref1 = factory.findRef(clazz, o1);
|
||||
ConvertColumnEntry ref2 = factory.findRef(clazz, o2);
|
||||
if ((ref1 != null && ref1.getIndex() > 0) || (ref2 != null && ref2.getIndex() > 0)) {
|
||||
int idx1 = ref1 == null ? Integer.MAX_VALUE / 2 : ref1.getIndex();
|
||||
int idx2 = ref2 == null ? Integer.MAX_VALUE / 2 : ref2.getIndex();
|
||||
if (idx1 != idx2) return idx1 - idx2;
|
||||
if (idx1 != idx2) {
|
||||
return idx1 - idx2;
|
||||
}
|
||||
}
|
||||
String n1 = ref1 == null || ref1.name().isEmpty() ? readGetSetFieldName(o1) : ref1.name();
|
||||
String n2 = ref2 == null || ref2.name().isEmpty() ? readGetSetFieldName(o2) : ref2.name();
|
||||
if (n1 == null && n2 == null) return 0;
|
||||
if (n1 == null) return -1;
|
||||
if (n2 == null) return 1;
|
||||
if (n1 == null && n2 == null) {
|
||||
return 0;
|
||||
}
|
||||
if (n1 == null) {
|
||||
return -1;
|
||||
}
|
||||
if (n2 == null) {
|
||||
return 1;
|
||||
}
|
||||
return n1.compareTo(n2);
|
||||
});
|
||||
return generateDyncEncoder(factory, clazz, members);
|
||||
@@ -173,13 +303,17 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
}
|
||||
|
||||
protected static ConvertSmallString readConvertSmallString(AccessibleObject element) {
|
||||
if (element instanceof Field) return ((Field) element).getAnnotation(ConvertSmallString.class);
|
||||
if (element instanceof Field) {
|
||||
return ((Field) element).getAnnotation(ConvertSmallString.class);
|
||||
}
|
||||
Method method = (Method) element;
|
||||
ConvertSmallString small = method.getAnnotation(ConvertSmallString.class);
|
||||
if (small == null) {
|
||||
try {
|
||||
Field f = method.getDeclaringClass().getDeclaredField(readGetSetFieldName(method));
|
||||
if (f != null) small = f.getAnnotation(ConvertSmallString.class);
|
||||
if (f != null) {
|
||||
small = f.getAnnotation(ConvertSmallString.class);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
@@ -187,18 +321,26 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
}
|
||||
|
||||
protected static Class readGetSetFieldType(AccessibleObject element) {
|
||||
if (element instanceof Field) return ((Field) element).getType();
|
||||
if (element instanceof Field) {
|
||||
return ((Field) element).getType();
|
||||
}
|
||||
return element == null ? null : ((Method) element).getReturnType();
|
||||
}
|
||||
|
||||
protected static String readGetSetFieldName(AccessibleObject element) {
|
||||
if (element instanceof Field) return ((Field) element).getName();
|
||||
if (element instanceof Field) {
|
||||
return ((Field) element).getName();
|
||||
}
|
||||
Method method = (Method) element;
|
||||
if (method == null) return null;
|
||||
if (method == null) {
|
||||
return null;
|
||||
}
|
||||
String fname = method.getName();
|
||||
if (!(fname.startsWith("is") && fname.length() > 2)
|
||||
&& !(fname.startsWith("get") && fname.length() > 3)
|
||||
&& !(fname.startsWith("set") && fname.length() > 3)) return fname;
|
||||
&& !(fname.startsWith("set") && fname.length() > 3)) {
|
||||
return fname;
|
||||
}
|
||||
fname = fname.substring(fname.startsWith("is") ? 2 : 3);
|
||||
if (fname.length() > 1 && !(fname.charAt(1) >= 'A' && fname.charAt(1) <= 'Z')) {
|
||||
fname = Character.toLowerCase(fname.charAt(0)) + fname.substring(1);
|
||||
@@ -211,8 +353,9 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
protected static JsonDynEncoder generateDyncEncoder(final JsonFactory factory, final Class clazz, final List<AccessibleObject> members) {
|
||||
final ObjectEncoder selfObjEncoder = factory.createObjectEncoder(clazz);
|
||||
selfObjEncoder.init(factory);
|
||||
if (selfObjEncoder.getMembers().length != members.size()) return null; //存在ignore等定制配置
|
||||
|
||||
if (selfObjEncoder.getMembers().length != members.size()) {
|
||||
return null; //存在ignore等定制配置
|
||||
}
|
||||
final String supDynName = JsonDynEncoder.class.getName().replace('.', '/');
|
||||
final String valtypeName = clazz.getName().replace('.', '/');
|
||||
final String writerName = JsonWriter.class.getName().replace('.', '/');
|
||||
@@ -234,7 +377,9 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
memberb.append(fieldname).append(',');
|
||||
final Class fieldtype = readGetSetFieldType(element);
|
||||
if (fieldtype != String.class && !fieldtype.isPrimitive()) {
|
||||
if (mixedNames0 == null) mixedNames0 = new HashMap<>();
|
||||
if (mixedNames0 == null) {
|
||||
mixedNames0 = new HashMap<>();
|
||||
}
|
||||
mixedNames0.put(fieldname, element);
|
||||
}
|
||||
}
|
||||
@@ -288,16 +433,21 @@ public abstract class JsonDynEncoder<T> implements Encodeable<JsonWriter, T> {
|
||||
fv = cw.visitField(ACC_PROTECTED, fieldname + "Encoder", encodeableDesc, null, null);
|
||||
fv.visitEnd();
|
||||
}
|
||||
if (fieldtype == int.class) intFieldCount++;
|
||||
if (fieldtype == int.class) {
|
||||
intFieldCount++;
|
||||
}
|
||||
if (fieldtype == String.class && membersSize == 1 && readConvertSmallString(element) != null) {
|
||||
onlyOneLatin1FieldObjectFlag = true;
|
||||
} else if (fieldtype != short.class && fieldtype != int.class && fieldtype != long.class && !(fieldtype == String.class && readConvertSmallString(element) != null)) {
|
||||
onlyShotIntLongLatin1MoreFieldObjectFlag = false;
|
||||
}
|
||||
}
|
||||
if (intFieldCount == 2 && intFieldCount == membersSize) onlyTwoIntFieldObjectFlag = true;
|
||||
if (onlyShotIntLongLatin1MoreFieldObjectFlag && membersSize < 2) onlyShotIntLongLatin1MoreFieldObjectFlag = false; //字段个数必须大于1
|
||||
|
||||
if (intFieldCount == 2 && intFieldCount == membersSize) {
|
||||
onlyTwoIntFieldObjectFlag = true;
|
||||
}
|
||||
if (onlyShotIntLongLatin1MoreFieldObjectFlag && membersSize < 2) {
|
||||
onlyShotIntLongLatin1MoreFieldObjectFlag = false; //字段个数必须大于1
|
||||
}
|
||||
{ // 构造函数
|
||||
mv = (cw.visitMethod(ACC_PUBLIC, "<init>", "(" + jsonfactoryDesc + typeDesc + ")V", null, null));
|
||||
//mv.setDebug(true);
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
package org.redkale.convert.json;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.lang.reflect.*;
|
||||
import java.lang.reflect.Type;
|
||||
import java.math.*;
|
||||
import java.net.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.ext.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.DLong;
|
||||
|
||||
/**
|
||||
* JSON的ConvertFactory
|
||||
@@ -89,7 +89,9 @@ public final class JsonFactory extends ConvertFactory<JsonReader, JsonWriter> {
|
||||
|
||||
@Override
|
||||
public final JsonConvert getConvert() {
|
||||
if (convert == null) convert = new JsonConvert(this, tiny);
|
||||
if (convert == null) {
|
||||
convert = new JsonConvert(this, tiny);
|
||||
}
|
||||
return (JsonConvert) convert;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,7 +41,9 @@ public class JsonMultiArrayDecoder implements Decodeable<JsonReader, Object[]> {
|
||||
|
||||
public Object[] convertFrom(JsonReader in, DeMember member) {
|
||||
int len = in.readArrayB(member, null, null);
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
//len must be Reader.SIGN_NOLENGTH
|
||||
final List<Object> result = new ArrayList();
|
||||
int startPosition = in.position();
|
||||
|
||||
@@ -68,13 +68,17 @@ public class JsonMultiImplDecoder<T> implements Decodeable<JsonReader, T> {
|
||||
for (String s : fields[i]) {
|
||||
boolean repeat = false;
|
||||
for (int j = 0; j < fields.length; j++) {
|
||||
if (j == i) continue;
|
||||
if (j == i) {
|
||||
continue;
|
||||
}
|
||||
if (fields[j].contains(s)) {
|
||||
repeat = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (repeat) removes.add(s);
|
||||
if (repeat) {
|
||||
removes.add(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +104,9 @@ public class JsonMultiImplDecoder<T> implements Decodeable<JsonReader, T> {
|
||||
@Override
|
||||
public T convertFrom(JsonReader in) {
|
||||
final String clazz = in.readObjectB(null);
|
||||
if (clazz == null) return null;
|
||||
if (clazz == null) {
|
||||
return null;
|
||||
}
|
||||
ObjectDecoder decoder = this.firstDecoder;
|
||||
Map<String, ObjectDecoder> uniques = this.uniqueFieldToDecoders;
|
||||
Map<String, ObjectDecoder> repeats = this.repeatFieldToDecoders;
|
||||
|
||||
@@ -8,7 +8,8 @@ package org.redkale.convert.json;
|
||||
import java.util.Map;
|
||||
import org.redkale.convert.*;
|
||||
import static org.redkale.convert.Reader.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.convert.Reader.ValueType;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
/**
|
||||
* JSON数据源
|
||||
@@ -75,14 +76,18 @@ public class JsonReader extends Reader {
|
||||
* @param key 指定的属性名
|
||||
*/
|
||||
public final void seek(String key) {
|
||||
if (key == null || key.length() < 1) return;
|
||||
if (key == null || key.length() < 1) {
|
||||
return;
|
||||
}
|
||||
final String[] keys = key.split("\\.");
|
||||
nextGoodChar(true); //读掉 { [
|
||||
for (String key1 : keys) {
|
||||
while (this.hasNext()) {
|
||||
String field = this.readSmallString();
|
||||
readBlank();
|
||||
if (key1.equals(field)) break;
|
||||
if (key1.equals(field)) {
|
||||
break;
|
||||
}
|
||||
skipValue();
|
||||
}
|
||||
}
|
||||
@@ -117,7 +122,9 @@ public class JsonReader extends Reader {
|
||||
char c;
|
||||
for (;;) {
|
||||
c = nextChar();
|
||||
if (c <= ' ') return;
|
||||
if (c <= ' ') {
|
||||
return;
|
||||
}
|
||||
if (c == '}' || c == ']' || c == ',' || c == ':') {
|
||||
backChar(c);
|
||||
return;
|
||||
@@ -133,7 +140,9 @@ public class JsonReader extends Reader {
|
||||
*/
|
||||
protected char nextChar() {
|
||||
int p = ++this.position;
|
||||
if (p >= text.length) return 0;
|
||||
if (p >= text.length) {
|
||||
return 0;
|
||||
}
|
||||
return this.text[p];
|
||||
}
|
||||
|
||||
@@ -148,13 +157,17 @@ public class JsonReader extends Reader {
|
||||
char c;
|
||||
for (;;) {
|
||||
c = nextChar();
|
||||
if (c == 0) return c;// 0 表示buffer结尾了
|
||||
if (c == 0) {
|
||||
return c;// 0 表示buffer结尾了
|
||||
}
|
||||
if (c > ' ') {
|
||||
if (allowComment && c == '/') { //支持单行和多行注释
|
||||
char n = nextChar();
|
||||
if (n == '/') {
|
||||
for (;;) {
|
||||
if (nextChar() == '\n') break;
|
||||
if (nextChar() == '\n') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nextGoodChar(allowComment);
|
||||
} else if (n == '*') {
|
||||
@@ -162,7 +175,9 @@ public class JsonReader extends Reader {
|
||||
char lc = 0;
|
||||
for (;;) {
|
||||
nc = nextChar();
|
||||
if (nc == '/' && lc == '*') break;
|
||||
if (nc == '/' && lc == '*') {
|
||||
break;
|
||||
}
|
||||
lc = nc;
|
||||
}
|
||||
return nextGoodChar(allowComment);
|
||||
@@ -231,11 +246,19 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public String readObjectB(final Class clazz) {
|
||||
this.fieldIndex = 0; //必须要重置为0
|
||||
if (this.text.length == 0) return null;
|
||||
if (this.text.length == 0) {
|
||||
return null;
|
||||
}
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == '{') return "";
|
||||
if (ch == 'n' && text[++position] == 'u' && text[++position] == 'l' && text[++position] == 'l') return null;
|
||||
if (ch == 'N' && text[++position] == 'U' && text[++position] == 'L' && text[++position] == 'L') return null;
|
||||
if (ch == '{') {
|
||||
return "";
|
||||
}
|
||||
if (ch == 'n' && text[++position] == 'u' && text[++position] == 'l' && text[++position] == 'l') {
|
||||
return null;
|
||||
}
|
||||
if (ch == 'N' && text[++position] == 'U' && text[++position] == 'L' && text[++position] == 'L') {
|
||||
return null;
|
||||
}
|
||||
throw new ConvertException("a json object text must begin with '{' (position = " + position + ") but '" + ch + "' in (" + new String(this.text) + ")");
|
||||
}
|
||||
|
||||
@@ -273,12 +296,22 @@ public class JsonReader extends Reader {
|
||||
*/
|
||||
@Override
|
||||
public int readArrayB(DeMember member, byte[] typevals, Decodeable componentDecoder) {
|
||||
if (this.text.length == 0) return SIGN_NULL;
|
||||
if (this.text.length == 0) {
|
||||
return SIGN_NULL;
|
||||
}
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == '[') return SIGN_NOLENGTH;
|
||||
if (ch == '{') return SIGN_NOLENGTH;
|
||||
if (ch == 'n' && text[++position] == 'u' && text[++position] == 'l' && text[++position] == 'l') return SIGN_NULL;
|
||||
if (ch == 'N' && text[++position] == 'U' && text[++position] == 'L' && text[++position] == 'L') return SIGN_NULL;
|
||||
if (ch == '[') {
|
||||
return SIGN_NOLENGTH;
|
||||
}
|
||||
if (ch == '{') {
|
||||
return SIGN_NOLENGTH;
|
||||
}
|
||||
if (ch == 'n' && text[++position] == 'u' && text[++position] == 'l' && text[++position] == 'l') {
|
||||
return SIGN_NULL;
|
||||
}
|
||||
if (ch == 'N' && text[++position] == 'U' && text[++position] == 'L' && text[++position] == 'L') {
|
||||
return SIGN_NULL;
|
||||
}
|
||||
throw new ConvertException("a json array text must begin with '[' (position = " + position + ") but '" + ch + "' in (" + new String(this.text) + ")");
|
||||
}
|
||||
|
||||
@@ -292,7 +325,9 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public void readBlank() {
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == ':') return;
|
||||
if (ch == ':') {
|
||||
return;
|
||||
}
|
||||
throw new ConvertException("'" + new String(text) + "'expected a ':' but '" + ch + "'(position = " + position + ") in (" + new String(this.text) + ")");
|
||||
}
|
||||
|
||||
@@ -319,11 +354,15 @@ public class JsonReader extends Reader {
|
||||
char ch = nextGoodChar(true);
|
||||
if (ch == ',') {
|
||||
char nt = nextGoodChar(true);
|
||||
if (nt == '}' || nt == ']') return false;
|
||||
if (nt == '}' || nt == ']') {
|
||||
return false;
|
||||
}
|
||||
this.position--;
|
||||
return true;
|
||||
}
|
||||
if (ch == '}' || ch == ']') return false;
|
||||
if (ch == '}' || ch == ']') {
|
||||
return false;
|
||||
}
|
||||
this.position--; // { [ 交由 readObjectB 或 readMapB 或 readArrayB 读取
|
||||
return true;
|
||||
}
|
||||
@@ -336,7 +375,9 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public String readSmallString() {
|
||||
final int eof = this.limit;
|
||||
if (this.position == eof) return null;
|
||||
if (this.position == eof) {
|
||||
return null;
|
||||
}
|
||||
char ch = nextGoodChar(true); //需要跳过注释
|
||||
final char[] text0 = this.text;
|
||||
int currpos = this.position;
|
||||
@@ -359,9 +400,13 @@ public class JsonReader extends Reader {
|
||||
} else {
|
||||
int start = currpos;
|
||||
for (;;) {
|
||||
if (currpos == eof) break;
|
||||
if (currpos == eof) {
|
||||
break;
|
||||
}
|
||||
ch = text0[++currpos];
|
||||
if (ch == ',' || ch == ']' || ch == '}' || ch <= ' ' || ch == ':') break;
|
||||
if (ch == ',' || ch == ']' || ch == '}' || ch <= ' ' || ch == ':') {
|
||||
break;
|
||||
}
|
||||
}
|
||||
int len = currpos - start;
|
||||
if (len < 1) {
|
||||
@@ -369,7 +414,9 @@ public class JsonReader extends Reader {
|
||||
return String.valueOf(ch);
|
||||
}
|
||||
this.position = currpos - 1;
|
||||
if (len == 4 && text0[start] == 'n' && text0[start + 1] == 'u' && text0[start + 2] == 'l' && text0[start + 3] == 'l') return null;
|
||||
if (len == 4 && text0[start] == 'n' && text0[start + 1] == 'u' && text0[start + 2] == 'l' && text0[start + 3] == 'l') {
|
||||
return null;
|
||||
}
|
||||
return new String(text0, start, len == eof ? (len + 1) : len);
|
||||
}
|
||||
}
|
||||
@@ -386,44 +433,74 @@ public class JsonReader extends Reader {
|
||||
if (firstchar == '"' || firstchar == '\'') {
|
||||
quote = true;
|
||||
firstchar = nextGoodChar(false);
|
||||
if (firstchar == '"' || firstchar == '\'') return 0;
|
||||
if (firstchar == '"' || firstchar == '\'') {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int value = 0;
|
||||
final boolean negative = firstchar == '-';
|
||||
if (!negative) {
|
||||
if (firstchar == '+') firstchar = nextChar(); //兼容+开头的
|
||||
if (firstchar < '0' || firstchar > '9') throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
if (firstchar == '+') {
|
||||
firstchar = nextChar(); //兼容+开头的
|
||||
}
|
||||
if (firstchar < '0' || firstchar > '9') {
|
||||
throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
}
|
||||
value = firstchar - '0';
|
||||
}
|
||||
if (firstchar == 'N') {
|
||||
if (negative) throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
if (negative) {
|
||||
throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
}
|
||||
char c = nextChar();
|
||||
if (c != 'a') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'a') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'N') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'N') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
if (quote) {
|
||||
c = nextChar();
|
||||
if (c != '"' && c != '\'') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != '"' && c != '\'') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
}
|
||||
return 0; //NaN 返回0;
|
||||
} else if (firstchar == 'I') { //Infinity
|
||||
char c = nextChar();
|
||||
if (c != 'n') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'n') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'f') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'f') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'i') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'i') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'n') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'n') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'i') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'i') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 't') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 't') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'y') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'y') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
if (quote) {
|
||||
c = nextChar();
|
||||
if (c != '"' && c != '\'') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != '"' && c != '\'') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
}
|
||||
return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
|
||||
}
|
||||
@@ -431,23 +508,39 @@ public class JsonReader extends Reader {
|
||||
boolean dot = false;
|
||||
for (;;) {
|
||||
char ch = nextChar();
|
||||
if (ch == 0) break;
|
||||
if (ch == 0) {
|
||||
break;
|
||||
}
|
||||
if (ch >= '0' && ch <= '9') {
|
||||
if (dot) continue;
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (hex ? (value << 4) : ((value << 3) + (value << 1))) + digits[ch];
|
||||
} else if (ch == '"' || ch == '\'') {
|
||||
if (quote) break;
|
||||
if (quote) {
|
||||
break;
|
||||
}
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
} else if (ch == 'x' || ch == 'X') {
|
||||
if (value != 0) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (value != 0) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
hex = true;
|
||||
} else if (ch >= 'a' && ch <= 'f') {
|
||||
if (!hex) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (dot) continue;
|
||||
if (!hex) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (value << 4) + digits[ch];
|
||||
} else if (ch >= 'A' && ch <= 'F') {
|
||||
if (!hex) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (dot) continue;
|
||||
if (!hex) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (value << 4) + digits[ch];
|
||||
} else if (quote && ch <= ' ') {
|
||||
} else if (ch == '.') {
|
||||
@@ -474,44 +567,74 @@ public class JsonReader extends Reader {
|
||||
if (firstchar == '"' || firstchar == '\'') {
|
||||
quote = true;
|
||||
firstchar = nextGoodChar(false);
|
||||
if (firstchar == '"' || firstchar == '\'') return 0L;
|
||||
if (firstchar == '"' || firstchar == '\'') {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
long value = 0;
|
||||
final boolean negative = firstchar == '-';
|
||||
if (!negative) {
|
||||
if (firstchar == '+') firstchar = nextChar(); //兼容+开头的
|
||||
if (firstchar < '0' || firstchar > '9') throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
if (firstchar == '+') {
|
||||
firstchar = nextChar(); //兼容+开头的
|
||||
}
|
||||
if (firstchar < '0' || firstchar > '9') {
|
||||
throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
}
|
||||
value = firstchar - '0';
|
||||
}
|
||||
if (firstchar == 'N') {
|
||||
if (negative) throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
if (negative) {
|
||||
throw new ConvertException("illegal escape(" + firstchar + ") (position = " + position + ")");
|
||||
}
|
||||
char c = nextChar();
|
||||
if (c != 'a') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'a') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'N') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'N') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
if (quote) {
|
||||
c = nextChar();
|
||||
if (c != '"' && c != '\'') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != '"' && c != '\'') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
}
|
||||
return 0L; //NaN 返回0;
|
||||
} else if (firstchar == 'I') { //Infinity
|
||||
char c = nextChar();
|
||||
if (c != 'n') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'n') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'f') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'f') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'i') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'i') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'n') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'n') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'i') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'i') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 't') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 't') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
c = nextChar();
|
||||
if (c != 'y') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != 'y') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
if (quote) {
|
||||
c = nextChar();
|
||||
if (c != '"' && c != '\'') throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
if (c != '"' && c != '\'') {
|
||||
throw new ConvertException("illegal escape(" + c + ") (position = " + position + ")");
|
||||
}
|
||||
}
|
||||
return negative ? Long.MIN_VALUE : Long.MAX_VALUE;
|
||||
}
|
||||
@@ -519,23 +642,39 @@ public class JsonReader extends Reader {
|
||||
boolean dot = false;
|
||||
for (;;) {
|
||||
char ch = nextChar();
|
||||
if (ch == 0) break;
|
||||
if (ch == 0) {
|
||||
break;
|
||||
}
|
||||
if (ch >= '0' && ch <= '9') {
|
||||
if (dot) continue;
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (hex ? (value << 4) : ((value << 3) + (value << 1))) + digits[ch];
|
||||
} else if (ch == '"' || ch == '\'') {
|
||||
if (quote) break;
|
||||
if (quote) {
|
||||
break;
|
||||
}
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
} else if (ch == 'x' || ch == 'X') {
|
||||
if (value != 0) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (value != 0) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
hex = true;
|
||||
} else if (ch >= 'a' && ch <= 'f') {
|
||||
if (!hex) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (dot) continue;
|
||||
if (!hex) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (value << 4) + digits[ch];
|
||||
} else if (ch >= 'A' && ch <= 'F') {
|
||||
if (!hex) throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
if (dot) continue;
|
||||
if (!hex) {
|
||||
throw new ConvertException("illegal escape(" + ch + ") (position = " + position + ")");
|
||||
}
|
||||
if (dot) {
|
||||
continue;
|
||||
}
|
||||
value = (value << 4) + digits[ch];
|
||||
} else if (quote && ch <= ' ') {
|
||||
} else if (ch == '.') {
|
||||
@@ -557,9 +696,13 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public final DeMember readFieldName(final DeMember[] members, Map<String, DeMember> memberFieldMap, Map<Integer, DeMember> memberTagMap) {
|
||||
final String exceptedField = this.readSmallString();
|
||||
if (exceptedField == null) return null;
|
||||
if (exceptedField == null) {
|
||||
return null;
|
||||
}
|
||||
final int len = members.length;
|
||||
if (this.fieldIndex >= len) this.fieldIndex = 0;
|
||||
if (this.fieldIndex >= len) {
|
||||
this.fieldIndex = 0;
|
||||
}
|
||||
for (int k = this.fieldIndex; k < len; k++) {
|
||||
if (exceptedField.equals(members[k].getAttribute().field())) {
|
||||
this.fieldIndex = k;
|
||||
@@ -591,7 +734,9 @@ public class JsonReader extends Reader {
|
||||
public final byte[] readByteArray() {
|
||||
int len = readArrayB(null, null, null);
|
||||
int contentLength = -1;
|
||||
if (len == Reader.SIGN_NULL) return null;
|
||||
if (len == Reader.SIGN_NULL) {
|
||||
return null;
|
||||
}
|
||||
if (len == Reader.SIGN_NOLENBUTBYTES) {
|
||||
contentLength = readMemberContentLength(null, null);
|
||||
len = Reader.SIGN_NOLENGTH;
|
||||
@@ -635,8 +780,12 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public final float readFloat() {
|
||||
String chars = readSmallString();
|
||||
if (chars != null) chars = chars.trim();
|
||||
if (chars == null || chars.isEmpty()) return 0.f;
|
||||
if (chars != null) {
|
||||
chars = chars.trim();
|
||||
}
|
||||
if (chars == null || chars.isEmpty()) {
|
||||
return 0.f;
|
||||
}
|
||||
switch (chars) {
|
||||
case "Infinity": return (float) Double.POSITIVE_INFINITY;
|
||||
case "-Infinity": return (float) Double.NEGATIVE_INFINITY;
|
||||
@@ -647,8 +796,12 @@ public class JsonReader extends Reader {
|
||||
@Override
|
||||
public final double readDouble() {
|
||||
String chars = readSmallString();
|
||||
if (chars != null) chars = chars.trim();
|
||||
if (chars == null || chars.isEmpty()) return 0.0;
|
||||
if (chars != null) {
|
||||
chars = chars.trim();
|
||||
}
|
||||
if (chars == null || chars.isEmpty()) {
|
||||
return 0.0;
|
||||
}
|
||||
switch (chars) {
|
||||
case "Infinity": return Double.POSITIVE_INFINITY;
|
||||
case "-Infinity": return Double.NEGATIVE_INFINITY;
|
||||
@@ -672,15 +825,23 @@ public class JsonReader extends Reader {
|
||||
this.position = currpos;
|
||||
if (text0.length > currpos + 4) {
|
||||
char ch = text0[currpos + 1];
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') return null;
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') {
|
||||
return null;
|
||||
}
|
||||
final int start = currpos - 3;
|
||||
for (;;) {
|
||||
if (currpos >= text0.length) break;
|
||||
if (currpos >= text0.length) {
|
||||
break;
|
||||
}
|
||||
ch = text0[currpos];
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') break;
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') {
|
||||
break;
|
||||
}
|
||||
currpos++;
|
||||
}
|
||||
if (currpos == start) throw new ConvertException("expected a string after a key but '" + text0[position] + "' (position = " + position + ") in (" + new String(this.text) + ")");
|
||||
if (currpos == start) {
|
||||
throw new ConvertException("expected a string after a key but '" + text0[position] + "' (position = " + position + ") in (" + new String(this.text) + ")");
|
||||
}
|
||||
this.position = currpos - 1;
|
||||
return new String(text0, start, currpos - start);
|
||||
} else {
|
||||
@@ -690,12 +851,18 @@ public class JsonReader extends Reader {
|
||||
} else {
|
||||
final int start = currpos;
|
||||
for (;;) {
|
||||
if (currpos >= text0.length) break;
|
||||
if (currpos >= text0.length) {
|
||||
break;
|
||||
}
|
||||
char ch = text0[currpos];
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') break;
|
||||
if (ch == ',' || ch <= ' ' || ch == '}' || ch == ']' || ch == ':') {
|
||||
break;
|
||||
}
|
||||
currpos++;
|
||||
}
|
||||
if (currpos == start) throw new ConvertException("expected a string after a key but '" + text0[position] + "' (position = " + position + ") in (" + new String(this.text) + ")");
|
||||
if (currpos == start) {
|
||||
throw new ConvertException("expected a string after a key but '" + text0[position] + "' (position = " + position + ") in (" + new String(this.text) + ")");
|
||||
}
|
||||
this.position = currpos - 1;
|
||||
return new String(text0, start, currpos - start);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,9 @@ package org.redkale.convert.json;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.*;
|
||||
import java.nio.charset.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.util.*;
|
||||
import java.nio.charset.Charset;
|
||||
import org.redkale.convert.ConvertException;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -39,7 +39,9 @@ class JsonStreamWriter extends JsonByteBufferWriter {
|
||||
|
||||
@Override
|
||||
public void writeTo(final char ch) {
|
||||
if (ch > Byte.MAX_VALUE) throw new ConvertException("writeTo char(int.value = " + (int) ch + ") must be less 127");
|
||||
if (ch > Byte.MAX_VALUE) {
|
||||
throw new ConvertException("writeTo char(int.value = " + (int) ch + ") must be less 127");
|
||||
}
|
||||
try {
|
||||
out.write((byte) ch);
|
||||
} catch (IOException e) {
|
||||
@@ -54,7 +56,9 @@ class JsonStreamWriter extends JsonByteBufferWriter {
|
||||
|
||||
private void writeTo(final boolean quote, final char[] chs, final int start, final int len) {
|
||||
try {
|
||||
if (quote) out.write('"');
|
||||
if (quote) {
|
||||
out.write('"');
|
||||
}
|
||||
if (charset == null) { //UTF-8
|
||||
final int limit = start + len;
|
||||
for (int i = start; i < limit; i++) {
|
||||
@@ -81,7 +85,9 @@ class JsonStreamWriter extends JsonByteBufferWriter {
|
||||
ByteBuffer bb = charset.encode(CharBuffer.wrap(chs, start, len));
|
||||
out.write(bb.array());
|
||||
}
|
||||
if (quote) out.write('"');
|
||||
if (quote) {
|
||||
out.write('"');
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new ConvertException(e);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ package org.redkale.convert.json;
|
||||
|
||||
import java.lang.reflect.Type;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.StringWrapper;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -92,7 +92,9 @@ public abstract class JsonWriter extends Writer {
|
||||
|
||||
@Override //只容许JsonBytesWriter重写此方法
|
||||
public void writeFieldName(EnMember member, String fieldName, Type fieldType, int fieldPos) {
|
||||
if (this.comma) writeTo(',');
|
||||
if (this.comma) {
|
||||
writeTo(',');
|
||||
}
|
||||
if (member != null) {
|
||||
writeTo(member.getJsonFieldNameChars());
|
||||
} else {
|
||||
@@ -129,7 +131,9 @@ public abstract class JsonWriter extends Writer {
|
||||
writeArrayB(values.length, null, null, values);
|
||||
boolean flag = false;
|
||||
for (byte v : values) {
|
||||
if (flag) writeArrayMark();
|
||||
if (flag) {
|
||||
writeArrayMark();
|
||||
}
|
||||
writeByte(v);
|
||||
flag = true;
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ import java.lang.reflect.Type;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.logging.*;
|
||||
import java.util.logging.Logger;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.net.http.*;
|
||||
import static org.redkale.mq.MessageRecord.CTYPE_HTTP_REQUEST;
|
||||
import org.redkale.net.http.*;
|
||||
|
||||
/**
|
||||
* 不依赖MessageRecord则可兼容RPC方式
|
||||
@@ -48,7 +48,9 @@ public class HttpMessageClient extends MessageClient {
|
||||
|
||||
public String generateHttpReqTopic(HttpSimpleRequest request, String path) {
|
||||
String module = request.getRequestURI();
|
||||
if (path != null && !path.isEmpty() && module.startsWith(path)) module = module.substring(path.length());
|
||||
if (path != null && !path.isEmpty() && module.startsWith(path)) {
|
||||
module = module.substring(path.length());
|
||||
}
|
||||
module = module.substring(1); //去掉/
|
||||
module = module.substring(0, module.indexOf('/'));
|
||||
Map<String, String> headers = request.getHeaders();
|
||||
@@ -122,21 +124,27 @@ public class HttpMessageClient extends MessageClient {
|
||||
|
||||
public <T> CompletableFuture<T> sendMessage(HttpSimpleRequest request, Type type) {
|
||||
return sendMessage(generateHttpReqTopic(request, null), 0, null, request, null).thenApply((HttpResult<byte[]> httbs) -> {
|
||||
if (httbs == null || httbs.getResult() == null) return null;
|
||||
if (httbs == null || httbs.getResult() == null) {
|
||||
return null;
|
||||
}
|
||||
return JsonConvert.root().convertFrom(type, httbs.getResult());
|
||||
});
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> sendMessage(Serializable userid, HttpSimpleRequest request, Type type) {
|
||||
return sendMessage(generateHttpReqTopic(request, null), userid, null, request, null).thenApply((HttpResult<byte[]> httbs) -> {
|
||||
if (httbs == null || httbs.getResult() == null) return null;
|
||||
if (httbs == null || httbs.getResult() == null) {
|
||||
return null;
|
||||
}
|
||||
return JsonConvert.root().convertFrom(type, httbs.getResult());
|
||||
});
|
||||
}
|
||||
|
||||
public <T> CompletableFuture<T> sendMessage(Serializable userid, String groupid, HttpSimpleRequest request, Type type) {
|
||||
return sendMessage(generateHttpReqTopic(request, null), userid, groupid, request, null).thenApply((HttpResult<byte[]> httbs) -> {
|
||||
if (httbs == null || httbs.getResult() == null) return null;
|
||||
if (httbs == null || httbs.getResult() == null) {
|
||||
return null;
|
||||
}
|
||||
return JsonConvert.root().convertFrom(type, httbs.getResult());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.logging.Level;
|
||||
import org.redkale.annotation.Resource;
|
||||
import org.redkale.boot.Application;
|
||||
@@ -86,19 +86,35 @@ public class HttpMessageClusterClient extends HttpMessageClient {
|
||||
final String localModule = module;
|
||||
return clusterAgent.queryMqtpAddress("mqtp", module, resname).thenCompose(addrmap -> {
|
||||
if (addrmap == null || addrmap.isEmpty()) {
|
||||
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "mqtpAsync.broadcastMessage: module=" + localModule + ", resname=" + resname + ", addrmap is empty");
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "mqtpAsync.broadcastMessage: module=" + localModule + ", resname=" + resname + ", addrmap is empty");
|
||||
}
|
||||
return new HttpResult<byte[]>().status(404).toFuture();
|
||||
}
|
||||
final Map<String, String> clientHeaders = new LinkedHashMap<>();
|
||||
byte[] clientBody = null;
|
||||
if (req.isRpc()) clientHeaders.put(Rest.REST_HEADER_RPC, "true");
|
||||
if (req.isFrombody()) clientHeaders.put(Rest.REST_HEADER_PARAM_FROM_BODY, "true");
|
||||
if (req.getReqConvertType() != null) clientHeaders.put(Rest.REST_HEADER_REQ_CONVERT_TYPE, req.getReqConvertType().toString());
|
||||
if (req.getRespConvertType() != null) clientHeaders.put(Rest.REST_HEADER_RESP_CONVERT_TYPE, req.getRespConvertType().toString());
|
||||
if (userid != null) clientHeaders.put(Rest.REST_HEADER_CURRUSERID_NAME, "" + userid);
|
||||
if (headers != null) headers.forEach((n, v) -> {
|
||||
if (!DISALLOWED_HEADERS_SET.contains(n.toLowerCase())) clientHeaders.put(n, v);
|
||||
if (req.isRpc()) {
|
||||
clientHeaders.put(Rest.REST_HEADER_RPC, "true");
|
||||
}
|
||||
if (req.isFrombody()) {
|
||||
clientHeaders.put(Rest.REST_HEADER_PARAM_FROM_BODY, "true");
|
||||
}
|
||||
if (req.getReqConvertType() != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_REQ_CONVERT_TYPE, req.getReqConvertType().toString());
|
||||
}
|
||||
if (req.getRespConvertType() != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_RESP_CONVERT_TYPE, req.getRespConvertType().toString());
|
||||
}
|
||||
if (userid != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_CURRUSERID_NAME, "" + userid);
|
||||
}
|
||||
if (headers != null) {
|
||||
headers.forEach((n, v) -> {
|
||||
if (!DISALLOWED_HEADERS_SET.contains(n.toLowerCase())) {
|
||||
clientHeaders.put(n, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
clientHeaders.put("Content-Type", "x-www-form-urlencoded");
|
||||
if (req.getBody() != null && req.getBody().length > 0) {
|
||||
String paramstr = req.getParametersToString();
|
||||
@@ -112,20 +128,28 @@ public class HttpMessageClusterClient extends HttpMessageClient {
|
||||
clientBody = req.getBody();
|
||||
} else {
|
||||
String paramstr = req.getParametersToString();
|
||||
if (paramstr != null) clientBody = paramstr.getBytes(StandardCharsets.UTF_8);
|
||||
if (paramstr != null) {
|
||||
clientBody = paramstr.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
List<CompletableFuture> futures = new ArrayList<>();
|
||||
if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "mqtpAsync: module=" + localModule + ", resname=" + resname + ", addrmap=" + addrmap);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.log(Level.FINEST, "mqtpAsync: module=" + localModule + ", resname=" + resname + ", addrmap=" + addrmap);
|
||||
}
|
||||
for (Map.Entry<String, Collection<InetSocketAddress>> en : addrmap.entrySet()) {
|
||||
String realmodule = en.getKey();
|
||||
Collection<InetSocketAddress> addrs = en.getValue();
|
||||
if (addrs == null || addrs.isEmpty()) continue;
|
||||
if (addrs == null || addrs.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String suburi = req.getRequestURI();
|
||||
suburi = suburi.substring(1); //跳过 /
|
||||
suburi = "/" + realmodule + suburi.substring(suburi.indexOf('/'));
|
||||
futures.add(forEachCollectionFuture(logger.isLoggable(Level.FINEST), userid, req, (req.getPath() != null && !req.getPath().isEmpty() ? req.getPath() : "") + suburi, clientHeaders, clientBody, addrs.iterator()));
|
||||
}
|
||||
if (futures.isEmpty()) return CompletableFuture.completedFuture(null);
|
||||
if (futures.isEmpty()) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).thenApply(v -> null);
|
||||
});
|
||||
}
|
||||
@@ -137,25 +161,41 @@ public class HttpMessageClusterClient extends HttpMessageClient {
|
||||
Map<String, String> headers = req.getHeaders();
|
||||
String resname = headers == null ? "" : headers.getOrDefault(Rest.REST_HEADER_RESOURCE_NAME, "");
|
||||
final String localModule = module;
|
||||
if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "httpAsync.queryHttpAddress: module=" + localModule + ", resname=" + resname);
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.log(Level.FINEST, "httpAsync.queryHttpAddress: module=" + localModule + ", resname=" + resname);
|
||||
}
|
||||
return clusterAgent.queryHttpAddress("http", module, resname).thenCompose(addrs -> {
|
||||
if (addrs == null || addrs.isEmpty()) {
|
||||
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "httpAsync." + (produce ? "produceMessage" : "sendMessage") + ": module=" + localModule + ", resname=" + resname + ", addrmap is empty");
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "httpAsync." + (produce ? "produceMessage" : "sendMessage") + ": module=" + localModule + ", resname=" + resname + ", addrmap is empty");
|
||||
}
|
||||
return new HttpResult<byte[]>().status(404).toFuture();
|
||||
}
|
||||
final Map<String, String> clientHeaders = new LinkedHashMap<>();
|
||||
byte[] clientBody = null;
|
||||
if (req.isRpc()) clientHeaders.put(Rest.REST_HEADER_RPC, "true");
|
||||
if (req.isFrombody()) clientHeaders.put(Rest.REST_HEADER_PARAM_FROM_BODY, "true");
|
||||
if (req.getReqConvertType() != null) clientHeaders.put(Rest.REST_HEADER_REQ_CONVERT_TYPE, req.getReqConvertType().toString());
|
||||
if (req.getRespConvertType() != null) clientHeaders.put(Rest.REST_HEADER_RESP_CONVERT_TYPE, req.getRespConvertType().toString());
|
||||
if (userid != null) clientHeaders.put(Rest.REST_HEADER_CURRUSERID_NAME, "" + userid);
|
||||
if (req.isRpc()) {
|
||||
clientHeaders.put(Rest.REST_HEADER_RPC, "true");
|
||||
}
|
||||
if (req.isFrombody()) {
|
||||
clientHeaders.put(Rest.REST_HEADER_PARAM_FROM_BODY, "true");
|
||||
}
|
||||
if (req.getReqConvertType() != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_REQ_CONVERT_TYPE, req.getReqConvertType().toString());
|
||||
}
|
||||
if (req.getRespConvertType() != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_RESP_CONVERT_TYPE, req.getRespConvertType().toString());
|
||||
}
|
||||
if (userid != null) {
|
||||
clientHeaders.put(Rest.REST_HEADER_CURRUSERID_NAME, "" + userid);
|
||||
}
|
||||
if (headers != null) {
|
||||
boolean ws = headers.containsKey("Sec-WebSocket-Key");
|
||||
headers.forEach((n, v) -> {
|
||||
if (!DISALLOWED_HEADERS_SET.contains(n.toLowerCase())
|
||||
&& (!ws || (!"Connection".equals(n) && !"Sec-WebSocket-Key".equals(n)
|
||||
&& !"Sec-WebSocket-Version".equals(n)))) clientHeaders.put(n, v);
|
||||
&& !"Sec-WebSocket-Version".equals(n)))) {
|
||||
clientHeaders.put(n, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
clientHeaders.put("Content-Type", "x-www-form-urlencoded");
|
||||
@@ -171,28 +211,42 @@ public class HttpMessageClusterClient extends HttpMessageClient {
|
||||
clientBody = req.getBody();
|
||||
} else {
|
||||
String paramstr = req.getParametersToString();
|
||||
if (paramstr != null) clientBody = paramstr.getBytes(StandardCharsets.UTF_8);
|
||||
if (paramstr != null) {
|
||||
clientBody = paramstr.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.log(Level.FINEST, "httpAsync: module=" + localModule + ", resname=" + resname + ", enter forEachCollectionFuture");
|
||||
}
|
||||
if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "httpAsync: module=" + localModule + ", resname=" + resname + ", enter forEachCollectionFuture");
|
||||
return forEachCollectionFuture(logger.isLoggable(Level.FINEST), userid, req, (req.getPath() != null && !req.getPath().isEmpty() ? req.getPath() : "") + req.getRequestURI(), clientHeaders, clientBody, addrs.iterator());
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<HttpResult<byte[]>> forEachCollectionFuture(boolean finest, Serializable userid, HttpSimpleRequest req, String requesturi, final Map<String, String> clientHeaders, byte[] clientBody, Iterator<InetSocketAddress> it) {
|
||||
if (!it.hasNext()) return CompletableFuture.completedFuture(null);
|
||||
if (!it.hasNext()) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
InetSocketAddress addr = it.next();
|
||||
String url = "http://" + addr.getHostString() + ":" + addr.getPort() + requesturi;
|
||||
if (finest) logger.log(Level.FINEST, "forEachCollectionFuture: url=" + url + ", headers=" + clientHeaders);
|
||||
if (httpSimpleClient != null) return httpSimpleClient.postAsync(url, clientHeaders, clientBody);
|
||||
if (finest) {
|
||||
logger.log(Level.FINEST, "forEachCollectionFuture: url=" + url + ", headers=" + clientHeaders);
|
||||
}
|
||||
if (httpSimpleClient != null) {
|
||||
return httpSimpleClient.postAsync(url, clientHeaders, clientBody);
|
||||
}
|
||||
java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder().uri(URI.create(url))
|
||||
.timeout(Duration.ofMillis(10_000))
|
||||
//存在sendHeader后不发送body数据的问题, java.net.http.HttpRequest的bug?
|
||||
.method("POST", clientBody == null ? java.net.http.HttpRequest.BodyPublishers.noBody() : java.net.http.HttpRequest.BodyPublishers.ofByteArray(clientBody));
|
||||
if (clientHeaders != null) clientHeaders.forEach((n, v) -> builder.header(n, v));
|
||||
if (clientHeaders != null) {
|
||||
clientHeaders.forEach((n, v) -> builder.header(n, v));
|
||||
}
|
||||
return httpClient.sendAsync(builder.build(), java.net.http.HttpResponse.BodyHandlers.ofByteArray())
|
||||
.thenApply((java.net.http.HttpResponse<byte[]> resp) -> {
|
||||
final int rs = resp.statusCode();
|
||||
if (rs != 200) return new HttpResult<byte[]>().status(rs);
|
||||
if (rs != 200) {
|
||||
return new HttpResult<byte[]>().status(rs);
|
||||
}
|
||||
return new HttpResult<byte[]>(resp.body());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
import java.util.logging.Level;
|
||||
import org.redkale.boot.*;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.Convert;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.net.http.*;
|
||||
|
||||
@@ -96,7 +96,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
HttpServlet servlet = findHttpServlet(topic);
|
||||
CompletableFuture future = new CompletableFuture();
|
||||
if (servlet == null) {
|
||||
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "sendMessage: request=" + request + ", not found servlet");
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "sendMessage: request=" + request + ", not found servlet");
|
||||
}
|
||||
future.completeExceptionally(new RuntimeException("404 Not Found " + topic));
|
||||
return future;
|
||||
}
|
||||
@@ -114,7 +116,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
public CompletableFuture<HttpResult<byte[]>> sendMessage(String topic, Serializable userid, String groupid, HttpSimpleRequest request, AtomicLong counter) {
|
||||
HttpServlet servlet = findHttpServlet(topic);
|
||||
if (servlet == null) {
|
||||
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "sendMessage: request=" + request + ", not found servlet");
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "sendMessage: request=" + request + ", not found servlet");
|
||||
}
|
||||
return CompletableFuture.completedFuture(new HttpResult().status(404));
|
||||
}
|
||||
HttpRequest req = new HttpMessageLocalRequest(context(), request, userid);
|
||||
@@ -126,10 +130,14 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
future.completeExceptionally(e);
|
||||
}
|
||||
return future.thenApply(rs -> {
|
||||
if (rs == null) return new HttpResult();
|
||||
if (rs == null) {
|
||||
return new HttpResult();
|
||||
}
|
||||
if (rs instanceof HttpResult) {
|
||||
Object result = ((HttpResult) rs).getResult();
|
||||
if (result == null || result instanceof byte[]) return (HttpResult) rs;
|
||||
if (result == null || result instanceof byte[]) {
|
||||
return (HttpResult) rs;
|
||||
}
|
||||
return new HttpResult(JsonConvert.root().convertToBytes(result));
|
||||
}
|
||||
return new HttpResult(JsonConvert.root().convertToBytes(rs));
|
||||
@@ -141,7 +149,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
HttpDispatcherServlet ps = dispatcherServlet();
|
||||
HttpServlet servlet = ps.findServletByTopic(topic);
|
||||
if (servlet == null) {
|
||||
if (logger.isLoggable(Level.FINE)) logger.log(Level.FINE, "produceMessage: request=" + request + ", not found servlet");
|
||||
if (logger.isLoggable(Level.FINE)) {
|
||||
logger.log(Level.FINE, "produceMessage: request=" + request + ", not found servlet");
|
||||
}
|
||||
return;
|
||||
}
|
||||
HttpRequest req = new HttpMessageLocalRequest(context(), request, userid);
|
||||
@@ -171,7 +181,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
public HttpMessageLocalRequest(HttpContext context, HttpSimpleRequest req, Serializable userid) {
|
||||
super(context, req);
|
||||
if (userid != null) this.currentUserid = userid;
|
||||
if (userid != null) {
|
||||
this.currentUserid = userid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +213,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finishJson(final JsonConvert convert, final Type type, final Object obj) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
future.complete(obj);
|
||||
}
|
||||
|
||||
@@ -212,13 +226,17 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(final Convert convert, Type type, org.redkale.service.RetResult ret) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
future.complete(ret);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish(final Convert convert, final Type type, Object obj) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
if (obj instanceof CompletableFuture) {
|
||||
((CompletableFuture) obj).whenComplete((r, t) -> {
|
||||
if (t == null) {
|
||||
@@ -234,7 +252,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(String obj) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
future.complete(obj == null ? "" : obj);
|
||||
}
|
||||
|
||||
@@ -260,7 +280,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(int status, String msg) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
if (status == 0 || status == 200) {
|
||||
future.complete(msg == null ? "" : msg);
|
||||
} else {
|
||||
@@ -270,14 +292,20 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(final Convert convert, Type valueType, HttpResult result) {
|
||||
if (future == null) return;
|
||||
if (convert != null) result.convert(convert);
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
if (convert != null) {
|
||||
result.convert(convert);
|
||||
}
|
||||
future.complete(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish(boolean kill, final byte[] bs, int offset, int length) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
if (offset == 0 && bs.length == length) {
|
||||
future.complete(bs);
|
||||
} else {
|
||||
@@ -287,14 +315,18 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(boolean kill, final String contentType, final byte[] bs, int offset, int length) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
byte[] rs = (offset == 0 && bs.length == length) ? bs : Arrays.copyOfRange(bs, offset, offset + length);
|
||||
future.complete(rs);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish(boolean kill, ByteBuffer buffer) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
byte[] bs = new byte[buffer.remaining()];
|
||||
buffer.get(bs);
|
||||
future.complete(bs);
|
||||
@@ -302,7 +334,9 @@ public class HttpMessageLocalClient extends HttpMessageClient {
|
||||
|
||||
@Override
|
||||
public void finish(boolean kill, ByteBuffer... buffers) {
|
||||
if (future == null) return;
|
||||
if (future == null) {
|
||||
return;
|
||||
}
|
||||
int size = 0;
|
||||
for (ByteBuffer buf : buffers) {
|
||||
size += buf.remaining();
|
||||
|
||||
@@ -54,7 +54,9 @@ public class HttpMessageProcessor implements MessageProcessor {
|
||||
protected long startTime;
|
||||
|
||||
protected final Runnable innerCallback = () -> {
|
||||
if (cdl != null) cdl.countDown();
|
||||
if (cdl != null) {
|
||||
cdl.countDown();
|
||||
}
|
||||
};
|
||||
|
||||
public HttpMessageProcessor(Logger logger, HttpMessageClient messageClient, MessageProducers producers, NodeHttpServer server, Service service, HttpServlet servlet) {
|
||||
@@ -92,12 +94,15 @@ public class HttpMessageProcessor implements MessageProcessor {
|
||||
long now = System.currentTimeMillis();
|
||||
long cha = now - message.createTime;
|
||||
long e = now - startTime;
|
||||
if (multiConsumer) message.setRespTopic(null); //不容许有响应
|
||||
|
||||
if (multiConsumer) {
|
||||
message.setRespTopic(null); //不容许有响应
|
||||
}
|
||||
HttpMessageResponse response = respSupplier.get();
|
||||
request = response.request();
|
||||
response.prepare(message, callback, producers.getProducer(message));
|
||||
if (multiConsumer) request.setRequestURI(request.getRequestURI().replaceFirst(this.multiModule, this.restModule));
|
||||
if (multiConsumer) {
|
||||
request.setRequestURI(request.getRequestURI().replaceFirst(this.multiModule, this.restModule));
|
||||
}
|
||||
|
||||
server.getHttpServer().getContext().execute(servlet, request, response);
|
||||
long o = System.currentTimeMillis() - now;
|
||||
|
||||
@@ -11,12 +11,12 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.function.*;
|
||||
import java.util.logging.Level;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.Convert;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.service.RetResult;
|
||||
import static org.redkale.mq.MessageRecord.CTYPE_HTTP_RESULT;
|
||||
import org.redkale.net.Response;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.service.RetResult;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -74,17 +74,27 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
}
|
||||
|
||||
public static void finishHttpResult(boolean finest, Convert respConvert, Type type, MessageRecord msg, Runnable callback, MessageClient messageClient, MessageProducer producer, String resptopic, HttpResult result) {
|
||||
if (callback != null) callback.run();
|
||||
if (resptopic == null || resptopic.isEmpty()) return;
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
if (resptopic == null || resptopic.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (result.getResult() instanceof RetResult) {
|
||||
RetResult ret = (RetResult) result.getResult();
|
||||
//必须要塞入retcode, 开发者可以无需反序列化ret便可确定操作是否返回成功
|
||||
if (!ret.isSuccess()) result.header("retcode", String.valueOf(ret.getRetcode()));
|
||||
if (!ret.isSuccess()) {
|
||||
result.header("retcode", String.valueOf(ret.getRetcode()));
|
||||
}
|
||||
}
|
||||
if (result.convert() == null && respConvert != null) {
|
||||
result.convert(respConvert);
|
||||
}
|
||||
if (result.convert() == null && respConvert != null) result.convert(respConvert);
|
||||
if (finest) {
|
||||
Object innerrs = result.getResult();
|
||||
if (innerrs instanceof byte[]) innerrs = new String((byte[]) innerrs, StandardCharsets.UTF_8);
|
||||
if (innerrs instanceof byte[]) {
|
||||
innerrs = new String((byte[]) innerrs, StandardCharsets.UTF_8);
|
||||
}
|
||||
producer.logger.log(Level.FINEST, "HttpMessageResponse.finishHttpResult seqid=" + msg.getSeqid() + ", content: " + innerrs + ", status: " + result.getStatus() + ", headers: " + result.getHeaders());
|
||||
}
|
||||
byte[] content = HttpResultCoder.getInstance().encode(result);
|
||||
@@ -117,7 +127,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finishJson(final JsonConvert convert, final Object obj) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(obj.getClass(), convert, new HttpResult(obj));
|
||||
@@ -127,7 +139,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finishJson(final Type type, final Object obj) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(type, new HttpResult(obj));
|
||||
@@ -136,7 +150,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finishJson(final JsonConvert convert, final Type type, final Object obj) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(type, convert, new HttpResult(obj));
|
||||
@@ -145,7 +161,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(Type type, org.redkale.service.RetResult ret) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(type, new HttpResult(ret));
|
||||
@@ -155,7 +173,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(final Convert convert, Type type, org.redkale.service.RetResult ret) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(type, convert, new HttpResult(ret));
|
||||
@@ -164,7 +184,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(final Convert convert, final Type type, Object obj) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(type, convert, new HttpResult(obj));
|
||||
@@ -173,7 +195,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(String obj) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(String.class, new HttpResult(obj == null ? "" : obj));
|
||||
@@ -207,7 +231,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
producer.logger.log(Level.FINEST, "HttpMessageResponse.finish status: " + status);
|
||||
}
|
||||
if (this.message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishHttpResult(String.class, new HttpResult(msg == null ? "" : msg).status(status));
|
||||
@@ -216,17 +242,23 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(final Convert convert, Type type, HttpResult result) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (convert != null) result.convert(convert);
|
||||
if (convert != null) {
|
||||
result.convert(convert);
|
||||
}
|
||||
finishHttpResult(type, result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finish(boolean kill, final byte[] bs, int offset, int length) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (offset == 0 && bs.length == length) {
|
||||
@@ -239,7 +271,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(boolean kill, final String contentType, final byte[] bs, int offset, int length) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
byte[] rs = (offset == 0 && bs.length == length) ? bs : Arrays.copyOfRange(bs, offset, offset + length);
|
||||
@@ -249,7 +283,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
protected <A> void finish(boolean kill, final String contentType, final byte[] bs, int offset, int length, Consumer<A> consumer, A attachment) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
byte[] rs = (offset == 0 && bs.length == length) ? bs : Arrays.copyOfRange(bs, offset, offset + length);
|
||||
@@ -259,7 +295,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(boolean kill, ByteBuffer buffer) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
byte[] bs = new byte[buffer.remaining()];
|
||||
@@ -270,7 +308,9 @@ public class HttpMessageResponse extends HttpResponse {
|
||||
@Override
|
||||
public void finish(boolean kill, ByteBuffer... buffers) {
|
||||
if (message.isEmptyRespTopic()) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
return;
|
||||
}
|
||||
int size = 0;
|
||||
|
||||
@@ -9,7 +9,7 @@ import java.net.HttpCookie;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.Convert;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import static org.redkale.mq.MessageCoder.*;
|
||||
import org.redkale.net.http.HttpResult;
|
||||
@@ -35,7 +35,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
|
||||
@Override
|
||||
public byte[] encode(HttpResult data) {
|
||||
if (data == null) return null;
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
byte[] contentType = MessageCoder.getBytes(data.getContentType());
|
||||
byte[] headers = MessageCoder.getBytes(data.getHeaders());
|
||||
byte[] cookies = getBytes(data.getCookies());
|
||||
@@ -48,7 +50,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
content = MessageCoder.getBytes(data.getResult().toString());
|
||||
} else {
|
||||
Convert cc = data.convert();
|
||||
if (cc == null) cc = JsonConvert.root();
|
||||
if (cc == null) {
|
||||
cc = JsonConvert.root();
|
||||
}
|
||||
content = cc.convertToBytes(data.getResult());
|
||||
}
|
||||
int count = 4 + 2 + contentType.length + headers.length + cookies.length + 4 + (content == null ? 0 : content.length);
|
||||
@@ -56,7 +60,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(bs);
|
||||
buffer.putInt(data.getStatus());
|
||||
buffer.putChar((char) contentType.length);
|
||||
if (contentType.length > 0) buffer.put(contentType);
|
||||
if (contentType.length > 0) {
|
||||
buffer.put(contentType);
|
||||
}
|
||||
buffer.put(headers);
|
||||
buffer.put(cookies);
|
||||
if (content == null || content.length == 0) {
|
||||
@@ -70,7 +76,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
|
||||
@Override
|
||||
public HttpResult<byte[]> decode(byte[] data) {
|
||||
if (data == null) return null;
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.wrap(data);
|
||||
HttpResult result = new HttpResult();
|
||||
result.setStatus(buffer.getInt());
|
||||
@@ -87,7 +95,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
}
|
||||
|
||||
public static byte[] getBytes(final List<HttpCookie> list) {
|
||||
if (list == null || list.isEmpty()) return new byte[2];
|
||||
if (list == null || list.isEmpty()) {
|
||||
return new byte[2];
|
||||
}
|
||||
final AtomicInteger len = new AtomicInteger(2);
|
||||
list.forEach(cookie -> {
|
||||
len.addAndGet(2 + (cookie.getName() == null ? 0 : Utility.encodeUTF8Length(cookie.getName())));
|
||||
@@ -115,7 +125,9 @@ public class HttpResultCoder implements MessageCoder<HttpResult> {
|
||||
|
||||
public static List<HttpCookie> getCookieList(ByteBuffer buffer) {
|
||||
int len = buffer.getChar();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
final List<HttpCookie> list = new ArrayList<>(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
HttpCookie cookie = new HttpCookie(getShortString(buffer), getShortString(buffer));
|
||||
|
||||
@@ -60,29 +60,47 @@ public class HttpSimpleRequestCoder implements MessageCoder<HttpSimpleRequest> {
|
||||
buffer.putInt(data.getReqConvertType() == null ? 0 : data.getReqConvertType().getValue());
|
||||
buffer.putInt(data.getRespConvertType() == null ? 0 : data.getRespConvertType().getValue());
|
||||
buffer.putChar((char) traceid.length);
|
||||
if (traceid.length > 0) buffer.put(traceid);
|
||||
if (traceid.length > 0) {
|
||||
buffer.put(traceid);
|
||||
}
|
||||
buffer.putInt(requestURI.length);
|
||||
if (requestURI.length > 0) buffer.put(requestURI);
|
||||
if (requestURI.length > 0) {
|
||||
buffer.put(requestURI);
|
||||
}
|
||||
buffer.putChar((char) path.length);
|
||||
if (path.length > 0) buffer.put(path);
|
||||
if (path.length > 0) {
|
||||
buffer.put(path);
|
||||
}
|
||||
buffer.putChar((char) remoteAddr.length);
|
||||
if (remoteAddr.length > 0) buffer.put(remoteAddr);
|
||||
if (remoteAddr.length > 0) {
|
||||
buffer.put(remoteAddr);
|
||||
}
|
||||
buffer.putChar((char) sessionid.length);
|
||||
if (sessionid.length > 0) buffer.put(sessionid);
|
||||
if (sessionid.length > 0) {
|
||||
buffer.put(sessionid);
|
||||
}
|
||||
buffer.putChar((char) contentType.length);
|
||||
if (contentType.length > 0) buffer.put(contentType);
|
||||
if (contentType.length > 0) {
|
||||
buffer.put(contentType);
|
||||
}
|
||||
buffer.putChar((char) userid.length);
|
||||
if (userid.length > 0) buffer.put(userid);
|
||||
if (userid.length > 0) {
|
||||
buffer.put(userid);
|
||||
}
|
||||
buffer.put(headers);
|
||||
buffer.put(params);
|
||||
buffer.putInt(body.length);
|
||||
if (body.length > 0) buffer.put(body);
|
||||
if (body.length > 0) {
|
||||
buffer.put(body);
|
||||
}
|
||||
return bs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public HttpSimpleRequest decode(byte[] data) {
|
||||
if (data == null) return null;
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.wrap(data);
|
||||
HttpSimpleRequest req = new HttpSimpleRequest();
|
||||
byte opt = buffer.get();
|
||||
@@ -91,8 +109,12 @@ public class HttpSimpleRequestCoder implements MessageCoder<HttpSimpleRequest> {
|
||||
req.setHashid(buffer.getInt());
|
||||
int reqformat = buffer.getInt();
|
||||
int respformat = buffer.getInt();
|
||||
if (reqformat != 0) req.setReqConvertType(ConvertType.find(reqformat));
|
||||
if (respformat != 0) req.setRespConvertType(ConvertType.find(respformat));
|
||||
if (reqformat != 0) {
|
||||
req.setReqConvertType(ConvertType.find(reqformat));
|
||||
}
|
||||
if (respformat != 0) {
|
||||
req.setRespConvertType(ConvertType.find(respformat));
|
||||
}
|
||||
req.setTraceid(MessageCoder.getShortString(buffer));
|
||||
req.setRequestURI(MessageCoder.getLongString(buffer));
|
||||
req.setPath(MessageCoder.getShortString(buffer));
|
||||
@@ -113,7 +135,9 @@ public class HttpSimpleRequestCoder implements MessageCoder<HttpSimpleRequest> {
|
||||
|
||||
protected static String getString(ByteBuffer buffer) {
|
||||
int len = buffer.getInt();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
byte[] bs = new byte[len];
|
||||
buffer.get(bs);
|
||||
return new String(bs, StandardCharsets.UTF_8);
|
||||
|
||||
@@ -76,8 +76,12 @@ public abstract class MessageAgent implements Resourcable {
|
||||
Class<MessageCoder<MessageRecord>> coderClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(coderType);
|
||||
RedkaleClassLoader.putReflectionPublicConstructors(coderClass, coderClass.getName());
|
||||
MessageCoder<MessageRecord> coder = coderClass.getConstructor().newInstance();
|
||||
if (factory != null) factory.inject(coder);
|
||||
if (coder instanceof Service) ((Service) coder).init(config);
|
||||
if (factory != null) {
|
||||
factory.inject(coder);
|
||||
}
|
||||
if (coder instanceof Service) {
|
||||
((Service) coder).init(config);
|
||||
}
|
||||
this.messageCoder = coder;
|
||||
} catch (RuntimeException ex) {
|
||||
throw ex;
|
||||
@@ -121,30 +125,50 @@ public abstract class MessageAgent implements Resourcable {
|
||||
public void destroy(AnyValue config) {
|
||||
this.httpMessageClient.close().join();
|
||||
this.sncpMessageClient.close().join();
|
||||
if (this.timeoutExecutor != null) this.timeoutExecutor.shutdown();
|
||||
if (this.sncpProducer != null) this.sncpProducer.shutdown().join();
|
||||
if (this.httpProducer != null) this.httpProducer.shutdown().join();
|
||||
if (this.messageCoder instanceof Service) ((Service) this.messageCoder).destroy(config);
|
||||
if (this.timeoutExecutor != null) {
|
||||
this.timeoutExecutor.shutdown();
|
||||
}
|
||||
if (this.sncpProducer != null) {
|
||||
this.sncpProducer.shutdown().join();
|
||||
}
|
||||
if (this.httpProducer != null) {
|
||||
this.httpProducer.shutdown().join();
|
||||
}
|
||||
if (this.messageCoder instanceof Service) {
|
||||
((Service) this.messageCoder).destroy(config);
|
||||
}
|
||||
}
|
||||
|
||||
protected List<MessageConsumer> getAllMessageConsumer() {
|
||||
List<MessageConsumer> consumers = new ArrayList<>();
|
||||
MessageConsumer one = this.httpMessageClient == null ? null : this.httpMessageClient.respConsumer;
|
||||
if (one != null) consumers.add(one);
|
||||
if (one != null) {
|
||||
consumers.add(one);
|
||||
}
|
||||
one = this.sncpMessageClient == null ? null : this.sncpMessageClient.respConsumer;
|
||||
if (one != null) consumers.add(one);
|
||||
if (one != null) {
|
||||
consumers.add(one);
|
||||
}
|
||||
consumers.addAll(messageNodes.values().stream().map(mcn -> mcn.consumer).collect(Collectors.toList()));
|
||||
return consumers;
|
||||
}
|
||||
|
||||
protected List<MessageProducer> getAllMessageProducer() {
|
||||
List<MessageProducer> producers = new ArrayList<>();
|
||||
if (this.httpProducer != null) producers.addAll(Utility.ofList(this.httpProducer.producers));
|
||||
if (this.sncpProducer != null) producers.addAll(Utility.ofList(this.sncpProducer.producers));
|
||||
if (this.httpProducer != null) {
|
||||
producers.addAll(Utility.ofList(this.httpProducer.producers));
|
||||
}
|
||||
if (this.sncpProducer != null) {
|
||||
producers.addAll(Utility.ofList(this.sncpProducer.producers));
|
||||
}
|
||||
MessageProducers one = this.httpMessageClient == null ? null : this.httpMessageClient.getProducer();
|
||||
if (one != null) producers.addAll(Utility.ofList(one.producers));
|
||||
if (one != null) {
|
||||
producers.addAll(Utility.ofList(one.producers));
|
||||
}
|
||||
one = this.sncpMessageClient == null ? null : this.sncpMessageClient.getProducer();
|
||||
if (one != null) producers.addAll(Utility.ofList(one.producers));
|
||||
if (one != null) {
|
||||
producers.addAll(Utility.ofList(one.producers));
|
||||
}
|
||||
return producers;
|
||||
}
|
||||
|
||||
@@ -182,8 +206,12 @@ public abstract class MessageAgent implements Resourcable {
|
||||
}
|
||||
|
||||
protected String checkName(String name) { //不能含特殊字符
|
||||
if (name.isEmpty()) return name;
|
||||
if (name.charAt(0) >= '0' && name.charAt(0) <= '9') throw new RuntimeException("name only 0-9 a-z A-Z _ cannot begin 0-9");
|
||||
if (name.isEmpty()) {
|
||||
return name;
|
||||
}
|
||||
if (name.charAt(0) >= '0' && name.charAt(0) <= '9') {
|
||||
throw new RuntimeException("name only 0-9 a-z A-Z _ cannot begin 0-9");
|
||||
}
|
||||
for (char ch : name.toCharArray()) {
|
||||
if (!((ch >= '0' && ch <= '9') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { //不能含特殊字符
|
||||
throw new RuntimeException("name only 0-9 a-z A-Z _ cannot begin 0-9");
|
||||
@@ -205,7 +233,9 @@ public abstract class MessageAgent implements Resourcable {
|
||||
producers[i] = producer;
|
||||
}
|
||||
long e = System.currentTimeMillis() - s;
|
||||
if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "MessageAgent.SncpProducer startup all in " + e + "ms");
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.log(Level.FINEST, "MessageAgent.SncpProducer startup all in " + e + "ms");
|
||||
}
|
||||
this.sncpProducer = new MessageProducers(producers);
|
||||
}
|
||||
}
|
||||
@@ -225,7 +255,9 @@ public abstract class MessageAgent implements Resourcable {
|
||||
producers[i] = producer;
|
||||
}
|
||||
long e = System.currentTimeMillis() - s;
|
||||
if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "MessageAgent.HttpProducer startup all in " + e + "ms");
|
||||
if (logger.isLoggable(Level.FINEST)) {
|
||||
logger.log(Level.FINEST, "MessageAgent.HttpProducer startup all in " + e + "ms");
|
||||
}
|
||||
this.httpProducer = new MessageProducers(producers);
|
||||
}
|
||||
}
|
||||
@@ -253,28 +285,42 @@ public abstract class MessageAgent implements Resourcable {
|
||||
|
||||
public final synchronized void putService(NodeHttpServer ns, Service service, HttpServlet servlet) {
|
||||
AutoLoad al = service.getClass().getAnnotation(AutoLoad.class);
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) return;
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return;
|
||||
}
|
||||
org.redkale.util.AutoLoad al2 = service.getClass().getAnnotation(org.redkale.util.AutoLoad.class);
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) return;
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return;
|
||||
}
|
||||
{ //标记@RestService(name = " ") 需要跳过, 一般作为模板引擎
|
||||
RestService rest = service.getClass().getAnnotation(RestService.class);
|
||||
if (rest != null && !rest.name().isEmpty() && rest.name().trim().isEmpty()) return;
|
||||
if (rest != null && !rest.name().isEmpty() && rest.name().trim().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
String[] topics = generateHttpReqTopics(service);
|
||||
String consumerid = generateHttpConsumerid(topics, service);
|
||||
if (messageNodes.containsKey(consumerid)) throw new RuntimeException("consumerid(" + consumerid + ") is repeat");
|
||||
if (messageNodes.containsKey(consumerid)) {
|
||||
throw new RuntimeException("consumerid(" + consumerid + ") is repeat");
|
||||
}
|
||||
HttpMessageProcessor processor = new HttpMessageProcessor(this.logger, httpMessageClient, getHttpProducer(), ns, service, servlet);
|
||||
this.messageNodes.put(consumerid, new MessageConsumerNode(ns, service, servlet, processor, createConsumer(topics, consumerid, processor)));
|
||||
}
|
||||
|
||||
public final synchronized void putService(NodeSncpServer ns, Service service, SncpServlet servlet) {
|
||||
AutoLoad al = service.getClass().getAnnotation(AutoLoad.class);
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) return;
|
||||
if (al != null && !al.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return;
|
||||
}
|
||||
org.redkale.util.AutoLoad al2 = service.getClass().getAnnotation(org.redkale.util.AutoLoad.class);
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) return;
|
||||
if (al2 != null && !al2.value() && service.getClass().getAnnotation(Local.class) != null) {
|
||||
return;
|
||||
}
|
||||
String topic = generateSncpReqTopic(service);
|
||||
String consumerid = generateSncpConsumerid(topic, service);
|
||||
if (messageNodes.containsKey(consumerid)) throw new RuntimeException("consumerid(" + consumerid + ") is repeat");
|
||||
if (messageNodes.containsKey(consumerid)) {
|
||||
throw new RuntimeException("consumerid(" + consumerid + ") is repeat");
|
||||
}
|
||||
SncpMessageProcessor processor = new SncpMessageProcessor(this.logger, sncpMessageClient, getSncpProducer(), ns, service, servlet);
|
||||
this.messageNodes.put(consumerid, new MessageConsumerNode(ns, service, servlet, processor, createConsumer(new String[]{topic}, consumerid, processor)));
|
||||
}
|
||||
@@ -319,7 +365,9 @@ public abstract class MessageAgent implements Resourcable {
|
||||
String resname = Sncp.getResourceName(service);
|
||||
String module = Rest.getRestModule(service).toLowerCase();
|
||||
MessageMultiConsumer mmc = service.getClass().getAnnotation(MessageMultiConsumer.class);
|
||||
if (mmc != null) return new String[]{generateHttpReqTopic(mmc.module()) + (resname.isEmpty() ? "" : ("-" + resname))};
|
||||
if (mmc != null) {
|
||||
return new String[]{generateHttpReqTopic(mmc.module()) + (resname.isEmpty() ? "" : ("-" + resname))};
|
||||
}
|
||||
return new String[]{"http.req." + module + (resname.isEmpty() ? "" : ("-" + resname))};
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import org.redkale.convert.Convert;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import static org.redkale.mq.MessageRecord.*;
|
||||
import org.redkale.net.http.*;
|
||||
import org.redkale.util.*;
|
||||
import org.redkale.util.Traces;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -47,7 +47,9 @@ public abstract class MessageClient {
|
||||
}
|
||||
|
||||
protected CompletableFuture<Void> close() {
|
||||
if (this.respConsumer == null) return CompletableFuture.completedFuture(null);
|
||||
if (this.respConsumer == null) {
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
return this.respConsumer.shutdown();
|
||||
}
|
||||
|
||||
@@ -68,11 +70,17 @@ public abstract class MessageClient {
|
||||
messageAgent.logger.log(Level.WARNING, MessageClient.this.getClass().getSimpleName() + " process " + msg + " error, not found mqresp.futurenode");
|
||||
return;
|
||||
}
|
||||
if (node.scheduledFuture != null) node.scheduledFuture.cancel(true);
|
||||
if (node.scheduledFuture != null) {
|
||||
node.scheduledFuture.cancel(true);
|
||||
}
|
||||
AtomicLong ncer = node.getCounter();
|
||||
if (ncer != null) ncer.decrementAndGet();
|
||||
if (ncer != null) {
|
||||
ncer.decrementAndGet();
|
||||
}
|
||||
final long cha = now - msg.createTime;
|
||||
if (finest) messageAgent.logger.log(Level.FINEST, clazzName + ".MessageRespFutureNode.receive (mq.delay = " + cha + "ms, mq.seqid = " + msg.getSeqid() + ")");
|
||||
if (finest) {
|
||||
messageAgent.logger.log(Level.FINEST, clazzName + ".MessageRespFutureNode.receive (mq.delay = " + cha + "ms, mq.seqid = " + msg.getSeqid() + ")");
|
||||
}
|
||||
node.future.complete(msg);
|
||||
long cha2 = System.currentTimeMillis() - now;
|
||||
if ((cha > 1000 || cha2 > 1000) && messageAgent != null && messageAgent.logger.isLoggable(Level.FINE)) {
|
||||
@@ -87,7 +95,9 @@ public abstract class MessageClient {
|
||||
MessageConsumer one = messageAgent.createConsumer(new String[]{respTopic}, respConsumerid, processor);
|
||||
one.startup().join();
|
||||
long onee = System.currentTimeMillis() - ones;
|
||||
if (finest) messageAgent.logger.log(Level.FINEST, clazzName + ".MessageRespFutureNode.startup " + onee + "ms ");
|
||||
if (finest) {
|
||||
messageAgent.logger.log(Level.FINEST, clazzName + ".MessageRespFutureNode.startup " + onee + "ms ");
|
||||
}
|
||||
this.respConsumer = one;
|
||||
}
|
||||
}
|
||||
@@ -95,7 +105,9 @@ public abstract class MessageClient {
|
||||
if (needresp && (message.getRespTopic() == null || message.getRespTopic().isEmpty())) {
|
||||
message.setRespTopic(respTopic);
|
||||
}
|
||||
if (counter != null) counter.incrementAndGet();
|
||||
if (counter != null) {
|
||||
counter.incrementAndGet();
|
||||
}
|
||||
getProducer().apply(message);
|
||||
if (needresp) {
|
||||
MessageRespFutureNode node = new MessageRespFutureNode(messageAgent.logger, message, respNodes, counter, future);
|
||||
|
||||
@@ -35,7 +35,9 @@ public interface MessageCoder<T> {
|
||||
|
||||
//type: 1:string, 2:int, 3:long
|
||||
public static byte[] encodeUserid(Serializable value) {
|
||||
if (value == null) return MessageRecord.EMPTY_BYTES;
|
||||
if (value == null) {
|
||||
return MessageRecord.EMPTY_BYTES;
|
||||
}
|
||||
if (value instanceof Integer) {
|
||||
int val = (Integer) value;
|
||||
return new byte[]{(byte) 2, (byte) (val >> 24 & 0xFF), (byte) (val >> 16 & 0xFF), (byte) (val >> 8 & 0xFF), (byte) (val & 0xFF)};
|
||||
@@ -45,34 +47,48 @@ public interface MessageCoder<T> {
|
||||
(byte) (val >> 32 & 0xFF), (byte) (val >> 24 & 0xFF), (byte) (val >> 16 & 0xFF), (byte) (val >> 8 & 0xFF), (byte) (val & 0xFF)};
|
||||
}
|
||||
String str = value.toString();
|
||||
if (str.isEmpty()) return MessageRecord.EMPTY_BYTES;
|
||||
if (str.isEmpty()) {
|
||||
return MessageRecord.EMPTY_BYTES;
|
||||
}
|
||||
return Utility.append(new byte[]{(byte) 1}, str.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
//type: 1:string, 2:int, 3:long
|
||||
public static Serializable decodeUserid(ByteBuffer buffer) {
|
||||
int len = buffer.getChar();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
byte type = buffer.get();
|
||||
if (type == 2) return buffer.getInt();
|
||||
if (type == 3) return buffer.getLong();
|
||||
if (type == 2) {
|
||||
return buffer.getInt();
|
||||
}
|
||||
if (type == 3) {
|
||||
return buffer.getLong();
|
||||
}
|
||||
byte[] bs = new byte[len - 1];
|
||||
buffer.get(bs);
|
||||
return new String(bs, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static byte[] getBytes(byte[] value) {
|
||||
if (value == null) return MessageRecord.EMPTY_BYTES;
|
||||
if (value == null) {
|
||||
return MessageRecord.EMPTY_BYTES;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static byte[] getBytes(String value) {
|
||||
if (value == null || value.isEmpty()) return MessageRecord.EMPTY_BYTES;
|
||||
if (value == null || value.isEmpty()) {
|
||||
return MessageRecord.EMPTY_BYTES;
|
||||
}
|
||||
return value.getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static byte[] getBytes(final Map<String, String> map) {
|
||||
if (map == null || map.isEmpty()) return new byte[2];
|
||||
if (map == null || map.isEmpty()) {
|
||||
return new byte[2];
|
||||
}
|
||||
final AtomicInteger len = new AtomicInteger(2);
|
||||
map.forEach((key, value) -> {
|
||||
len.addAndGet(2 + (key == null ? 0 : Utility.encodeUTF8Length(key)));
|
||||
@@ -100,7 +116,9 @@ public interface MessageCoder<T> {
|
||||
|
||||
public static String getLongString(ByteBuffer buffer) {
|
||||
int len = buffer.getInt();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
byte[] bs = new byte[len];
|
||||
buffer.get(bs);
|
||||
return new String(bs, StandardCharsets.UTF_8);
|
||||
@@ -118,7 +136,9 @@ public interface MessageCoder<T> {
|
||||
|
||||
public static String getShortString(ByteBuffer buffer) {
|
||||
int len = buffer.getChar();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
byte[] bs = new byte[len];
|
||||
buffer.get(bs);
|
||||
return new String(bs, StandardCharsets.UTF_8);
|
||||
@@ -126,7 +146,9 @@ public interface MessageCoder<T> {
|
||||
|
||||
public static Map<String, String> getMap(ByteBuffer buffer) {
|
||||
int len = buffer.getChar();
|
||||
if (len == 0) return null;
|
||||
if (len == 0) {
|
||||
return null;
|
||||
}
|
||||
Map<String, String> map = new HashMap<>(len);
|
||||
for (int i = 0; i < len; i++) {
|
||||
map.put(getShortString(buffer), getLongString(buffer));
|
||||
|
||||
@@ -7,12 +7,12 @@ package org.redkale.mq;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.redkale.annotation.Comment;
|
||||
import org.redkale.convert.*;
|
||||
import org.redkale.convert.bson.BsonConvert;
|
||||
import org.redkale.convert.json.JsonConvert;
|
||||
import org.redkale.net.http.HttpSimpleRequest;
|
||||
import org.redkale.net.sncp.SncpRequest;
|
||||
import org.redkale.annotation.Comment;
|
||||
|
||||
/**
|
||||
* 存在MQ里面的数据结构<p>
|
||||
@@ -135,12 +135,16 @@ public class MessageRecord implements Serializable {
|
||||
}
|
||||
|
||||
public <T> T convertFromContent(Convert convert, java.lang.reflect.Type type) {
|
||||
if (this.content == null || this.content.length == 0) return null;
|
||||
if (this.content == null || this.content.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return (T) convert.convertFrom(type, this.content);
|
||||
}
|
||||
|
||||
public <T> T decodeContent(MessageCoder<T> coder) {
|
||||
if (this.content == null || this.content.length == 0) return null;
|
||||
if (this.content == null || this.content.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return (T) coder.decode(this.content);
|
||||
}
|
||||
|
||||
@@ -295,12 +299,24 @@ public class MessageRecord implements Serializable {
|
||||
StringBuilder sb = new StringBuilder(128);
|
||||
sb.append("{\"seqid\":").append(this.seqid);
|
||||
sb.append(",\"version\":").append(this.version);
|
||||
if (this.flag != 0) sb.append(",\"flag\":").append(this.flag);
|
||||
if (this.createTime != 0) sb.append(",\"createTime\":").append(this.createTime);
|
||||
if (this.userid != null) sb.append(",\"userid\":").append(this.userid);
|
||||
if (this.groupid != null) sb.append(",\"groupid\":\"").append(this.groupid).append("\"");
|
||||
if (this.topic != null) sb.append(",\"topic\":\"").append(this.topic).append("\"");
|
||||
if (this.respTopic != null) sb.append(",\"respTopic\":\"").append(this.respTopic).append("\"");
|
||||
if (this.flag != 0) {
|
||||
sb.append(",\"flag\":").append(this.flag);
|
||||
}
|
||||
if (this.createTime != 0) {
|
||||
sb.append(",\"createTime\":").append(this.createTime);
|
||||
}
|
||||
if (this.userid != null) {
|
||||
sb.append(",\"userid\":").append(this.userid);
|
||||
}
|
||||
if (this.groupid != null) {
|
||||
sb.append(",\"groupid\":\"").append(this.groupid).append("\"");
|
||||
}
|
||||
if (this.topic != null) {
|
||||
sb.append(",\"topic\":\"").append(this.topic).append("\"");
|
||||
}
|
||||
if (this.respTopic != null) {
|
||||
sb.append(",\"respTopic\":\"").append(this.respTopic).append("\"");
|
||||
}
|
||||
if (this.content != null) {
|
||||
if (this.ctype == CTYPE_BSON_RESULT && this.content.length > SncpRequest.HEADER_SIZE) {
|
||||
int offset = SncpRequest.HEADER_SIZE + 1; //循环占位符
|
||||
@@ -309,8 +325,12 @@ public class MessageRecord implements Serializable {
|
||||
} else if (this.ctype == CTYPE_HTTP_REQUEST) {
|
||||
HttpSimpleRequest req = HttpSimpleRequestCoder.getInstance().decode(this.content);
|
||||
if (req != null) {
|
||||
if (req.getCurrentUserid() == null) req.setCurrentUserid(this.userid);
|
||||
if (req.getHashid() == 0) req.setHashid(this.hash());
|
||||
if (req.getCurrentUserid() == null) {
|
||||
req.setCurrentUserid(this.userid);
|
||||
}
|
||||
if (req.getHashid() == 0) {
|
||||
req.setHashid(this.hash());
|
||||
}
|
||||
}
|
||||
sb.append(",\"content\":").append(req);
|
||||
} else if (this.ctype == CTYPE_HTTP_RESULT) {
|
||||
|
||||
@@ -28,7 +28,9 @@ public class MessageRecordCoder implements MessageCoder<MessageRecord> {
|
||||
|
||||
@Override
|
||||
public byte[] encode(MessageRecord data) {
|
||||
if (data == null) return null;
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
byte[] userid = MessageCoder.encodeUserid(data.getUserid());
|
||||
byte[] groupid = MessageCoder.getBytes(data.getGroupid());
|
||||
byte[] topic = MessageCoder.getBytes(data.getTopic());
|
||||
@@ -52,22 +54,32 @@ public class MessageRecordCoder implements MessageCoder<MessageRecord> {
|
||||
buffer.putInt(data.getVersion());
|
||||
buffer.putInt(data.getFlag());
|
||||
buffer.putLong(data.getCreateTime());
|
||||
|
||||
|
||||
buffer.putChar((char) userid.length);
|
||||
if (userid.length > 0) buffer.put(userid);
|
||||
|
||||
if (userid.length > 0) {
|
||||
buffer.put(userid);
|
||||
}
|
||||
|
||||
buffer.putChar((char) groupid.length);
|
||||
if (groupid.length > 0) buffer.put(groupid);
|
||||
|
||||
if (groupid.length > 0) {
|
||||
buffer.put(groupid);
|
||||
}
|
||||
|
||||
buffer.putChar((char) topic.length);
|
||||
if (topic.length > 0) buffer.put(topic);
|
||||
|
||||
if (topic.length > 0) {
|
||||
buffer.put(topic);
|
||||
}
|
||||
|
||||
buffer.putChar((char) respTopic.length);
|
||||
if (respTopic.length > 0) buffer.put(respTopic);
|
||||
|
||||
if (respTopic.length > 0) {
|
||||
buffer.put(respTopic);
|
||||
}
|
||||
|
||||
buffer.putChar((char) traceid.length);
|
||||
if (traceid.length > 0) buffer.put(traceid);
|
||||
|
||||
if (traceid.length > 0) {
|
||||
buffer.put(traceid);
|
||||
}
|
||||
|
||||
if (data.getContent() == null) {
|
||||
buffer.putInt(0);
|
||||
} else {
|
||||
@@ -79,7 +91,9 @@ public class MessageRecordCoder implements MessageCoder<MessageRecord> {
|
||||
|
||||
@Override
|
||||
public MessageRecord decode(byte[] data) {
|
||||
if (data == null) return null;
|
||||
if (data == null) {
|
||||
return null;
|
||||
}
|
||||
ByteBuffer buffer = ByteBuffer.wrap(data);
|
||||
long seqid = buffer.getLong();
|
||||
byte ctype = buffer.get();
|
||||
|
||||
@@ -55,7 +55,9 @@ public class SncpMessageClient extends MessageClient {
|
||||
|
||||
@Override
|
||||
protected MessageRecord formatRespMessage(MessageRecord message) {
|
||||
if (message != null) message.ctype = MessageRecord.CTYPE_BSON_RESULT;
|
||||
if (message != null) {
|
||||
message.ctype = MessageRecord.CTYPE_BSON_RESULT;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,9 @@ public class SncpMessageProcessor implements MessageProcessor {
|
||||
protected long starttime;
|
||||
|
||||
protected final Runnable innerCallback = () -> {
|
||||
if (cdl != null) cdl.countDown();
|
||||
if (cdl != null) {
|
||||
cdl.countDown();
|
||||
}
|
||||
};
|
||||
|
||||
public SncpMessageProcessor(Logger logger, SncpMessageClient messageClient, MessageProducers producer, NodeSncpServer server, Service service, SncpServlet servlet) {
|
||||
@@ -85,7 +87,9 @@ public class SncpMessageProcessor implements MessageProcessor {
|
||||
logger.log(Level.FINEST, "SncpMessageProcessor.process (mq.delay = " + cha + " ms, mq.block = " + e + " ms, mq.execute = " + o + " ms) message: " + message);
|
||||
}
|
||||
} catch (Throwable ex) {
|
||||
if (response != null) response.finish(SncpResponse.RETCODE_ILLSERVICEID, null);
|
||||
if (response != null) {
|
||||
response.finish(SncpResponse.RETCODE_ILLSERVICEID, null);
|
||||
}
|
||||
logger.log(Level.SEVERE, SncpMessageProcessor.class.getSimpleName() + " process error, message=" + message, ex instanceof CompletionException ? ((CompletionException) ex).getCause() : ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,7 @@
|
||||
package org.redkale.mq;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.logging.*;
|
||||
import org.redkale.net.sncp.*;
|
||||
import org.redkale.util.Utility;
|
||||
|
||||
@@ -35,7 +34,9 @@ public class SncpMessageRequest extends SncpRequest {
|
||||
|
||||
@Override //被SncpAsyncHandler.sncp_setParams调用
|
||||
protected void sncp_setParams(SncpDynServlet.SncpServletAction action, Logger logger, Object... params) {
|
||||
if (message.localAttach != null) return;
|
||||
if (message.localAttach != null) {
|
||||
return;
|
||||
}
|
||||
if (logger.isLoggable(Level.FINER)) {
|
||||
message.attach(Utility.append(new Object[]{action.actionName()}, params));
|
||||
} else {
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
package org.redkale.mq;
|
||||
|
||||
import org.redkale.convert.bson.BsonWriter;
|
||||
import org.redkale.net.sncp.*;
|
||||
import static org.redkale.net.sncp.SncpRequest.HEADER_SIZE;
|
||||
import org.redkale.net.sncp.*;
|
||||
import org.redkale.util.ByteArray;
|
||||
|
||||
/**
|
||||
@@ -47,7 +47,9 @@ public class SncpMessageResponse extends SncpResponse {
|
||||
|
||||
@Override
|
||||
public void finish(final int retcode, final BsonWriter out) {
|
||||
if (callback != null) callback.run();
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
if (out == null) {
|
||||
final ByteArray result = new ByteArray(SncpRequest.HEADER_SIZE);
|
||||
fillHeader(result, 0, retcode);
|
||||
|
||||
@@ -5,17 +5,19 @@
|
||||
*/
|
||||
package org.redkale.net;
|
||||
|
||||
import java.io.*;
|
||||
import java.io.IOException;
|
||||
import java.net.*;
|
||||
import java.nio.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
import java.util.function.*;
|
||||
import javax.net.ssl.*;
|
||||
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
|
||||
import static javax.net.ssl.SSLEngineResult.Status.*;
|
||||
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.*;
|
||||
import static javax.net.ssl.SSLEngineResult.Status.*;
|
||||
import javax.net.ssl.*;
|
||||
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.*;
|
||||
import static javax.net.ssl.SSLEngineResult.Status.*;
|
||||
import org.redkale.util.*;
|
||||
|
||||
/**
|
||||
@@ -266,7 +268,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
buffer.put(headerContent, headerOffset, headerLength);
|
||||
if (bodyLength > 0) {
|
||||
buffer.put(bodyContent, bodyOffset, bodyLength);
|
||||
if (bodyCallback != null) bodyCallback.accept(bodyAttachment);
|
||||
if (bodyCallback != null) {
|
||||
bodyCallback.accept(bodyAttachment);
|
||||
}
|
||||
}
|
||||
buffer.flip();
|
||||
CompletionHandler<Integer, Void> newhandler = new CompletionHandler<Integer, Void>() {
|
||||
@@ -288,7 +292,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
writer.put(headerContent, headerOffset, headerLength);
|
||||
if (bodyLength > 0) {
|
||||
writer.put(bodyContent, bodyOffset, bodyLength);
|
||||
if (bodyCallback != null) bodyCallback.accept(bodyAttachment);
|
||||
if (bodyCallback != null) {
|
||||
bodyCallback.accept(bodyAttachment);
|
||||
}
|
||||
}
|
||||
final ByteBuffer[] buffers = writer.toBuffers();
|
||||
CompletionHandler<Integer, Void> newhandler = new CompletionHandler<Integer, Void>() {
|
||||
@@ -309,7 +315,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
}
|
||||
|
||||
public void setReadBuffer(ByteBuffer buffer) {
|
||||
if (this.readBuffer != null) throw new RuntimeException("repeat AsyncConnection.setReadBuffer");
|
||||
if (this.readBuffer != null) {
|
||||
throw new RuntimeException("repeat AsyncConnection.setReadBuffer");
|
||||
}
|
||||
this.readBuffer = buffer;
|
||||
}
|
||||
|
||||
@@ -514,7 +522,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
}
|
||||
|
||||
protected void setReadSSLBuffer(ByteBuffer buffer) {
|
||||
if (this.readSSLHalfBuffer != null) throw new RuntimeException("repeat AsyncConnection.setReadSSLBuffer");
|
||||
if (this.readSSLHalfBuffer != null) {
|
||||
throw new RuntimeException("repeat AsyncConnection.setReadSSLBuffer");
|
||||
}
|
||||
this.readSSLHalfBuffer = buffer;
|
||||
}
|
||||
|
||||
@@ -537,12 +547,16 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
}
|
||||
|
||||
public void offerBuffer(ByteBuffer buffer) {
|
||||
if (buffer == null) return;
|
||||
if (buffer == null) {
|
||||
return;
|
||||
}
|
||||
bufferConsumer.accept(buffer);
|
||||
}
|
||||
|
||||
public void offerBuffer(ByteBuffer... buffers) {
|
||||
if (buffers == null) return;
|
||||
if (buffers == null) {
|
||||
return;
|
||||
}
|
||||
Consumer<ByteBuffer> consumer = this.bufferConsumer;
|
||||
for (ByteBuffer buffer : buffers) {
|
||||
consumer.accept(buffer);
|
||||
@@ -595,12 +609,18 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
}
|
||||
if (this.readBuffer != null) {
|
||||
Consumer<ByteBuffer> consumer = this.bufferConsumer;
|
||||
if (consumer != null) consumer.accept(this.readBuffer);
|
||||
if (consumer != null) {
|
||||
consumer.accept(this.readBuffer);
|
||||
}
|
||||
}
|
||||
if (attributes == null) {
|
||||
return;
|
||||
}
|
||||
if (attributes == null) return;
|
||||
try {
|
||||
for (Object obj : attributes.values()) {
|
||||
if (obj instanceof AutoCloseable) ((AutoCloseable) obj).close();
|
||||
if (obj instanceof AutoCloseable) {
|
||||
((AutoCloseable) obj).close();
|
||||
}
|
||||
}
|
||||
attributes.clear();
|
||||
} catch (Exception io) {
|
||||
@@ -618,7 +638,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
|
||||
@Override
|
||||
public void setAttribute(String name, Object value) {
|
||||
if (this.attributes == null) this.attributes = new HashMap<>();
|
||||
if (this.attributes == null) {
|
||||
this.attributes = new HashMap<>();
|
||||
}
|
||||
this.attributes.put(name, value);
|
||||
}
|
||||
|
||||
@@ -630,7 +652,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
|
||||
@Override
|
||||
public final void removeAttribute(String name) {
|
||||
if (this.attributes != null) this.attributes.remove(name);
|
||||
if (this.attributes != null) {
|
||||
this.attributes.remove(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -640,7 +664,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
|
||||
@Override
|
||||
public final void clearAttribute() {
|
||||
if (this.attributes != null) this.attributes.clear();
|
||||
if (this.attributes != null) {
|
||||
this.attributes.clear();
|
||||
}
|
||||
}
|
||||
|
||||
protected void startHandshake(final Consumer<Throwable> callback) {
|
||||
@@ -702,7 +728,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
netBuffer.flip();
|
||||
try {
|
||||
ByteBuffer appBuffer = sslUnwrap(handshake, netBuffer);
|
||||
if (appBuffer == null) return; //CLOSED,netBuffer已被回收
|
||||
if (appBuffer == null) {
|
||||
return; //CLOSED,netBuffer已被回收
|
||||
}
|
||||
if (AsyncConnection.this.readSSLHalfBuffer != netBuffer) {
|
||||
offerBuffer(netBuffer);
|
||||
}
|
||||
@@ -912,7 +940,9 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
callback.accept(t);
|
||||
}
|
||||
});
|
||||
if (rs) return;
|
||||
if (rs) {
|
||||
return;
|
||||
}
|
||||
} catch (SSLException e) {
|
||||
callback.accept(e);
|
||||
return;
|
||||
@@ -946,9 +976,13 @@ public abstract class AsyncConnection implements ChannelContext, Channel, AutoCl
|
||||
public String toString() {
|
||||
String s = super.toString();
|
||||
int pos = s.lastIndexOf('@');
|
||||
if (pos < 1) return s;
|
||||
if (pos < 1) {
|
||||
return s;
|
||||
}
|
||||
int cha = pos + 10 - s.length();
|
||||
if (cha < 1) return s;
|
||||
if (cha < 1) {
|
||||
return s;
|
||||
}
|
||||
for (int i = 0; i < cha; i++) s += ' ';
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ import java.nio.ByteBuffer;
|
||||
import java.nio.channels.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.*;
|
||||
|
||||
import org.redkale.annotation.ResourceType;
|
||||
import org.redkale.util.*;
|
||||
|
||||
@@ -60,7 +59,9 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
public AsyncIOGroup(boolean client, String threadPrefixName, final ExecutorService workExecutor, final int bufferCapacity, final int bufferPoolSize) {
|
||||
this(client, threadPrefixName, workExecutor, bufferCapacity, ObjectPool.createSafePool(null, null, bufferPoolSize,
|
||||
(Object... params) -> ByteBuffer.allocateDirect(bufferCapacity), null, (e) -> {
|
||||
if (e == null || e.isReadOnly() || e.capacity() != bufferCapacity) return false;
|
||||
if (e == null || e.isReadOnly() || e.capacity() != bufferCapacity) {
|
||||
return false;
|
||||
}
|
||||
e.clear();
|
||||
return true;
|
||||
}));
|
||||
@@ -101,24 +102,36 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
|
||||
@Override
|
||||
public AsyncGroup start() {
|
||||
if (started) return this;
|
||||
if (closed) throw new RuntimeException("group is closed");
|
||||
if (started) {
|
||||
return this;
|
||||
}
|
||||
if (closed) {
|
||||
throw new RuntimeException("group is closed");
|
||||
}
|
||||
for (AsyncIOThread thread : ioThreads) {
|
||||
thread.start();
|
||||
}
|
||||
if (connectThread != null) connectThread.start();
|
||||
if (connectThread != null) {
|
||||
connectThread.start();
|
||||
}
|
||||
started = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AsyncGroup close() {
|
||||
if (shareCount.decrementAndGet() > 0) return this;
|
||||
if (closed) return this;
|
||||
if (shareCount.decrementAndGet() > 0) {
|
||||
return this;
|
||||
}
|
||||
if (closed) {
|
||||
return this;
|
||||
}
|
||||
for (AsyncIOThread thread : ioThreads) {
|
||||
thread.close();
|
||||
}
|
||||
if (connectThread != null) connectThread.close();
|
||||
if (connectThread != null) {
|
||||
connectThread.close();
|
||||
}
|
||||
this.timeoutExecutor.shutdownNow();
|
||||
closed = true;
|
||||
return this;
|
||||
@@ -150,9 +163,15 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
}
|
||||
|
||||
public void interestOpsOr(AsyncIOThread thread, SelectionKey key, int opt) {
|
||||
if (key == null) return;
|
||||
if (key.selector() != thread.selector) throw new RuntimeException("NioThread.selector not the same to SelectionKey.selector");
|
||||
if ((key.interestOps() & opt) != 0) return;
|
||||
if (key == null) {
|
||||
return;
|
||||
}
|
||||
if (key.selector() != thread.selector) {
|
||||
throw new RuntimeException("NioThread.selector not the same to SelectionKey.selector");
|
||||
}
|
||||
if ((key.interestOps() & opt) != 0) {
|
||||
return;
|
||||
}
|
||||
key.interestOps(key.interestOps() | opt);
|
||||
if (thread.inCurrThread()) {
|
||||
// timeoutExecutor.execute(() -> {
|
||||
@@ -191,7 +210,9 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ioThread == null) ioThread = nextIOThread();
|
||||
if (ioThread == null) {
|
||||
ioThread = nextIOThread();
|
||||
}
|
||||
final AsyncNioTcpConnection conn = new AsyncNioTcpConnection(true, this, ioThread, connectThread, channel, null, null, address, connLivingCounter, connClosedCounter);
|
||||
final CompletableFuture<AsyncConnection> future = new CompletableFuture<>();
|
||||
conn.connect(address, null, new CompletionHandler<Void, Void>() {
|
||||
@@ -199,8 +220,12 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
public void completed(Void result, Void attachment) {
|
||||
conn.setReadTimeoutSeconds(readTimeoutSeconds);
|
||||
conn.setWriteTimeoutSeconds(writeTimeoutSeconds);
|
||||
if (connCreateCounter != null) connCreateCounter.increment();
|
||||
if (connLivingCounter != null) connLivingCounter.increment();
|
||||
if (connCreateCounter != null) {
|
||||
connCreateCounter.increment();
|
||||
}
|
||||
if (connLivingCounter != null) {
|
||||
connLivingCounter.increment();
|
||||
}
|
||||
if (conn.sslEngine == null) {
|
||||
future.complete(conn);
|
||||
} else {
|
||||
@@ -242,7 +267,9 @@ public class AsyncIOGroup extends AsyncGroup {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ioThread == null) ioThread = nextIOThread();
|
||||
if (ioThread == null) {
|
||||
ioThread = nextIOThread();
|
||||
}
|
||||
AsyncNioUdpConnection conn = new AsyncNioUdpConnection(true, this, ioThread, connectThread, channel, null, null, address, connLivingCounter, connClosedCounter);
|
||||
CompletableFuture future = new CompletableFuture();
|
||||
conn.connect(address, null, new CompletionHandler<Void, Void>() {
|
||||
|
||||
@@ -69,7 +69,9 @@ public class AsyncIOThread extends AsyncThread {
|
||||
|
||||
@Override
|
||||
public void execute(Collection<Runnable> commands) {
|
||||
if (commands == null) return;
|
||||
if (commands == null) {
|
||||
return;
|
||||
}
|
||||
for (Runnable command : commands) {
|
||||
commandQueue.offer(command);
|
||||
}
|
||||
@@ -104,7 +106,9 @@ public class AsyncIOThread extends AsyncThread {
|
||||
try {
|
||||
register.accept(selector);
|
||||
} catch (Throwable t) {
|
||||
if (!this.closed) logger.log(Level.INFO, getName() + " register run failed", t);
|
||||
if (!this.closed) {
|
||||
logger.log(Level.INFO, getName() + " register run failed", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
Runnable command;
|
||||
@@ -112,11 +116,15 @@ public class AsyncIOThread extends AsyncThread {
|
||||
try {
|
||||
command.run();
|
||||
} catch (Throwable t) {
|
||||
if (!this.closed) logger.log(Level.INFO, getName() + " command run failed", t);
|
||||
if (!this.closed) {
|
||||
logger.log(Level.INFO, getName() + " command run failed", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
int count = selector.select();
|
||||
if (count == 0) continue;
|
||||
if (count == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Set<SelectionKey> keys = selector.selectedKeys();
|
||||
Iterator<SelectionKey> it = keys.iterator();
|
||||
@@ -124,7 +132,9 @@ public class AsyncIOThread extends AsyncThread {
|
||||
SelectionKey key = it.next();
|
||||
it.remove();
|
||||
invoker = 0;
|
||||
if (!key.isValid()) continue;
|
||||
if (!key.isValid()) {
|
||||
continue;
|
||||
}
|
||||
AsyncNioConnection conn = (AsyncNioConnection) key.attachment();
|
||||
if (conn.client) {
|
||||
if (key.isConnectable()) {
|
||||
@@ -155,7 +165,9 @@ public class AsyncIOThread extends AsyncThread {
|
||||
}
|
||||
}
|
||||
} catch (Throwable ex) {
|
||||
if (!this.closed) logger.log(Level.FINE, getName() + " selector run failed", ex);
|
||||
if (!this.closed) {
|
||||
logger.log(Level.FINE, getName() + " selector run failed", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,7 +308,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
int totalCount = 0;
|
||||
boolean hasRemain = true;
|
||||
boolean writeOver = true;
|
||||
if (invokeDirect) currWriteInvoker++;
|
||||
if (invokeDirect) {
|
||||
currWriteInvoker++;
|
||||
}
|
||||
while (invokeDirect && hasRemain) { //必须要将buffer写完为止
|
||||
if (writeByteTuple1Array != null) {
|
||||
final ByteBuffer buffer = pollWriteBuffer();
|
||||
@@ -316,7 +318,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
buffer.put(writeByteTuple1Array, writeByteTuple1Offset, writeByteTuple1Length);
|
||||
if (writeByteTuple2Length > 0) {
|
||||
buffer.put(writeByteTuple2Array, writeByteTuple2Offset, writeByteTuple2Length);
|
||||
if (writeByteTuple2Callback != null) writeByteTuple2Callback.accept(writeByteTuple2Attachment);
|
||||
if (writeByteTuple2Callback != null) {
|
||||
writeByteTuple2Callback.accept(writeByteTuple2Attachment);
|
||||
}
|
||||
}
|
||||
buffer.flip();
|
||||
writeByteBuffer = buffer;
|
||||
@@ -333,7 +337,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
writer.put(writeByteTuple1Array, writeByteTuple1Offset, writeByteTuple1Length);
|
||||
if (writeByteTuple2Length > 0) {
|
||||
writer.put(writeByteTuple2Array, writeByteTuple2Offset, writeByteTuple2Length);
|
||||
if (writeByteTuple2Callback != null) writeByteTuple2Callback.accept(writeByteTuple2Attachment);
|
||||
if (writeByteTuple2Callback != null) {
|
||||
writeByteTuple2Callback.accept(writeByteTuple2Attachment);
|
||||
}
|
||||
}
|
||||
final ByteBuffer[] buffers = writer.toBuffers();
|
||||
writeByteBuffers = buffers;
|
||||
@@ -378,12 +384,16 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
}
|
||||
break;
|
||||
} else if (writeCount < 0) {
|
||||
if (totalCount == 0) totalCount = writeCount;
|
||||
if (totalCount == 0) {
|
||||
totalCount = writeCount;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
totalCount += writeCount;
|
||||
}
|
||||
if (!hasRemain) break;
|
||||
if (!hasRemain) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (writeOver && (totalCount != 0 || !hasRemain)) {
|
||||
@@ -497,7 +507,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
public synchronized int read() throws IOException {
|
||||
if (bb == null || !bb.hasRemaining()) {
|
||||
int r = readBuffer();
|
||||
if (r < 1) return -1;
|
||||
if (r < 1) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return bb.get() & 0xff;
|
||||
}
|
||||
@@ -513,7 +525,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
}
|
||||
if (bb == null || !bb.hasRemaining()) {
|
||||
int r = readBuffer();
|
||||
if (r < 1) return -1;
|
||||
if (r < 1) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
int size = Math.min(b.length, Math.min(len, bb.remaining()));
|
||||
bb.get(b, off, size);
|
||||
@@ -531,7 +545,9 @@ abstract class AsyncNioConnection extends AsyncConnection {
|
||||
|
||||
@Override
|
||||
public int available() throws IOException {
|
||||
if (bb == null || !bb.hasRemaining()) return 0;
|
||||
if (bb == null || !bb.hasRemaining()) {
|
||||
return 0;
|
||||
}
|
||||
return bb.remaining();
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user