diff --git a/src/main/java/org/redkale/boot/Application.java b/src/main/java/org/redkale/boot/Application.java index 02800f4c3..8c789db16 100644 --- a/src/main/java/org/redkale/boot/Application.java +++ b/src/main/java/org/redkale/boot/Application.java @@ -359,7 +359,9 @@ public final class Application { List 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 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 names = new HashSet<>(); @@ -1500,12 +1590,16 @@ public final class Application { Map 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> 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 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 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 singleton(String name, Class serviceClass, Class... 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 events) { - if (events == null || events.isEmpty()) return; + if (events == null || events.isEmpty()) { + return; + } synchronized (envProperties) { Properties envRegisterProps = new Properties(); Set 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 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 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 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 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 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 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); } diff --git a/src/main/java/org/redkale/boot/LoggingFileHandler.java b/src/main/java/org/redkale/boot/LoggingFileHandler.java index 3a895a7fa..ec1c9ab83 100644 --- a/src/main/java/org/redkale/boot/LoggingFileHandler.java +++ b/src/main/java/org/redkale/boot/LoggingFileHandler.java @@ -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); + } } } diff --git a/src/main/java/org/redkale/boot/NodeHttpServer.java b/src/main/java/org/redkale/boot/NodeHttpServer.java index 8446fe3bb..226494c1d 100644 --- a/src/main/java/org/redkale/boot/NodeHttpServer.java +++ b/src/main/java/org/redkale/boot/NodeHttpServer.java @@ -90,13 +90,17 @@ public class NodeHttpServer extends NodeServer { @Override protected void loadFilter(ClassFilter filterFilter, ClassFilter otherFilter) throws Exception { - if (httpServer != null) loadHttpFilter(filterFilter); + if (httpServer != null) { + loadHttpFilter(filterFilter); + } } @Override @SuppressWarnings("unchecked") protected void loadServlet(ClassFilter 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> list = new ArrayList(classFilter.getFilterEntrys()); for (FilterEntry en : list) { Class clazz = (Class) 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> list = new ArrayList(servletFilter.getFilterEntrys()); list.sort((FilterEntry o1, FilterEntry o2) -> { //必须保证WebSocketServlet优先加载, 因为要确保其他的HttpServlet可以注入本地模式的WebSocketNode @@ -196,10 +218,16 @@ public class NodeHttpServer extends NodeServer { final List> ss = sb == null ? null : new ArrayList<>(); for (FilterEntry en : list) { Class clazz = (Class) 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 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 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 o1, AbstractMap.SimpleEntry o2) -> o1.getKey().compareTo(o2.getKey())); for (AbstractMap.SimpleEntry as : ss) { - if (as.getKey().length() > max) max = as.getKey().length(); + if (as.getKey().length() > max) { + max = as.getKey().length(); + } } for (AbstractMap.SimpleEntry 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 webSocketFilter, final AnyValue restConf, final List restedObjects, final StringBuilder sb, final List> rests, final List> 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 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 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<>()); } } diff --git a/src/main/java/org/redkale/boot/NodeServer.java b/src/main/java/org/redkale/boot/NodeServer.java index d2b6044b6..c586b907f 100644 --- a/src/main/java/org/redkale/boot/NodeServer.java +++ b/src/main/java/org/redkale/boot/NodeServer.java @@ -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 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 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 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 serviceFilter, ClassFilter otherFilter) throws Exception { - if (serviceFilter == null) return; + if (serviceFilter == null) { + return; + } final long starts = System.currentTimeMillis(); final Set> 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 entry : entrys) { //service实现类 final Class 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(" value cannot contains '$' in " + entry.getProperty()); } - if (entry.getName().contains("$")) throw new RuntimeException(" 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 groups = entry.getGroups(); //groups.isEmpty()表示没有配置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)) { // 节点 @@ -650,7 +752,9 @@ public abstract class NodeServer { final AnyValue.Entry[] anys = av.getAnyEntrys(); if (anys != null) { for (AnyValue.Entry en : anys) { //将节点的非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; } diff --git a/src/main/java/org/redkale/boot/NodeSncpServer.java b/src/main/java/org/redkale/boot/NodeSncpServer.java index eb53b398b..a4f625b0d 100644 --- a/src/main/java/org/redkale/boot/NodeSncpServer.java +++ b/src/main/java/org/redkale/boot/NodeSncpServer.java @@ -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 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 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> list = new ArrayList(classFilter.getFilterEntrys()); for (FilterEntry en : list) { Class clazz = (Class) 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 diff --git a/src/main/java/org/redkale/boot/PrepareCompiler.java b/src/main/java/org/redkale/boot/PrepareCompiler.java index 1581a29f8..32320a046 100644 --- a/src/main/java/org/redkale/boot/PrepareCompiler.java +++ b/src/main/java/org/redkale/boot/PrepareCompiler.java @@ -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) { diff --git a/src/main/java/org/redkale/boot/watch/FilterWatchService.java b/src/main/java/org/redkale/boot/watch/FilterWatchService.java index 837b9a271..3b33f0c72 100644 --- a/src/main/java/org/redkale/boot/watch/FilterWatchService.java +++ b/src/main/java/org/redkale/boot/watch/FilterWatchService.java @@ -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 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(); } diff --git a/src/main/java/org/redkale/boot/watch/ServerWatchService.java b/src/main/java/org/redkale/boot/watch/ServerWatchService.java index e395a0b79..421c2bee4 100644 --- a/src/main/java/org/redkale/boot/watch/ServerWatchService.java +++ b/src/main/java/org/redkale/boot/watch/ServerWatchService.java @@ -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 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 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 { diff --git a/src/main/java/org/redkale/boot/watch/ServiceWatchService.java b/src/main/java/org/redkale/boot/watch/ServiceWatchService.java index 725799adb..f250adaee 100644 --- a/src/main/java/org/redkale/boot/watch/ServiceWatchService.java +++ b/src/main/java/org/redkale/boot/watch/ServiceWatchService.java @@ -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; /** *

@@ -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 params, @RestParam(name = "paramtypes", comment = "方法的参数数据类型") List 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; } diff --git a/src/main/java/org/redkale/boot/watch/TransportWatchService.java b/src/main/java/org/redkale/boot/watch/TransportWatchService.java index 6ba1d082a..3fde080f8 100644 --- a/src/main/java/org/redkale/boot/watch/TransportWatchService.java +++ b/src/main/java/org/redkale/boot/watch/TransportWatchService.java @@ -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)) { diff --git a/src/main/java/org/redkale/cluster/CacheClusterAgent.java b/src/main/java/org/redkale/cluster/CacheClusterAgent.java index f97513bb2..fd24ae598 100644 --- a/src/main/java/org/redkale/cluster/CacheClusterAgent.java +++ b/src/main/java/org/redkale/cluster/CacheClusterAgent.java @@ -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> queryHttpAddress(String protocol, String module, String resname) { final String serviceName = generateHttpServiceName(protocol, module, resname); Collection 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 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); } diff --git a/src/main/java/org/redkale/cluster/ClusterAgent.java b/src/main/java/org/redkale/cluster/ClusterAgent.java index fbefaf3b0..3e190eabd 100644 --- a/src/main/java/org/redkale/cluster/ClusterAgent.java +++ b/src/main/java/org/redkale/cluster/ClusterAgent.java @@ -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 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 localServices, Set 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 localServices, Set 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 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)); } diff --git a/src/main/java/org/redkale/convert/AnyDecoder.java b/src/main/java/org/redkale/convert/AnyDecoder.java index 5b9fc7d6b..b6bf1ad94 100644 --- a/src/main/java/org/redkale/convert/AnyDecoder.java +++ b/src/main/java/org/redkale/convert/AnyDecoder.java @@ -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.*; /** * 对不明类型的对象进行反序列化。
@@ -51,7 +51,9 @@ public class AnyDecoder implements Decodeable { @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); diff --git a/src/main/java/org/redkale/convert/AnyEncoder.java b/src/main/java/org/redkale/convert/AnyEncoder.java index 57066bfca..342c2d8c6 100644 --- a/src/main/java/org/redkale/convert/AnyEncoder.java +++ b/src/main/java/org/redkale/convert/AnyEncoder.java @@ -36,7 +36,9 @@ public final class AnyEncoder implements Encodeable { 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); } } diff --git a/src/main/java/org/redkale/convert/ArrayDecoder.java b/src/main/java/org/redkale/convert/ArrayDecoder.java index de1883099..1437e4ac1 100644 --- a/src/main/java/org/redkale/convert/ArrayDecoder.java +++ b/src/main/java/org/redkale/convert/ArrayDecoder.java @@ -74,7 +74,9 @@ public class ArrayDecoder implements Decodeable { 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 implements Decodeable { 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 implements Decodeable { } protected T readMemberValue(Reader in, DeMember member, Decodeable decoder, boolean first) { - if (in == null) return null; + if (in == null) { + return null; + } return decoder.convertFrom(in); } diff --git a/src/main/java/org/redkale/convert/CollectionDecoder.java b/src/main/java/org/redkale/convert/CollectionDecoder.java index a67feccdd..86eba87f2 100644 --- a/src/main/java/org/redkale/convert/CollectionDecoder.java +++ b/src/main/java/org/redkale/convert/CollectionDecoder.java @@ -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的反序列化操作类
@@ -80,7 +79,9 @@ public class CollectionDecoder implements Decodeable> { 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 implements Decodeable> { 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 implements Decodeable> { } protected T readMemberValue(Reader in, DeMember member, Decodeable decoder, boolean first) { - if (in == null) return null; + if (in == null) { + return null; + } return decoder.convertFrom(in); } diff --git a/src/main/java/org/redkale/convert/CollectionEncoder.java b/src/main/java/org/redkale/convert/CollectionEncoder.java index 02469ef2b..e70ed8955 100644 --- a/src/main/java/org/redkale/convert/CollectionEncoder.java +++ b/src/main/java/org/redkale/convert/CollectionEncoder.java @@ -79,9 +79,13 @@ public class CollectionEncoder implements Encodeable> { 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(); diff --git a/src/main/java/org/redkale/convert/DeMember.java b/src/main/java/org/redkale/convert/DeMember.java index 23b73b91d..59dc06dd0 100644 --- a/src/main/java/org/redkale/convert/DeMember.java +++ b/src/main/java/org/redkale/convert/DeMember.java @@ -156,17 +156,29 @@ public final class DeMember { } public int compareTo(boolean fieldSort, DeMember 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; } diff --git a/src/main/java/org/redkale/convert/EnMember.java b/src/main/java/org/redkale/convert/EnMember.java index c1a7e6378..ceafb02d1 100644 --- a/src/main/java/org/redkale/convert/EnMember.java +++ b/src/main/java/org/redkale/convert/EnMember.java @@ -175,17 +175,29 @@ public final class EnMember { } public int compareTo(boolean fieldSort, EnMember 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; } diff --git a/src/main/java/org/redkale/convert/MapDecoder.java b/src/main/java/org/redkale/convert/MapDecoder.java index bef9269f8..07ecd1e51 100644 --- a/src/main/java/org/redkale/convert/MapDecoder.java +++ b/src/main/java/org/redkale/convert/MapDecoder.java @@ -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的反序列化操作类
@@ -108,7 +107,9 @@ public class MapDecoder implements Decodeable> { 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 implements Decodeable> { 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); diff --git a/src/main/java/org/redkale/convert/MapEncoder.java b/src/main/java/org/redkale/convert/MapEncoder.java index c80e1d31c..d0aaaf420 100644 --- a/src/main/java/org/redkale/convert/MapEncoder.java +++ b/src/main/java/org/redkale/convert/MapEncoder.java @@ -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 implements Encodeable> { if (out.writeMapB(values.size(), (Encodeable) keyEncoder, (Encodeable) valueEncoder, value) < 0) { boolean first = true; for (Map.Entry 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(); diff --git a/src/main/java/org/redkale/convert/ObjectDecoder.java b/src/main/java/org/redkale/convert/ObjectDecoder.java index 4de8bb585..9836be1b8 100644 --- a/src/main/java/org/redkale/convert/ObjectDecoder.java +++ b/src/main/java/org/redkale/convert/ObjectDecoder.java @@ -89,7 +89,9 @@ public class ObjectDecoder implements Decodeable { } 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 list = new LinkedHashSet(); final String[] cps = ObjectEncoder.findConstructorProperties(this.creator); @@ -98,10 +100,16 @@ public class ObjectDecoder implements Decodeable { 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 fieldCoder; @@ -115,25 +123,45 @@ public class ObjectDecoder implements Decodeable { 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 implements Decodeable { 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 implements Decodeable { 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 implements Decodeable { break; } } - if (flag) continue; + if (flag) { + continue; + } //不存在setter方法 try { Field f = clazz.getDeclaredField(constructorField); @@ -212,7 +250,9 @@ public class ObjectDecoder implements Decodeable { Collections.sort(sorts, (a, b) -> a.compareTo(factory.isFieldSort(), b)); Set 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 implements Decodeable { 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 implements Decodeable { 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]); diff --git a/src/main/java/org/redkale/convert/ObjectEncoder.java b/src/main/java/org/redkale/convert/ObjectEncoder.java index ef66d86f8..d9e7d74a5 100644 --- a/src/main/java/org/redkale/convert/ObjectEncoder.java +++ b/src/main/java/org/redkale/convert/ObjectEncoder.java @@ -60,7 +60,9 @@ public class ObjectEncoder implements Encodeable { 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 list = new LinkedHashSet(); @@ -69,7 +71,9 @@ public class ObjectEncoder implements Encodeable { 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 implements Encodeable { 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 fieldCoder; @@ -94,22 +104,40 @@ public class ObjectEncoder implements Encodeable { 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 implements Encodeable { } } 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 implements Encodeable { 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 sorts = new ArrayList<>(list); @@ -159,7 +193,9 @@ public class ObjectEncoder implements Encodeable { break; } } - if (flag) continue; + if (flag) { + continue; + } //不存在setter方法 try { Field f = clazz.getDeclaredField(constructorField); @@ -185,12 +221,16 @@ public class ObjectEncoder implements Encodeable { } } } - 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 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 implements Encodeable { } 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 implements Encodeable { if (extFields != null) { Encodeable 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 implements Encodeable { 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); diff --git a/src/main/java/org/redkale/convert/StreamEncoder.java b/src/main/java/org/redkale/convert/StreamEncoder.java index 7a16c543b..b2c707ea8 100644 --- a/src/main/java/org/redkale/convert/StreamEncoder.java +++ b/src/main/java/org/redkale/convert/StreamEncoder.java @@ -80,9 +80,13 @@ public class StreamEncoder implements Encodeable> { 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(); diff --git a/src/main/java/org/redkale/convert/bson/BsonByteBufferReader.java b/src/main/java/org/redkale/convert/bson/BsonByteBufferReader.java index 77bdfe3b9..db9ef7896 100644 --- a/src/main/java/org/redkale/convert/bson/BsonByteBufferReader.java +++ b/src/main/java/org/redkale/convert/bson/BsonByteBufferReader.java @@ -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); } } diff --git a/src/main/java/org/redkale/convert/bson/BsonByteBufferWriter.java b/src/main/java/org/redkale/convert/bson/BsonByteBufferWriter.java index 2058e92ed..49a523a38 100644 --- a/src/main/java/org/redkale/convert/bson/BsonByteBufferWriter.java +++ b/src/main/java/org/redkale/convert/bson/BsonByteBufferWriter.java @@ -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()) { diff --git a/src/main/java/org/redkale/convert/bson/BsonConvert.java b/src/main/java/org/redkale/convert/bson/BsonConvert.java index ebd057136..2e0a31235 100644 --- a/src/main/java/org/redkale/convert/bson/BsonConvert.java +++ b/src/main/java/org/redkale/convert/bson/BsonConvert.java @@ -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 { //------------------------------ convertFrom ----------------------------------------------------------- @Override public 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 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 { @SuppressWarnings("unchecked") public 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 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 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 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 { @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 { } 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 { @Override public ByteBuffer[] convertTo(final Supplier 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 { @Override public ByteBuffer[] convertTo(final Supplier 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 { @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; diff --git a/src/main/java/org/redkale/convert/bson/BsonFactory.java b/src/main/java/org/redkale/convert/bson/BsonFactory.java index 6b13638ae..e9c01bdd9 100644 --- a/src/main/java/org/redkale/convert/bson/BsonFactory.java +++ b/src/main/java/org/redkale/convert/bson/BsonFactory.java @@ -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 { @Override public final BsonConvert getConvert() { - if (convert == null) convert = new BsonConvert(this, tiny); + if (convert == null) { + convert = new BsonConvert(this, tiny); + } return (BsonConvert) convert; } diff --git a/src/main/java/org/redkale/convert/bson/BsonReader.java b/src/main/java/org/redkale/convert/bson/BsonReader.java index 7532217aa..11940d346 100644 --- a/src/main/java/org/redkale/convert/bson/BsonReader.java +++ b/src/main/java/org/redkale/convert/bson/BsonReader.java @@ -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; diff --git a/src/main/java/org/redkale/convert/bson/BsonStreamWriter.java b/src/main/java/org/redkale/convert/bson/BsonStreamWriter.java index 35b828d13..81c1da233 100644 --- a/src/main/java/org/redkale/convert/bson/BsonStreamWriter.java +++ b/src/main/java/org/redkale/convert/bson/BsonStreamWriter.java @@ -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 diff --git a/src/main/java/org/redkale/convert/bson/BsonWriter.java b/src/main/java/org/redkale/convert/bson/BsonWriter.java index 53f3c1dba..df901caad 100644 --- a/src/main/java/org/redkale/convert/bson/BsonWriter.java +++ b/src/main/java/org/redkale/convert/bson/BsonWriter.java @@ -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); diff --git a/src/main/java/org/redkale/convert/bson/SkipArrayDecoder.java b/src/main/java/org/redkale/convert/bson/SkipArrayDecoder.java index 5efe46d80..e9fc3a0a4 100644 --- a/src/main/java/org/redkale/convert/bson/SkipArrayDecoder.java +++ b/src/main/java/org/redkale/convert/bson/SkipArrayDecoder.java @@ -27,7 +27,9 @@ public class SkipArrayDecoder extends ArrayDecoder { @Override protected Decodeable getComponentDecoder(Decodeable decoder, byte[] typevals) { - if (typevals != null) return BsonFactory.typeEnum(typevals[0]); + if (typevals != null) { + return BsonFactory.typeEnum(typevals[0]); + } return decoder; } } diff --git a/src/main/java/org/redkale/convert/bson/SkipCollectionDecoder.java b/src/main/java/org/redkale/convert/bson/SkipCollectionDecoder.java index 0b74fe110..2cd129b68 100644 --- a/src/main/java/org/redkale/convert/bson/SkipCollectionDecoder.java +++ b/src/main/java/org/redkale/convert/bson/SkipCollectionDecoder.java @@ -26,7 +26,9 @@ public class SkipCollectionDecoder extends CollectionDecoder { @Override protected Decodeable getComponentDecoder(Decodeable decoder, byte[] typevals) { - if (typevals != null) return BsonFactory.typeEnum(typevals[0]); + if (typevals != null) { + return BsonFactory.typeEnum(typevals[0]); + } return decoder; } } diff --git a/src/main/java/org/redkale/convert/bson/SkipMapDecoder.java b/src/main/java/org/redkale/convert/bson/SkipMapDecoder.java index a0b352849..7c3526576 100644 --- a/src/main/java/org/redkale/convert/bson/SkipMapDecoder.java +++ b/src/main/java/org/redkale/convert/bson/SkipMapDecoder.java @@ -26,13 +26,17 @@ public class SkipMapDecoder extends MapDecoder { @Override protected Decodeable getKeyDecoder(Decodeable decoder, byte[] typevals) { - if (typevals != null) return BsonFactory.typeEnum(typevals[0]); + if (typevals != null) { + return BsonFactory.typeEnum(typevals[0]); + } return decoder; } @Override protected Decodeable getValueDecoder(Decodeable decoder, byte[] typevals) { - if (typevals != null) return BsonFactory.typeEnum(typevals[1]); + if (typevals != null) { + return BsonFactory.typeEnum(typevals[1]); + } return decoder; } } diff --git a/src/main/java/org/redkale/convert/bson/SkipStreamDecoder.java b/src/main/java/org/redkale/convert/bson/SkipStreamDecoder.java index 8a42ace7f..fe373c89e 100644 --- a/src/main/java/org/redkale/convert/bson/SkipStreamDecoder.java +++ b/src/main/java/org/redkale/convert/bson/SkipStreamDecoder.java @@ -26,7 +26,9 @@ public class SkipStreamDecoder extends StreamDecoder { @Override protected Decodeable getComponentDecoder(Decodeable decoder, byte[] typevals) { - if (typevals != null) return BsonFactory.typeEnum(typevals[0]); + if (typevals != null) { + return BsonFactory.typeEnum(typevals[0]); + } return decoder; } } diff --git a/src/main/java/org/redkale/convert/ext/BigDecimalSimpledCoder.java b/src/main/java/org/redkale/convert/ext/BigDecimalSimpledCoder.java index 73404f32a..71967691e 100644 --- a/src/main/java/org/redkale/convert/ext/BigDecimalSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/BigDecimalSimpledCoder.java @@ -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 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 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); } } diff --git a/src/main/java/org/redkale/convert/ext/BigIntegerSimpledCoder.java b/src/main/java/org/redkale/convert/ext/BigIntegerSimpledCoder.java index 404cf675a..b31fa80c6 100644 --- a/src/main/java/org/redkale/convert/ext/BigIntegerSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/BigIntegerSimpledCoder.java @@ -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 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 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); diff --git a/src/main/java/org/redkale/convert/ext/BoolArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/BoolArraySimpledCoder.java index bf0ad401d..97df870e8 100644 --- a/src/main/java/org/redkale/convert/ext/BoolArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/BoolArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/BoolSimpledCoder.java b/src/main/java/org/redkale/convert/ext/BoolSimpledCoder.java index fe61d083f..65f72c20a 100644 --- a/src/main/java/org/redkale/convert/ext/BoolSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/BoolSimpledCoder.java @@ -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实现 - * + * *

* 详情见: https://redkale.org * diff --git a/src/main/java/org/redkale/convert/ext/ByteBufferSimpledCoder.java b/src/main/java/org/redkale/convert/ext/ByteBufferSimpledCoder.java index 0d7583664..89f609f7e 100644 --- a/src/main/java/org/redkale/convert/ext/ByteBufferSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/ByteBufferSimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/ByteSimpledCoder.java b/src/main/java/org/redkale/convert/ext/ByteSimpledCoder.java index ff630f072..6d32820d9 100644 --- a/src/main/java/org/redkale/convert/ext/ByteSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/ByteSimpledCoder.java @@ -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实现 - * + * *

* 详情见: https://redkale.org * diff --git a/src/main/java/org/redkale/convert/ext/CharArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/CharArraySimpledCoder.java index 1199ccde8..30caf98b8 100644 --- a/src/main/java/org/redkale/convert/ext/CharArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/CharArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/CharSimpledCoder.java b/src/main/java/org/redkale/convert/ext/CharSimpledCoder.java index 8c25c5a35..005c91a57 100644 --- a/src/main/java/org/redkale/convert/ext/CharSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/CharSimpledCoder.java @@ -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实现 * - *

详情见: https://redkale.org + *

+ * 详情见: https://redkale.org + * * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 diff --git a/src/main/java/org/redkale/convert/ext/DLongSimpledCoder.java b/src/main/java/org/redkale/convert/ext/DLongSimpledCoder.java index c1d881086..cd344307f 100644 --- a/src/main/java/org/redkale/convert/ext/DLongSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/DLongSimpledCoder.java @@ -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 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 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)); } } diff --git a/src/main/java/org/redkale/convert/ext/DoubleArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/DoubleArraySimpledCoder.java index c5db2c821..69e0f790e 100644 --- a/src/main/java/org/redkale/convert/ext/DoubleArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/DoubleArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/DoubleSimpledCoder.java b/src/main/java/org/redkale/convert/ext/DoubleSimpledCoder.java index 0b0a6fc6a..5b0648d3e 100644 --- a/src/main/java/org/redkale/convert/ext/DoubleSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/DoubleSimpledCoder.java @@ -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实现 * - *

详情见: https://redkale.org + *

+ * 详情见: https://redkale.org + * * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 diff --git a/src/main/java/org/redkale/convert/ext/DurationSimpledCoder.java b/src/main/java/org/redkale/convert/ext/DurationSimpledCoder.java index 631d41965..b22391988 100644 --- a/src/main/java/org/redkale/convert/ext/DurationSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/DurationSimpledCoder.java @@ -34,7 +34,9 @@ public class DurationSimpledCoder 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)); } diff --git a/src/main/java/org/redkale/convert/ext/EnumSimpledCoder.java b/src/main/java/org/redkale/convert/ext/EnumSimpledCoder.java index 3df9ebf7a..24dd3d80c 100644 --- a/src/main/java/org/redkale/convert/ext/EnumSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/EnumSimpledCoder.java @@ -76,7 +76,9 @@ public final class EnumSimpledCoder 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); } diff --git a/src/main/java/org/redkale/convert/ext/FloatArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/FloatArraySimpledCoder.java index b7892a0ae..0dde51cf2 100644 --- a/src/main/java/org/redkale/convert/ext/FloatArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/FloatArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/FloatSimpledCoder.java b/src/main/java/org/redkale/convert/ext/FloatSimpledCoder.java index 9169a2258..9c56c3e1b 100644 --- a/src/main/java/org/redkale/convert/ext/FloatSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/FloatSimpledCoder.java @@ -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实现 * - *

详情见: https://redkale.org + *

+ * 详情见: https://redkale.org + * * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 diff --git a/src/main/java/org/redkale/convert/ext/InetAddressSimpledCoder.java b/src/main/java/org/redkale/convert/ext/InetAddressSimpledCoder.java index d53b43a0c..a85531045 100644 --- a/src/main/java/org/redkale/convert/ext/InetAddressSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/InetAddressSimpledCoder.java @@ -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 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 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 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 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))); diff --git a/src/main/java/org/redkale/convert/ext/InstantSimpledCoder.java b/src/main/java/org/redkale/convert/ext/InstantSimpledCoder.java index 14f072600..3c7cdfa53 100644 --- a/src/main/java/org/redkale/convert/ext/InstantSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/InstantSimpledCoder.java @@ -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 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); } } diff --git a/src/main/java/org/redkale/convert/ext/IntArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/IntArraySimpledCoder.java index d3820dbc5..11dad402c 100644 --- a/src/main/java/org/redkale/convert/ext/IntArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/IntArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/IntSimpledCoder.java b/src/main/java/org/redkale/convert/ext/IntSimpledCoder.java index de0e8e19a..b5870cc8d 100644 --- a/src/main/java/org/redkale/convert/ext/IntSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/IntSimpledCoder.java @@ -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 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 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); diff --git a/src/main/java/org/redkale/convert/ext/LocalDateSimpledCoder.java b/src/main/java/org/redkale/convert/ext/LocalDateSimpledCoder.java index 7537d5f86..b13824f30 100644 --- a/src/main/java/org/redkale/convert/ext/LocalDateSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/LocalDateSimpledCoder.java @@ -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 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 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); } } diff --git a/src/main/java/org/redkale/convert/ext/LocalDateTimeSimpledCoder.java b/src/main/java/org/redkale/convert/ext/LocalDateTimeSimpledCoder.java index 12a54be2b..18f595982 100644 --- a/src/main/java/org/redkale/convert/ext/LocalDateTimeSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/LocalDateTimeSimpledCoder.java @@ -42,7 +42,9 @@ public final class LocalDateTimeSimpledCoder @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 @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); } } diff --git a/src/main/java/org/redkale/convert/ext/LocalTimeSimpledCoder.java b/src/main/java/org/redkale/convert/ext/LocalTimeSimpledCoder.java index 06f72ab6f..24ba5b5e4 100644 --- a/src/main/java/org/redkale/convert/ext/LocalTimeSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/LocalTimeSimpledCoder.java @@ -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 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); } } diff --git a/src/main/java/org/redkale/convert/ext/LongArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/LongArraySimpledCoder.java index 33a91961d..2437c6978 100644 --- a/src/main/java/org/redkale/convert/ext/LongArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/LongArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/LongSimpledCoder.java b/src/main/java/org/redkale/convert/ext/LongSimpledCoder.java index 91da6b495..b3157fb6f 100644 --- a/src/main/java/org/redkale/convert/ext/LongSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/LongSimpledCoder.java @@ -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 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 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); diff --git a/src/main/java/org/redkale/convert/ext/PatternSimpledCoder.java b/src/main/java/org/redkale/convert/ext/PatternSimpledCoder.java index 9d6daa5e2..246634af5 100644 --- a/src/main/java/org/redkale/convert/ext/PatternSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/PatternSimpledCoder.java @@ -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实现 + * + *

+ * 详情见: https://redkale.org * - *

详情见: https://redkale.org * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 @@ -32,7 +34,9 @@ public class PatternSimpledCoder 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))); } diff --git a/src/main/java/org/redkale/convert/ext/ShortArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/ShortArraySimpledCoder.java index 9f2fda2b4..95342bccc 100644 --- a/src/main/java/org/redkale/convert/ext/ShortArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/ShortArraySimpledCoder.java @@ -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 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 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; diff --git a/src/main/java/org/redkale/convert/ext/ShortSimpledCoder.java b/src/main/java/org/redkale/convert/ext/ShortSimpledCoder.java index 7df06aa64..14c6a4715 100644 --- a/src/main/java/org/redkale/convert/ext/ShortSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/ShortSimpledCoder.java @@ -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实现 * - *

详情见: https://redkale.org + *

+ * 详情见: https://redkale.org + * * @author zhangjx * @param Reader输入的子类型 * @param Writer输出的子类型 diff --git a/src/main/java/org/redkale/convert/ext/StringArraySimpledCoder.java b/src/main/java/org/redkale/convert/ext/StringArraySimpledCoder.java index 23ba5382a..cfc9ac4f4 100644 --- a/src/main/java/org/redkale/convert/ext/StringArraySimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/StringArraySimpledCoder.java @@ -30,7 +30,9 @@ public final class StringArraySimpledCoder 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 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; diff --git a/src/main/java/org/redkale/convert/ext/ThrowableSimpledCoder.java b/src/main/java/org/redkale/convert/ext/ThrowableSimpledCoder.java index 1c872bcfb..deeb54946 100644 --- a/src/main/java/org/redkale/convert/ext/ThrowableSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/ThrowableSimpledCoder.java @@ -33,7 +33,9 @@ public class ThrowableSimpledCoder 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); } diff --git a/src/main/java/org/redkale/convert/ext/TypeSimpledCoder.java b/src/main/java/org/redkale/convert/ext/TypeSimpledCoder.java index 70257d4ac..baa3e483c 100644 --- a/src/main/java/org/redkale/convert/ext/TypeSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/TypeSimpledCoder.java @@ -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 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) { diff --git a/src/main/java/org/redkale/convert/ext/URISimpledCoder.java b/src/main/java/org/redkale/convert/ext/URISimpledCoder.java index 1376d2b5c..315a7ce24 100644 --- a/src/main/java/org/redkale/convert/ext/URISimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/URISimpledCoder.java @@ -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 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) { diff --git a/src/main/java/org/redkale/convert/ext/URLSimpledCoder.java b/src/main/java/org/redkale/convert/ext/URLSimpledCoder.java index 172f2733c..0cc352b2d 100644 --- a/src/main/java/org/redkale/convert/ext/URLSimpledCoder.java +++ b/src/main/java/org/redkale/convert/ext/URLSimpledCoder.java @@ -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 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) { diff --git a/src/main/java/org/redkale/convert/json/JsonByteBufferReader.java b/src/main/java/org/redkale/convert/json/JsonByteBufferReader.java index 6561768fc..45e18acc3 100644 --- a/src/main/java/org/redkale/convert/json/JsonByteBufferReader.java +++ b/src/main/java/org/redkale/convert/json/JsonByteBufferReader.java @@ -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; diff --git a/src/main/java/org/redkale/convert/json/JsonByteBufferWriter.java b/src/main/java/org/redkale/convert/json/JsonByteBufferWriter.java index 0e21596b8..21da23b67 100644 --- a/src/main/java/org/redkale/convert/json/JsonByteBufferWriter.java +++ b/src/main/java/org/redkale/convert/json/JsonByteBufferWriter.java @@ -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; } } diff --git a/src/main/java/org/redkale/convert/json/JsonBytesWriter.java b/src/main/java/org/redkale/convert/json/JsonBytesWriter.java index fd6a3ee50..87e76236c 100644 --- a/src/main/java/org/redkale/convert/json/JsonBytesWriter.java +++ b/src/main/java/org/redkale/convert/json/JsonBytesWriter.java @@ -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; } diff --git a/src/main/java/org/redkale/convert/json/JsonCharsWriter.java b/src/main/java/org/redkale/convert/json/JsonCharsWriter.java index 800f140ed..c90a9f7b4 100644 --- a/src/main/java/org/redkale/convert/json/JsonCharsWriter.java +++ b/src/main/java/org/redkale/convert/json/JsonCharsWriter.java @@ -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; } diff --git a/src/main/java/org/redkale/convert/json/JsonConvert.java b/src/main/java/org/redkale/convert/json/JsonConvert.java index 5453841b5..168e2b98f 100644 --- a/src/main/java/org/redkale/convert/json/JsonConvert.java +++ b/src/main/java/org/redkale/convert/json/JsonConvert.java @@ -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 { //------------------------------ convertFrom ----------------------------------------------------------- @Override public 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 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 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 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 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 { } public 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 { @Override public 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 { @Override public 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 { } public 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 { //返回非null的值是由String、ArrayList、HashMap任意组合的对象 public 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 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 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 { //返回非null的值是由String、ArrayList、HashMap任意组合的对象 public 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 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 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 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 { @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 { 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 { 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 { } 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 { 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 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 { @Override public ByteBuffer[] convertTo(final Supplier 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 { 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 { encoder = factory.loadEncoder(type); this.lastConvertEncodeable = encoder; } - if (encoder.specifyable()) writer.specify(type); + if (encoder.specifyable()) { + writer.specify(type); + } encoder.convertTo(writer, value); } } diff --git a/src/main/java/org/redkale/convert/json/JsonDynEncoder.java b/src/main/java/org/redkale/convert/json/JsonDynEncoder.java index 2d078fb64..33832efd3 100644 --- a/src/main/java/org/redkale/convert/json/JsonDynEncoder.java +++ b/src/main/java/org/redkale/convert/json/JsonDynEncoder.java @@ -45,35 +45,79 @@ public abstract class JsonDynEncoder implements Encodeable { } 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 implements Encodeable { //字段全部是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 members = null; @@ -111,52 +193,100 @@ public abstract class JsonDynEncoder implements Encodeable { 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 implements Encodeable { } 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 implements Encodeable { } 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 implements Encodeable { protected static JsonDynEncoder generateDyncEncoder(final JsonFactory factory, final Class clazz, final List 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 implements Encodeable { 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 implements Encodeable { 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, "", "(" + jsonfactoryDesc + typeDesc + ")V", null, null)); //mv.setDebug(true); diff --git a/src/main/java/org/redkale/convert/json/JsonFactory.java b/src/main/java/org/redkale/convert/json/JsonFactory.java index 6b2ac8023..1e05c70f1 100644 --- a/src/main/java/org/redkale/convert/json/JsonFactory.java +++ b/src/main/java/org/redkale/convert/json/JsonFactory.java @@ -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 { @Override public final JsonConvert getConvert() { - if (convert == null) convert = new JsonConvert(this, tiny); + if (convert == null) { + convert = new JsonConvert(this, tiny); + } return (JsonConvert) convert; } diff --git a/src/main/java/org/redkale/convert/json/JsonMultiArrayDecoder.java b/src/main/java/org/redkale/convert/json/JsonMultiArrayDecoder.java index ce03aa798..7446b7995 100644 --- a/src/main/java/org/redkale/convert/json/JsonMultiArrayDecoder.java +++ b/src/main/java/org/redkale/convert/json/JsonMultiArrayDecoder.java @@ -41,7 +41,9 @@ public class JsonMultiArrayDecoder implements Decodeable { 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 result = new ArrayList(); int startPosition = in.position(); diff --git a/src/main/java/org/redkale/convert/json/JsonMultiImplDecoder.java b/src/main/java/org/redkale/convert/json/JsonMultiImplDecoder.java index dcfc05832..d30b0978a 100644 --- a/src/main/java/org/redkale/convert/json/JsonMultiImplDecoder.java +++ b/src/main/java/org/redkale/convert/json/JsonMultiImplDecoder.java @@ -68,13 +68,17 @@ public class JsonMultiImplDecoder implements Decodeable { 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 implements Decodeable { @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 uniques = this.uniqueFieldToDecoders; Map repeats = this.repeatFieldToDecoders; diff --git a/src/main/java/org/redkale/convert/json/JsonReader.java b/src/main/java/org/redkale/convert/json/JsonReader.java index 71cfdd1f0..1bf1228a1 100644 --- a/src/main/java/org/redkale/convert/json/JsonReader.java +++ b/src/main/java/org/redkale/convert/json/JsonReader.java @@ -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 memberFieldMap, Map 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); } diff --git a/src/main/java/org/redkale/convert/json/JsonStreamWriter.java b/src/main/java/org/redkale/convert/json/JsonStreamWriter.java index 40010235e..c2405609c 100644 --- a/src/main/java/org/redkale/convert/json/JsonStreamWriter.java +++ b/src/main/java/org/redkale/convert/json/JsonStreamWriter.java @@ -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); } diff --git a/src/main/java/org/redkale/convert/json/JsonWriter.java b/src/main/java/org/redkale/convert/json/JsonWriter.java index fd84788ab..ee3e47291 100644 --- a/src/main/java/org/redkale/convert/json/JsonWriter.java +++ b/src/main/java/org/redkale/convert/json/JsonWriter.java @@ -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; } diff --git a/src/main/java/org/redkale/mq/HttpMessageClient.java b/src/main/java/org/redkale/mq/HttpMessageClient.java index bf29d82fb..95e1e506c 100644 --- a/src/main/java/org/redkale/mq/HttpMessageClient.java +++ b/src/main/java/org/redkale/mq/HttpMessageClient.java @@ -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 headers = request.getHeaders(); @@ -122,21 +124,27 @@ public class HttpMessageClient extends MessageClient { public CompletableFuture sendMessage(HttpSimpleRequest request, Type type) { return sendMessage(generateHttpReqTopic(request, null), 0, null, request, null).thenApply((HttpResult 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 CompletableFuture sendMessage(Serializable userid, HttpSimpleRequest request, Type type) { return sendMessage(generateHttpReqTopic(request, null), userid, null, request, null).thenApply((HttpResult 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 CompletableFuture sendMessage(Serializable userid, String groupid, HttpSimpleRequest request, Type type) { return sendMessage(generateHttpReqTopic(request, null), userid, groupid, request, null).thenApply((HttpResult httbs) -> { - if (httbs == null || httbs.getResult() == null) return null; + if (httbs == null || httbs.getResult() == null) { + return null; + } return JsonConvert.root().convertFrom(type, httbs.getResult()); }); } diff --git a/src/main/java/org/redkale/mq/HttpMessageClusterClient.java b/src/main/java/org/redkale/mq/HttpMessageClusterClient.java index 73625f472..e12f337b2 100644 --- a/src/main/java/org/redkale/mq/HttpMessageClusterClient.java +++ b/src/main/java/org/redkale/mq/HttpMessageClusterClient.java @@ -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().status(404).toFuture(); } final Map 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 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> en : addrmap.entrySet()) { String realmodule = en.getKey(); Collection 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 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().status(404).toFuture(); } final Map 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> forEachCollectionFuture(boolean finest, Serializable userid, HttpSimpleRequest req, String requesturi, final Map clientHeaders, byte[] clientBody, Iterator 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 resp) -> { final int rs = resp.statusCode(); - if (rs != 200) return new HttpResult().status(rs); + if (rs != 200) { + return new HttpResult().status(rs); + } return new HttpResult(resp.body()); }); } diff --git a/src/main/java/org/redkale/mq/HttpMessageLocalClient.java b/src/main/java/org/redkale/mq/HttpMessageLocalClient.java index f49cd2400..a3aa025a0 100644 --- a/src/main/java/org/redkale/mq/HttpMessageLocalClient.java +++ b/src/main/java/org/redkale/mq/HttpMessageLocalClient.java @@ -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> 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(); diff --git a/src/main/java/org/redkale/mq/HttpMessageProcessor.java b/src/main/java/org/redkale/mq/HttpMessageProcessor.java index 94f211a67..c0868bc57 100644 --- a/src/main/java/org/redkale/mq/HttpMessageProcessor.java +++ b/src/main/java/org/redkale/mq/HttpMessageProcessor.java @@ -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; diff --git a/src/main/java/org/redkale/mq/HttpMessageResponse.java b/src/main/java/org/redkale/mq/HttpMessageResponse.java index 12b124a26..544361ff9 100644 --- a/src/main/java/org/redkale/mq/HttpMessageResponse.java +++ b/src/main/java/org/redkale/mq/HttpMessageResponse.java @@ -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 void finish(boolean kill, final String contentType, final byte[] bs, int offset, int length, Consumer 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; diff --git a/src/main/java/org/redkale/mq/HttpResultCoder.java b/src/main/java/org/redkale/mq/HttpResultCoder.java index a6464b5b9..90c42b5c6 100644 --- a/src/main/java/org/redkale/mq/HttpResultCoder.java +++ b/src/main/java/org/redkale/mq/HttpResultCoder.java @@ -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 { @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 { 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 { 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 { @Override public HttpResult 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 { } public static byte[] getBytes(final List 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 { public static List getCookieList(ByteBuffer buffer) { int len = buffer.getChar(); - if (len == 0) return null; + if (len == 0) { + return null; + } final List list = new ArrayList<>(len); for (int i = 0; i < len; i++) { HttpCookie cookie = new HttpCookie(getShortString(buffer), getShortString(buffer)); diff --git a/src/main/java/org/redkale/mq/HttpSimpleRequestCoder.java b/src/main/java/org/redkale/mq/HttpSimpleRequestCoder.java index d8d718ca7..1c3391d9b 100644 --- a/src/main/java/org/redkale/mq/HttpSimpleRequestCoder.java +++ b/src/main/java/org/redkale/mq/HttpSimpleRequestCoder.java @@ -60,29 +60,47 @@ public class HttpSimpleRequestCoder implements MessageCoder { 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 { 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 { 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); diff --git a/src/main/java/org/redkale/mq/MessageAgent.java b/src/main/java/org/redkale/mq/MessageAgent.java index 2feaec3c7..a004ea624 100644 --- a/src/main/java/org/redkale/mq/MessageAgent.java +++ b/src/main/java/org/redkale/mq/MessageAgent.java @@ -76,8 +76,12 @@ public abstract class MessageAgent implements Resourcable { Class> coderClass = (Class) Thread.currentThread().getContextClassLoader().loadClass(coderType); RedkaleClassLoader.putReflectionPublicConstructors(coderClass, coderClass.getName()); MessageCoder 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 getAllMessageConsumer() { List 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 getAllMessageProducer() { List 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))}; } diff --git a/src/main/java/org/redkale/mq/MessageClient.java b/src/main/java/org/redkale/mq/MessageClient.java index 41cb09784..d6745ff1a 100644 --- a/src/main/java/org/redkale/mq/MessageClient.java +++ b/src/main/java/org/redkale/mq/MessageClient.java @@ -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 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); diff --git a/src/main/java/org/redkale/mq/MessageCoder.java b/src/main/java/org/redkale/mq/MessageCoder.java index 7f34e65aa..a2687186e 100644 --- a/src/main/java/org/redkale/mq/MessageCoder.java +++ b/src/main/java/org/redkale/mq/MessageCoder.java @@ -35,7 +35,9 @@ public interface MessageCoder { //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 { (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 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 { 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 { 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 { public static Map getMap(ByteBuffer buffer) { int len = buffer.getChar(); - if (len == 0) return null; + if (len == 0) { + return null; + } Map map = new HashMap<>(len); for (int i = 0; i < len; i++) { map.put(getShortString(buffer), getLongString(buffer)); diff --git a/src/main/java/org/redkale/mq/MessageRecord.java b/src/main/java/org/redkale/mq/MessageRecord.java index 589c9a19b..aeae7deb8 100644 --- a/src/main/java/org/redkale/mq/MessageRecord.java +++ b/src/main/java/org/redkale/mq/MessageRecord.java @@ -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里面的数据结构

@@ -135,12 +135,16 @@ public class MessageRecord implements Serializable { } public 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 decodeContent(MessageCoder 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) { diff --git a/src/main/java/org/redkale/mq/MessageRecordCoder.java b/src/main/java/org/redkale/mq/MessageRecordCoder.java index ab4a02d9c..6eb336d0b 100644 --- a/src/main/java/org/redkale/mq/MessageRecordCoder.java +++ b/src/main/java/org/redkale/mq/MessageRecordCoder.java @@ -28,7 +28,9 @@ public class MessageRecordCoder implements MessageCoder { @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 { 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 { @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(); diff --git a/src/main/java/org/redkale/mq/SncpMessageClient.java b/src/main/java/org/redkale/mq/SncpMessageClient.java index 471961769..32bf5c580 100644 --- a/src/main/java/org/redkale/mq/SncpMessageClient.java +++ b/src/main/java/org/redkale/mq/SncpMessageClient.java @@ -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; } } diff --git a/src/main/java/org/redkale/mq/SncpMessageProcessor.java b/src/main/java/org/redkale/mq/SncpMessageProcessor.java index 8af83ebdb..576925155 100644 --- a/src/main/java/org/redkale/mq/SncpMessageProcessor.java +++ b/src/main/java/org/redkale/mq/SncpMessageProcessor.java @@ -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); } } diff --git a/src/main/java/org/redkale/mq/SncpMessageRequest.java b/src/main/java/org/redkale/mq/SncpMessageRequest.java index ffb07c16e..65b8a6cd1 100644 --- a/src/main/java/org/redkale/mq/SncpMessageRequest.java +++ b/src/main/java/org/redkale/mq/SncpMessageRequest.java @@ -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 { diff --git a/src/main/java/org/redkale/mq/SncpMessageResponse.java b/src/main/java/org/redkale/mq/SncpMessageResponse.java index 59e275841..34fbfe39b 100644 --- a/src/main/java/org/redkale/mq/SncpMessageResponse.java +++ b/src/main/java/org/redkale/mq/SncpMessageResponse.java @@ -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); diff --git a/src/main/java/org/redkale/net/AsyncConnection.java b/src/main/java/org/redkale/net/AsyncConnection.java index 9d8ed7439..97becb208 100644 --- a/src/main/java/org/redkale/net/AsyncConnection.java +++ b/src/main/java/org/redkale/net/AsyncConnection.java @@ -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 newhandler = new CompletionHandler() { @@ -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 newhandler = new CompletionHandler() { @@ -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 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 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 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; } diff --git a/src/main/java/org/redkale/net/AsyncIOGroup.java b/src/main/java/org/redkale/net/AsyncIOGroup.java index 8977879fb..e2ca8c1db 100644 --- a/src/main/java/org/redkale/net/AsyncIOGroup.java +++ b/src/main/java/org/redkale/net/AsyncIOGroup.java @@ -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 future = new CompletableFuture<>(); conn.connect(address, null, new CompletionHandler() { @@ -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() { diff --git a/src/main/java/org/redkale/net/AsyncIOThread.java b/src/main/java/org/redkale/net/AsyncIOThread.java index ca53574bf..0082d879d 100644 --- a/src/main/java/org/redkale/net/AsyncIOThread.java +++ b/src/main/java/org/redkale/net/AsyncIOThread.java @@ -69,7 +69,9 @@ public class AsyncIOThread extends AsyncThread { @Override public void execute(Collection 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 keys = selector.selectedKeys(); Iterator 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); + } } } } diff --git a/src/main/java/org/redkale/net/AsyncNioConnection.java b/src/main/java/org/redkale/net/AsyncNioConnection.java index e70953984..e080315c5 100644 --- a/src/main/java/org/redkale/net/AsyncNioConnection.java +++ b/src/main/java/org/redkale/net/AsyncNioConnection.java @@ -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(); } diff --git a/src/main/java/org/redkale/net/AsyncNioTcpConnection.java b/src/main/java/org/redkale/net/AsyncNioTcpConnection.java index aa58d9295..46d6ec573 100644 --- a/src/main/java/org/redkale/net/AsyncNioTcpConnection.java +++ b/src/main/java/org/redkale/net/AsyncNioTcpConnection.java @@ -5,11 +5,11 @@ */ 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.Set; import java.util.concurrent.atomic.LongAdder; import java.util.function.*; import javax.net.ssl.SSLContext; @@ -114,7 +114,9 @@ class AsyncNioTcpConnection extends AsyncNioConnection { } public ReadableByteChannel readableByteChannel() { - if (this.sslEngine == null) return this.channel; + if (this.sslEngine == null) { + return this.channel; + } AsyncConnection self = this; return new ReadableByteChannel() { @@ -139,8 +141,9 @@ class AsyncNioTcpConnection extends AsyncNioConnection { netBuffer.flip(); if (netBuffer.hasRemaining()) { ByteBuffer appBuffer = sslUnwrap(false, netBuffer); - if (appBuffer == null) return -1; //CLOSED,netBuffer已被回收 - + if (appBuffer == null) { + return -1; //CLOSED,netBuffer已被回收 + } appBuffer.flip(); int pos = bb.position(); while (bb.hasRemaining() && appBuffer.hasRemaining()) bb.put(appBuffer.get()); @@ -175,7 +178,9 @@ class AsyncNioTcpConnection extends AsyncNioConnection { @Override public WritableByteChannel writableByteChannel() { - if (this.sslEngine == null) return this.channel; + if (this.sslEngine == null) { + return this.channel; + } AsyncConnection self = this; return new WritableByteChannel() { @@ -284,9 +289,15 @@ class AsyncNioTcpConnection extends AsyncNioConnection { channel.shutdownInput(); channel.shutdownOutput(); channel.close(); - if (this.connectKey != null) this.connectKey.cancel(); - if (this.readKey != null) this.readKey.cancel(); - if (this.writeKey != null) this.writeKey.cancel(); + if (this.connectKey != null) { + this.connectKey.cancel(); + } + if (this.readKey != null) { + this.readKey.cancel(); + } + if (this.writeKey != null) { + this.writeKey.cancel(); + } } } diff --git a/src/main/java/org/redkale/net/AsyncNioTcpProtocolServer.java b/src/main/java/org/redkale/net/AsyncNioTcpProtocolServer.java index 88fb1f50d..74ace08e4 100644 --- a/src/main/java/org/redkale/net/AsyncNioTcpProtocolServer.java +++ b/src/main/java/org/redkale/net/AsyncNioTcpProtocolServer.java @@ -96,7 +96,9 @@ class AsyncNioTcpProtocolServer extends ProtocolServer { ObjectPool safeResponsePool = server.createResponsePool(createResponseCounter, cycleResponseCounter, server.responsePoolSize); final int respPoolMax = server.getResponsePoolSize(); ThreadLocal> localResponsePool = ThreadLocal.withInitial(() -> { - if (!(Thread.currentThread() instanceof WorkThread)) return null; + if (!(Thread.currentThread() instanceof WorkThread)) { + return null; + } return ObjectPool.createUnsafePool(safeResponsePool, safeResponsePool.getCreatCounter(), safeResponsePool.getCycleCounter(), respPoolMax, safeResponsePool.getCreator(), safeResponsePool.getPrepare(), safeResponsePool.getRecycler()); }); @@ -129,13 +131,17 @@ class AsyncNioTcpProtocolServer extends ProtocolServer { while (!closed) { try { int count = selector.select(); - if (count == 0) continue; + if (count == 0) { + continue; + } Set keys = selector.selectedKeys(); Iterator it = keys.iterator(); while (it.hasNext()) { SelectionKey key = it.next(); it.remove(); - if (key.isAcceptable()) accept(key); + if (key.isAcceptable()) { + accept(key); + } } } catch (Throwable t) { server.logger.log(Level.SEVERE, "server accept error", t); @@ -156,9 +162,13 @@ class AsyncNioTcpProtocolServer extends ProtocolServer { channel.setOption(StandardSocketOptions.SO_SNDBUF, 16 * 1024); AsyncIOThread readThread = ioGroup.nextIOThread(); LongAdder connCreateCounter = ioGroup.connCreateCounter; - if (connCreateCounter != null) connCreateCounter.increment(); + if (connCreateCounter != null) { + connCreateCounter.increment(); + } LongAdder connLivingCounter = ioGroup.connLivingCounter; - if (connLivingCounter != null) connLivingCounter.increment(); + if (connLivingCounter != null) { + connLivingCounter.increment(); + } AsyncNioTcpConnection conn = new AsyncNioTcpConnection(false, ioGroup, readThread, ioGroup.connectThread(), channel, context.getSSLBuilder(), context.getSSLContext(), null, connLivingCounter, ioGroup.connClosedCounter); ProtocolCodec codec = new ProtocolCodec(context, responseSupplier, responseConsumer, conn); conn.protocolCodec = codec; @@ -179,7 +189,9 @@ class AsyncNioTcpProtocolServer extends ProtocolServer { @Override public void close() throws IOException { - if (this.closed) return; + if (this.closed) { + return; + } this.closed = true; this.selector.wakeup(); this.ioGroup.close(); diff --git a/src/main/java/org/redkale/net/AsyncNioUdpConnection.java b/src/main/java/org/redkale/net/AsyncNioUdpConnection.java index 15d2ee958..88c1f077d 100644 --- a/src/main/java/org/redkale/net/AsyncNioUdpConnection.java +++ b/src/main/java/org/redkale/net/AsyncNioUdpConnection.java @@ -5,11 +5,11 @@ */ package org.redkale.net; -import java.io.*; +import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; -import java.util.*; +import java.util.Set; import java.util.concurrent.atomic.LongAdder; import java.util.function.*; import javax.net.ssl.SSLContext; @@ -103,19 +103,25 @@ class AsyncNioUdpConnection extends AsyncNioConnection { @Override public ReadableByteChannel readableByteChannel() { - if (this.sslEngine == null) return this.channel; + if (this.sslEngine == null) { + return this.channel; + } throw new UnsupportedOperationException("Not supported yet."); } @Override public WritableByteChannel writableByteChannel() { - if (this.sslEngine == null) return this.channel; + if (this.sslEngine == null) { + return this.channel; + } throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean isConnected() { - if (!client) return true; + if (!client) { + return true; + } return this.channel.isConnected(); } @@ -139,7 +145,9 @@ class AsyncNioUdpConnection extends AsyncNioConnection { int end = offset + length; for (int i = offset; i < end; i++) { ByteBuffer buf = srcs[i]; - if (buf.hasRemaining()) return this.channel.send(buf, remoteAddress); + if (buf.hasRemaining()) { + return this.channel.send(buf, remoteAddress); + } } return 0; } @@ -164,10 +172,18 @@ class AsyncNioUdpConnection extends AsyncNioConnection { @Override public final void close() throws IOException { super.close(); - if (client) channel.close(); //不能关闭channel - if (this.connectKey != null) this.connectKey.cancel(); - if (this.readKey != null) this.readKey.cancel(); - if (this.writeKey != null) this.writeKey.cancel(); + if (client) { + channel.close(); //不能关闭channel + } + if (this.connectKey != null) { + this.connectKey.cancel(); + } + if (this.readKey != null) { + this.readKey.cancel(); + } + if (this.writeKey != null) { + this.writeKey.cancel(); + } } } diff --git a/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java b/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java index ce1cd6d73..8c7dcc550 100644 --- a/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java +++ b/src/main/java/org/redkale/net/AsyncNioUdpProtocolServer.java @@ -9,7 +9,7 @@ import java.io.IOException; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; -import java.util.*; +import java.util.Set; import java.util.concurrent.atomic.LongAdder; import java.util.function.*; import org.redkale.boot.Application; @@ -92,7 +92,9 @@ class AsyncNioUdpProtocolServer extends ProtocolServer { ObjectPool safeBufferPool = server.createBufferPool(createBufferCounter, cycleBufferCounter, server.bufferPoolSize); ObjectPool safeResponsePool = server.createResponsePool(createResponseCounter, cycleResponseCounter, server.responsePoolSize); ThreadLocal> localResponsePool = ThreadLocal.withInitial(() -> { - if (!(Thread.currentThread() instanceof WorkThread)) return null; + if (!(Thread.currentThread() instanceof WorkThread)) { + return null; + } return ObjectPool.createUnsafePool(safeResponsePool, safeResponsePool.getCreatCounter(), safeResponsePool.getCycleCounter(), 16, safeResponsePool.getCreator(), safeResponsePool.getPrepare(), safeResponsePool.getRecycler()); }); @@ -137,9 +139,13 @@ class AsyncNioUdpProtocolServer extends ProtocolServer { private void accept(SocketAddress address, ByteBuffer buffer) throws IOException { AsyncIOThread readThread = ioGroup.nextIOThread(); LongAdder connCreateCounter = ioGroup.connCreateCounter; - if (connCreateCounter != null) connCreateCounter.increment(); + if (connCreateCounter != null) { + connCreateCounter.increment(); + } LongAdder connLivingCounter = ioGroup.connLivingCounter; - if (connLivingCounter != null) connLivingCounter.increment(); + if (connLivingCounter != null) { + connLivingCounter.increment(); + } AsyncNioUdpConnection conn = new AsyncNioUdpConnection(false, ioGroup, readThread, ioGroup.connectThread(), this.serverChannel, context.getSSLBuilder(), context.getSSLContext(), address, connLivingCounter, ioGroup.connClosedCounter); ProtocolCodec codec = new ProtocolCodec(context, responseSupplier, responseConsumer, conn); conn.protocolCodec = codec; @@ -160,7 +166,9 @@ class AsyncNioUdpProtocolServer extends ProtocolServer { @Override public void close() throws IOException { - if (this.closed) return; + if (this.closed) { + return; + } this.closed = true; this.ioGroup.close(); this.serverChannel.close(); diff --git a/src/main/java/org/redkale/net/DispatcherServlet.java b/src/main/java/org/redkale/net/DispatcherServlet.java index f240dff1a..41a7cd29f 100644 --- a/src/main/java/org/redkale/net/DispatcherServlet.java +++ b/src/main/java/org/redkale/net/DispatcherServlet.java @@ -5,9 +5,9 @@ */ package org.redkale.net; -import java.io.*; +import java.io.Serializable; import java.util.*; -import java.util.concurrent.atomic.*; +import java.util.concurrent.atomic.LongAdder; import java.util.function.Predicate; import java.util.logging.Level; import java.util.stream.Stream; @@ -69,7 +69,9 @@ public abstract class DispatcherServlet servletClass) { synchronized (servletLock) { for (S servlet : new HashSet<>(servlets)) { - if (servlet.getClass().equals(servletClass)) return true; + if (servlet.getClass().equals(servletClass)) { + return true; + } } return false; } @@ -78,7 +80,9 @@ public abstract class DispatcherServlet(servlets)) { - if (servlet.getClass().getName().equals(servletClassName)) return true; + if (servlet.getClass().getName().equals(servletClassName)) { + return true; + } } return false; } @@ -128,7 +132,9 @@ public abstract class DispatcherServlet filterClass) { - if (this.headFilter == null || filterClass == null) return false; + if (this.headFilter == null || filterClass == null) { + return false; + } Filter filter = this.headFilter; do { - if (filter.getClass().equals(filterClass)) return true; + if (filter.getClass().equals(filterClass)) { + return true; + } } while ((filter = filter._next) != null); return false; } public boolean containsFilter(String filterClassName) { - if (this.headFilter == null || filterClassName == null) return false; + if (this.headFilter == null || filterClassName == null) { + return false; + } Filter filter = this.headFilter; do { - if (filter.getClass().getName().equals(filterClassName)) return true; + if (filter.getClass().getName().equals(filterClassName)) { + return true; + } } while ((filter = filter._next) != null); return false; } @SuppressWarnings("unchecked") public > T removeFilter(Predicate predicate) { - if (this.headFilter == null || predicate == null) return null; + if (this.headFilter == null || predicate == null) { + return null; + } synchronized (filters) { Filter filter = this.headFilter; Filter prev = null; do { - if (predicate.test((T) filter)) break; + if (predicate.test((T) filter)) { + break; + } prev = filter; } while ((filter = filter._next) != null); if (filter != null) { diff --git a/src/main/java/org/redkale/net/ProtocolCodec.java b/src/main/java/org/redkale/net/ProtocolCodec.java index 493f2a2d1..7012fd42e 100644 --- a/src/main/java/org/redkale/net/ProtocolCodec.java +++ b/src/main/java/org/redkale/net/ProtocolCodec.java @@ -136,7 +136,9 @@ class ProtocolCodec implements CompletionHandler { if (rs < 0) { //表示数据格式不正确 final DispatcherServlet preparer = context.prepare; LongAdder ec = preparer.executeCounter; - if (ec != null) ec.increment(); + if (ec != null) { + ec.increment(); + } channel.offerBuffer(buffer); if (rs != Integer.MIN_VALUE && preparer.illRequestCounter != null) { preparer.illRequestCounter.increment(); @@ -148,15 +150,21 @@ class ProtocolCodec implements CompletionHandler { } else if (rs == 0) { final DispatcherServlet preparer = context.prepare; LongAdder ec = preparer.executeCounter; - if (ec != null) ec.increment(); + if (ec != null) { + ec.increment(); + } int pindex = pipelineIndex; boolean pipeline = false; Request hreq = lastreq; if (buffer.hasRemaining()) { pipeline = true; - if (pindex == 0) pindex++; + if (pindex == 0) { + pindex++; + } request.pipeline(pindex, pindex + 1); - if (hreq == null) hreq = request.copyHeader(); + if (hreq == null) { + hreq = request.copyHeader(); + } } else { request.pipeline(pindex, pindex); channel.setReadBuffer((ByteBuffer) buffer.clear()); @@ -193,7 +201,9 @@ class ProtocolCodec implements CompletionHandler { } channel.offerBuffer(attachment); response.finish(true); - if (exc != null) request.context.logger.log(Level.FINER, "Servlet read channel erroneous, force to close channel ", exc); + if (exc != null) { + request.context.logger.log(Level.FINER, "Servlet read channel erroneous, force to close channel ", exc); + } } }); } diff --git a/src/main/java/org/redkale/net/Response.java b/src/main/java/org/redkale/net/Response.java index 44e4d05d1..c3e3c167c 100644 --- a/src/main/java/org/redkale/net/Response.java +++ b/src/main/java/org/redkale/net/Response.java @@ -120,14 +120,18 @@ public abstract class Response> { } protected boolean recycle() { - if (!inited) return false; + if (!inited) { + return false; + } this.output = null; this.filter = null; this.servlet = null; boolean notpipeline = request.pipelineIndex == 0 || request.pipelineOver; request.recycle(); if (channel != null) { - if (notpipeline) channel.dispose(); + if (notpipeline) { + channel.dispose(); + } channel = null; } this.responseSupplier = null; @@ -195,9 +199,12 @@ public abstract class Response> { } public void finish(boolean kill) { - if (!this.inited) return; //避免重复关闭 - //System.println("耗时: " + (System.currentTimeMillis() - request.createtime)); - if (kill) refuseAlive(); + if (!this.inited) { + return; //避免重复关闭 + } //System.println("耗时: " + (System.currentTimeMillis() - request.createtime)); + if (kill) { + refuseAlive(); + } if (this.recycleListener != null) { try { this.recycleListener.accept(request, this); @@ -243,8 +250,12 @@ public abstract class Response> { } public void finish(boolean kill, final byte[] bs, int offset, int length) { - if (!this.inited) return; //避免重复关闭 - if (kill) refuseAlive(); + if (!this.inited) { + return; //避免重复关闭 + } + if (kill) { + refuseAlive(); + } if (this.channel.hasPipelineData()) { this.channel.flushPipelineData(null, new CompletionHandler() { @@ -264,8 +275,12 @@ public abstract class Response> { } public void finish(boolean kill, final byte[] bs, int offset, int length, final byte[] bs2, int offset2, int length2, Consumer callback, A attachment) { - if (!this.inited) return; //避免重复关闭 - if (kill) refuseAlive(); + if (!this.inited) { + return; //避免重复关闭 + } + if (kill) { + refuseAlive(); + } if (this.channel.hasPipelineData()) { this.channel.flushPipelineData(null, new CompletionHandler() { @@ -293,8 +308,12 @@ public abstract class Response> { } protected void finish(boolean kill, ByteBuffer buffer) { - if (!this.inited) return; //避免重复关闭 - if (kill) refuseAlive(); + if (!this.inited) { + return; //避免重复关闭 + } + if (kill) { + refuseAlive(); + } if (this.channel.hasPipelineData()) { this.channel.flushPipelineData(null, new CompletionHandler() { @@ -314,8 +333,12 @@ public abstract class Response> { } protected void finish(boolean kill, ByteBuffer... buffers) { - if (!this.inited) return; //避免重复关闭 - if (kill) refuseAlive(); + if (!this.inited) { + return; //避免重复关闭 + } + if (kill) { + refuseAlive(); + } if (this.channel.hasPipelineData()) { this.channel.flushPipelineData(null, new CompletionHandler() { @@ -339,12 +362,16 @@ public abstract class Response> { @Override public void completed(Integer result, Void attachment) { - if (handler != null) handler.completed(result, attachment); + if (handler != null) { + handler.completed(result, attachment); + } } @Override public void failed(Throwable exc, Void attachment) { - if (handler != null) handler.failed(exc, attachment); + if (handler != null) { + handler.failed(exc, attachment); + } } }); @@ -356,13 +383,17 @@ public abstract class Response> { @Override public void completed(Integer result, A attachment) { channel.offerBuffer(buffer); - if (handler != null) handler.completed(result, attachment); + if (handler != null) { + handler.completed(result, attachment); + } } @Override public void failed(Throwable exc, A attachment) { channel.offerBuffer(buffer); - if (handler != null) handler.failed(exc, attachment); + if (handler != null) { + handler.failed(exc, attachment); + } } }); @@ -374,7 +405,9 @@ public abstract class Response> { @Override public void completed(Integer result, A attachment) { channel.offerBuffer(buffers); - if (handler != null) handler.completed(result, attachment); + if (handler != null) { + handler.completed(result, attachment); + } } @Override @@ -382,7 +415,9 @@ public abstract class Response> { for (ByteBuffer buffer : buffers) { channel.offerBuffer(buffer); } - if (handler != null) handler.failed(exc, attachment); + if (handler != null) { + handler.failed(exc, attachment); + } } }); diff --git a/src/main/java/org/redkale/net/Server.java b/src/main/java/org/redkale/net/Server.java index 1cd991c32..44c16ca77 100644 --- a/src/main/java/org/redkale/net/Server.java +++ b/src/main/java/org/redkale/net/Server.java @@ -133,7 +133,9 @@ public abstract class Server= 0) { - if (value.endsWith("G")) return (long) (Float.parseFloat(value.replace("G", "")) * 1024 * 1024 * 1024); - if (value.endsWith("M")) return (long) (Float.parseFloat(value.replace("M", "")) * 1024 * 1024); - if (value.endsWith("K")) return (long) (Float.parseFloat(value.replace("K", "")) * 1024); + if (value.endsWith("G")) { + return (long) (Float.parseFloat(value.replace("G", "")) * 1024 * 1024 * 1024); + } + if (value.endsWith("M")) { + return (long) (Float.parseFloat(value.replace("M", "")) * 1024 * 1024); + } + if (value.endsWith("K")) { + return (long) (Float.parseFloat(value.replace("K", "")) * 1024); + } return (long) Float.parseFloat(value); } - if (value.endsWith("G")) return Long.decode(value.replace("G", "")) * 1024 * 1024 * 1024; - if (value.endsWith("M")) return Long.decode(value.replace("M", "")) * 1024 * 1024; - if (value.endsWith("K")) return Long.decode(value.replace("K", "")) * 1024; + if (value.endsWith("G")) { + return Long.decode(value.replace("G", "")) * 1024 * 1024 * 1024; + } + if (value.endsWith("M")) { + return Long.decode(value.replace("M", "")) * 1024 * 1024; + } + if (value.endsWith("K")) { + return Long.decode(value.replace("K", "")) * 1024; + } return Long.decode(value); } protected static String formatLenth(long value) { - if (value < 1) return "" + value; - if (value % (1024 * 1024 * 1024) == 0) return value / (1024 * 1024 * 1024) + "G"; - if (value % (1024 * 1024) == 0) return value / (1024 * 1024) + "M"; - if (value % 1024 == 0) return value / (1024) + "K"; + if (value < 1) { + return "" + value; + } + if (value % (1024 * 1024 * 1024) == 0) { + return value / (1024 * 1024 * 1024) + "G"; + } + if (value % (1024 * 1024) == 0) { + return value / (1024 * 1024) + "M"; + } + if (value % 1024 == 0) { + return value / (1024) + "K"; + } return value + "B"; } @@ -333,39 +357,55 @@ public abstract class Server set = new HashSet<>(); try { for (String s : lib.split(";")) { - if (s.isEmpty()) continue; + if (s.isEmpty()) { + continue; + } if (s.endsWith("*")) { File root = new File(s.substring(0, s.length() - 1)); if (root.isDirectory()) { File[] lfs = root.listFiles(); - if (lfs == null) throw new RuntimeException("File(" + root + ") cannot listFiles()"); + if (lfs == null) { + throw new RuntimeException("File(" + root + ") cannot listFiles()"); + } for (File f : lfs) { set.add(f.toURI().toURL()); } } } else { File f = new File(s); - if (f.canRead()) set.add(f.toURI().toURL()); + if (f.canRead()) { + set.add(f.toURI().toURL()); + } } } } catch (IOException e) { throw new RuntimeException(e); } - if (set.isEmpty()) return new URL[0]; + if (set.isEmpty()) { + return new URL[0]; + } for (URL url : set) { classLoader.addURL(url); } diff --git a/src/main/java/org/redkale/net/Transport.java b/src/main/java/org/redkale/net/Transport.java index 4e7bd2d8e..1e92dbe30 100644 --- a/src/main/java/org/redkale/net/Transport.java +++ b/src/main/java/org/redkale/net/Transport.java @@ -9,18 +9,17 @@ import java.io.IOException; import java.lang.ref.WeakReference; import java.net.*; import java.nio.ByteBuffer; -import java.nio.channels.*; +import java.nio.channels.CompletionHandler; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.*; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.logging.Level; import javax.net.ssl.SSLContext; - import org.redkale.annotation.ConstructorParameters; -import org.redkale.convert.*; +import org.redkale.convert.ConvertDisabled; import org.redkale.convert.json.JsonConvert; -import org.redkale.util.*; +import org.redkale.util.Utility; /** * 传输客户端 @@ -104,7 +103,9 @@ public final class Transport { List list = new ArrayList<>(); if (addresses != null) { for (InetSocketAddress addr : addresses) { - if (clientAddress != null && clientAddress.equals(addr)) continue; + if (clientAddress != null && clientAddress.equals(addr)) { + continue; + } boolean hasold = false; for (TransportNode oldAddr : oldNodes) { if (oldAddr.getAddress().equals(addr)) { @@ -113,7 +114,9 @@ public final class Transport { break; } } - if (hasold) continue; + if (hasold) { + continue; + } list.add(new TransportNode(factory.poolmaxconns, addr)); } } @@ -128,14 +131,20 @@ public final class Transport { } public final boolean addRemoteAddresses(final InetSocketAddress addr) { - if (addr == null) return false; - if (clientAddress != null && clientAddress.equals(addr)) return false; + if (addr == null) { + return false; + } + if (clientAddress != null && clientAddress.equals(addr)) { + return false; + } synchronized (this) { if (this.transportNodes.length == 0) { this.transportNodes = new TransportNode[]{new TransportNode(factory.poolmaxconns, addr)}; } else { for (TransportNode i : this.transportNodes) { - if (addr.equals(i.address)) return false; + if (addr.equals(i.address)) { + return false; + } } this.transportNodes = Utility.append(transportNodes, new TransportNode(factory.poolmaxconns, addr)); } @@ -144,7 +153,9 @@ public final class Transport { } public final boolean removeRemoteAddresses(InetSocketAddress addr) { - if (addr == null) return false; + if (addr == null) { + return false; + } synchronized (this) { this.transportNodes = Utility.remove(transportNodes, new TransportNode(factory.poolmaxconns, addr)); } @@ -157,9 +168,13 @@ public final class Transport { public void close() { TransportNode[] nodes = this.transportNodes; - if (nodes == null) return; + if (nodes == null) { + return; + } for (TransportNode node : nodes) { - if (node != null) node.dispose(); + if (node != null) { + node.dispose(); + } } } @@ -173,7 +188,9 @@ public final class Transport { public TransportNode findTransportNode(SocketAddress addr) { for (TransportNode node : this.transportNodes) { - if (node.address.equals(addr)) return node; + if (node.address.equals(addr)) { + return node; + } } return null; } @@ -214,23 +231,33 @@ public final class Transport { if (semaphore != null && !semaphore.tryAcquire()) { final CompletableFuture future = Utility.orTimeout(new CompletableFuture<>(), 10, TimeUnit.SECONDS); future.whenComplete((r, t) -> node.pollQueue.remove(future)); - if (node.pollQueue.offer(future)) return future; + if (node.pollQueue.offer(future)) { + return future; + } future.completeExceptionally(new IOException("create transport connection error")); return future; } return func.get().thenApply(conn -> { - if (conn != null && semaphore != null) conn.beforeCloseListener((c) -> semaphore.release()); + if (conn != null && semaphore != null) { + conn.beforeCloseListener((c) -> semaphore.release()); + } return conn; }); } public CompletableFuture pollConnection(SocketAddress addr0) { - if (this.strategy != null) return strategy.pollConnection(addr0, this); + if (this.strategy != null) { + return strategy.pollConnection(addr0, this); + } final TransportNode[] nodes = this.transportNodes; - if (addr0 == null && nodes.length == 1) addr0 = nodes[0].address; + if (addr0 == null && nodes.length == 1) { + addr0 = nodes[0].address; + } final SocketAddress addr = addr0; final boolean rand = addr == null; //是否随机取地址 - if (rand && nodes.length < 1) throw new RuntimeException("Transport (" + this.name + ") have no remoteAddress list"); + if (rand && nodes.length < 1) { + throw new RuntimeException("Transport (" + this.name + ") have no remoteAddress list"); + } try { if (!tcp) { // UDP SocketAddress udpaddr = rand ? nodes[0].address : addr; @@ -238,7 +265,9 @@ public final class Transport { } if (!rand) { //指定地址 TransportNode node = findTransportNode(addr); - if (node == null) return asyncGroup.createTCPClient(addr, factory.readTimeoutSeconds, factory.writeTimeoutSeconds); + if (node == null) { + return asyncGroup.createTCPClient(addr, factory.readTimeoutSeconds, factory.writeTimeoutSeconds); + } return pollAsync(node, addr, () -> asyncGroup.createTCPClient(addr, factory.readTimeoutSeconds, factory.writeTimeoutSeconds)); } @@ -246,7 +275,9 @@ public final class Transport { int enablecount = 0; final TransportNode[] newnodes = new TransportNode[nodes.length]; for (final TransportNode node : nodes) { - if (node.disabletime > 0) continue; + if (node.disabletime > 0) { + continue; + } newnodes[enablecount++] = node; } final long now = System.currentTimeMillis(); @@ -280,11 +311,17 @@ public final class Transport { //从可用/不可用的地址列表中创建连接 CompletableFuture future = new CompletableFuture(); for (final TransportNode node : nodes) { - if (node == exclude) continue; - if (future.isDone()) return future; + if (node == exclude) { + continue; + } + if (future.isDone()) { + return future; + } asyncGroup.createTCPClient(node.address, factory.readTimeoutSeconds, factory.writeTimeoutSeconds) .whenComplete((c, t) -> { - if (c != null && !future.complete(c)) node.connQueue.offer(c); + if (c != null && !future.complete(c)) { + node.connQueue.offer(c); + } node.disabletime = t == null ? 0 : System.currentTimeMillis(); }); } @@ -292,11 +329,15 @@ public final class Transport { } public void offerConnection(final boolean forceClose, AsyncConnection conn) { - if (this.strategy != null && strategy.offerConnection(forceClose, conn)) return; + if (this.strategy != null && strategy.offerConnection(forceClose, conn)) { + return; + } if (!forceClose && conn.isTCP()) { if (conn.isOpen()) { TransportNode node = findTransportNode(conn.getRemoteAddress()); - if (node == null || !node.connQueue.offer(conn)) conn.dispose(); + if (node == null || !node.connQueue.offer(conn)) { + conn.dispose(); + } } else { conn.dispose(); } @@ -321,7 +362,9 @@ public final class Transport { @Override public void completed(Integer result, ByteBuffer attachment) { - if (handler != null) handler.completed(result, att); + if (handler != null) { + handler.completed(result, att); + } conn.offerBuffer(attachment); offerConnection(false, conn); } @@ -401,7 +444,9 @@ public final class Transport { public void setAttributes(ConcurrentHashMap map) { attributes.clear(); - if (map != null) attributes.putAll(map); + if (map != null) { + attributes.putAll(map); + } } public InetSocketAddress getAddress() { @@ -431,9 +476,15 @@ public final class Transport { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } final TransportNode other = (TransportNode) obj; return this.address.equals(other.address); } diff --git a/src/main/java/org/redkale/net/TransportFactory.java b/src/main/java/org/redkale/net/TransportFactory.java index 085ff11d0..6485bfaa4 100644 --- a/src/main/java/org/redkale/net/TransportFactory.java +++ b/src/main/java/org/redkale/net/TransportFactory.java @@ -6,15 +6,14 @@ package org.redkale.net; import java.lang.ref.WeakReference; -import java.net.*; +import java.net.InetSocketAddress; import java.nio.ByteBuffer; -import java.nio.channels.*; +import java.nio.channels.CompletionHandler; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; import java.util.stream.Collectors; import javax.net.ssl.SSLContext; - import org.redkale.annotation.Comment; import org.redkale.service.Service; import org.redkale.util.*; @@ -109,9 +108,15 @@ public class TransportFactory { this.poolmaxconns = conf.getIntValue(NAME_POOLMAXCONNS, this.poolmaxconns); this.pinginterval = conf.getIntValue(NAME_PINGINTERVAL, this.pinginterval); this.checkinterval = conf.getIntValue(NAME_CHECKINTERVAL, this.checkinterval); - if (this.poolmaxconns < 2) this.poolmaxconns = 2; - if (this.pinginterval < 2) this.pinginterval = 2; - if (this.checkinterval < 2) this.checkinterval = 2; + if (this.poolmaxconns < 2) { + this.poolmaxconns = 2; + } + if (this.pinginterval < 2) { + this.pinginterval = 2; + } + if (this.checkinterval < 2) { + this.checkinterval = 2; + } } this.scheduler = new ScheduledThreadPoolExecutor(1, (Runnable r) -> { final Thread t = new Thread(r, "Redkale-" + this.getClass().getSimpleName() + "-Schedule-Thread"); @@ -163,12 +168,16 @@ public class TransportFactory { } public String findGroupName(InetSocketAddress addr) { - if (addr == null) return null; + if (addr == null) { + return null; + } return groupAddrs.get(addr); } public TransportGroupInfo findGroupInfo(String group) { - if (group == null) return null; + if (group == null) { + return null; + } return groupInfos.get(group); } @@ -178,10 +187,16 @@ public class TransportFactory { } public boolean removeGroupInfo(String groupName, InetSocketAddress addr) { - if (groupName == null || groupName.isEmpty() || addr == null) return false; - if (!groupName.equals(groupAddrs.get(addr))) return false; + if (groupName == null || groupName.isEmpty() || addr == null) { + return false; + } + if (!groupName.equals(groupAddrs.get(addr))) { + return false; + } TransportGroupInfo group = groupInfos.get(groupName); - if (group == null) return false; + if (group == null) { + return false; + } group.removeAddress(addr); groupAddrs.remove(addr); return true; @@ -193,13 +208,23 @@ public class TransportFactory { } public boolean addGroupInfo(TransportGroupInfo info) { - if (info == null) throw new RuntimeException("TransportGroupInfo can not null"); - if (info.addresses == null) throw new RuntimeException("TransportGroupInfo.addresses can not null"); - if (!checkName(info.name)) throw new RuntimeException("Transport.group.name only 0-9 a-z A-Z _ cannot begin 0-9"); + if (info == null) { + throw new RuntimeException("TransportGroupInfo can not null"); + } + if (info.addresses == null) { + throw new RuntimeException("TransportGroupInfo.addresses can not null"); + } + if (!checkName(info.name)) { + throw new RuntimeException("Transport.group.name only 0-9 a-z A-Z _ cannot begin 0-9"); + } TransportGroupInfo old = groupInfos.get(info.name); - if (old != null && !old.protocol.equals(info.protocol)) throw new RuntimeException("Transport.group.name repeat but protocol is different"); + if (old != null && !old.protocol.equals(info.protocol)) { + throw new RuntimeException("Transport.group.name repeat but protocol is different"); + } for (InetSocketAddress addr : info.addresses) { - if (!groupAddrs.getOrDefault(addr, info.name).equals(info.name)) throw new RuntimeException(addr + " repeat but different group.name"); + if (!groupAddrs.getOrDefault(addr, info.name).equals(info.name)) { + throw new RuntimeException(addr + " repeat but different group.name"); + } } if (old == null) { groupInfos.put(info.name, info); @@ -213,12 +238,16 @@ public class TransportFactory { } public Transport loadTransport(InetSocketAddress sncpAddress, final Set groups) { - if (groups == null) return null; + if (groups == null) { + return null; + } Set addresses = new HashSet<>(); TransportGroupInfo info = null; for (String group : groups) { info = groupInfos.get(group); - if (info == null) continue; + if (info == null) { + continue; + } addresses.addAll(info.addresses); } if (info == null) { @@ -226,7 +255,9 @@ public class TransportFactory { } else { info.protocol = netprotocol; } - if (sncpAddress != null) addresses.remove(sncpAddress); + if (sncpAddress != null) { + addresses.remove(sncpAddress); + } return new Transport(groups.stream().sorted().collect(Collectors.joining(";")), info.protocol, this, this.asyncGroup, this.sslContext, sncpAddress, addresses, this.strategy); } @@ -239,7 +270,9 @@ public class TransportFactory { } public void addSncpService(Service service) { - if (service == null) return; + if (service == null) { + return; + } services.add(new WeakReference<>(service)); } @@ -247,13 +280,17 @@ public class TransportFactory { List rs = new ArrayList<>(); for (WeakReference ref : services) { Service service = ref.get(); - if (service != null) rs.add(service); + if (service != null) { + rs.add(service); + } } return rs; } public void shutdownNow() { - if (this.scheduler != null) this.scheduler.shutdownNow(); + if (this.scheduler != null) { + this.scheduler.shutdownNow(); + } } private void checks() { @@ -266,11 +303,15 @@ public class TransportFactory { } Transport.TransportNode[] nodes = transport.getTransportNodes(); for (final Transport.TransportNode node : nodes) { - if (node.disabletime < 1) continue; //可用 + if (node.disabletime < 1) { + continue; //可用 + } CompletableFuture future = Utility.orTimeout(asyncGroup.createTCPClient(node.address), 2, TimeUnit.SECONDS); future.whenComplete((r, t) -> { node.disabletime = t == null ? 0 : System.currentTimeMillis(); - if (r != null) r.dispose(); + if (r != null) { + r.dispose(); + } }); } } @@ -283,7 +324,9 @@ public class TransportFactory { long timex = System.currentTimeMillis() - (this.pinginterval < 15 ? this.pinginterval : (this.pinginterval - 3)) * 1000; for (WeakReference ref : transportReferences) { Transport transport = ref.get(); - if (transport == null) continue; + if (transport == null) { + continue; + } Transport.TransportNode[] nodes = transport.getTransportNodes(); for (final Transport.TransportNode node : nodes) { final BlockingQueue queue = node.connQueue; @@ -338,8 +381,12 @@ public class TransportFactory { } private static boolean checkName(String name) { //不能含特殊字符 - if (name.isEmpty()) return false; - if (name.charAt(0) >= '0' && name.charAt(0) <= '9') return false; + if (name.isEmpty()) { + return false; + } + if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { + return false; + } for (char ch : name.toCharArray()) { if (!((ch >= '0' && ch <= '9') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { //不能含特殊字符 return false; diff --git a/src/main/java/org/redkale/net/TransportGroupInfo.java b/src/main/java/org/redkale/net/TransportGroupInfo.java index 21975af1f..db7a45f0f 100644 --- a/src/main/java/org/redkale/net/TransportGroupInfo.java +++ b/src/main/java/org/redkale/net/TransportGroupInfo.java @@ -79,31 +79,45 @@ public class TransportGroupInfo { public boolean containsAddress(InetSocketAddress addr) { synchronized (this) { - if (this.addresses == null) return false; + if (this.addresses == null) { + return false; + } return this.addresses.contains(addr); } } public void removeAddress(InetSocketAddress addr) { - if (addr == null) return; + if (addr == null) { + return; + } synchronized (this) { - if (this.addresses == null) return; + if (this.addresses == null) { + return; + } this.addresses.remove(addr); } } public void putAddress(InetSocketAddress addr) { - if (addr == null) return; + if (addr == null) { + return; + } synchronized (this) { - if (this.addresses == null) this.addresses = new HashSet<>(); + if (this.addresses == null) { + this.addresses = new HashSet<>(); + } this.addresses.add(addr); } } public void putAddress(Set addrs) { - if (addrs == null) return; + if (addrs == null) { + return; + } synchronized (this) { - if (this.addresses == null) this.addresses = new HashSet<>(); + if (this.addresses == null) { + this.addresses = new HashSet<>(); + } this.addresses.addAll(addrs); } } diff --git a/src/main/java/org/redkale/net/WorkThread.java b/src/main/java/org/redkale/net/WorkThread.java index 9653f4943..cb835ac2e 100644 --- a/src/main/java/org/redkale/net/WorkThread.java +++ b/src/main/java/org/redkale/net/WorkThread.java @@ -29,7 +29,9 @@ public class WorkThread extends Thread implements Executor { public WorkThread(String name, int index, int threads, ExecutorService workExecutor, Runnable target) { super(target); - if (name != null) setName(name); + if (name != null) { + setName(name); + } this.index = index; this.threads = threads; this.workExecutor = workExecutor; @@ -64,7 +66,9 @@ public class WorkThread extends Thread implements Executor { } public void execute(Collection commands) { - if (commands == null) return; + if (commands == null) { + return; + } if (workExecutor == null) { for (Runnable command : commands) { command.run(); diff --git a/src/main/java/org/redkale/net/client/Client.java b/src/main/java/org/redkale/net/client/Client.java index e6cb7e97e..b981bf5c0 100644 --- a/src/main/java/org/redkale/net/client/Client.java +++ b/src/main/java/org/redkale/net/client/Client.java @@ -8,8 +8,8 @@ package org.redkale.net.client; import java.util.Queue; import java.util.concurrent.*; import java.util.concurrent.atomic.*; -import java.util.function.*; -import java.util.logging.*; +import java.util.function.Function; +import java.util.logging.Logger; import org.redkale.net.*; import org.redkale.util.*; @@ -105,7 +105,9 @@ public abstract class Client { @SuppressWarnings("OverridableMethodCallInConstructor") protected Client(AsyncGroup group, boolean tcp, ClientAddress address, int maxconns, int maxPipelines, R pingRequest, R closeRequest, Function, CompletableFuture> authenticate) { - if (maxPipelines < 1) throw new IllegalArgumentException("maxPipelines must bigger 0"); + if (maxPipelines < 1) { + throw new IllegalArgumentException("maxPipelines must bigger 0"); + } this.group = group; this.tcp = tcp; this.address = address; @@ -140,8 +142,12 @@ public abstract class Client { } long now = System.currentTimeMillis(); for (ClientConnection conn : this.connArray) { - if (conn == null) continue; - if (now - conn.getLastWriteTime() < 10_000) continue; + if (conn == null) { + continue; + } + if (now - conn.getLastWriteTime() < 10_000) { + continue; + } conn.writeChannel(req).thenAccept(p -> handlePingResult(conn, p)); } } catch (Throwable t) { @@ -160,11 +166,15 @@ public abstract class Client { } public synchronized void close() { - if (this.closed) return; + if (this.closed) { + return; + } this.timeoutScheduler.shutdownNow(); final R closereq = closeRequest; for (ClientConnection conn : this.connArray) { - if (conn == null) continue; + if (conn == null) { + continue; + } if (closereq == null) { conn.dispose(null); } else { @@ -180,12 +190,16 @@ public abstract class Client { } public final CompletableFuture

sendAsync(R request) { - if (request.workThread == null) request.workThread = WorkThread.currWorkThread(); + if (request.workThread == null) { + request.workThread = WorkThread.currWorkThread(); + } return connect(null).thenCompose(conn -> writeChannel(conn, request)); } public final CompletableFuture

sendAsync(ChannelContext context, R request) { - if (request.workThread == null) request.workThread = WorkThread.currWorkThread(); + if (request.workThread == null) { + request.workThread = WorkThread.currWorkThread(); + } return connect(context).thenCompose(conn -> writeChannel(conn, request)); } @@ -201,7 +215,9 @@ public abstract class Client { final boolean cflag = context != null && connectionContextName != null; if (cflag) { ClientConnection cc = context.getAttribute(connectionContextName); - if (cc != null && cc.isOpen()) return CompletableFuture.completedFuture(cc); + if (cc != null && cc.isOpen()) { + return CompletableFuture.completedFuture(cc); + } } int connIndex; final int size = this.connArray.length; @@ -214,7 +230,9 @@ public abstract class Client { // if (connIndex >= 0) { ClientConnection cc = this.connArray[connIndex]; if (cc != null && cc.isOpen()) { - if (cflag) context.setAttribute(connectionContextName, cc); + if (cflag) { + context.setAttribute(connectionContextName, cc); + } return CompletableFuture.completedFuture(cc); } final int index = connIndex; @@ -226,13 +244,17 @@ public abstract class Client { c.authenticated = true; this.connArray[index] = c; CompletableFuture f; - if (cflag) context.setAttribute(connectionContextName, c); + if (cflag) { + context.setAttribute(connectionContextName, c); + } while ((f = waitQueue.poll()) != null) { f.complete(c); } return c; }).whenComplete((r, t) -> { - if (t != null) this.connOpenStates[index].set(false); + if (t != null) { + this.connOpenStates[index].set(false); + } }); } else { CompletableFuture rs = Utility.orTimeout(new CompletableFuture(), 6, TimeUnit.SECONDS); diff --git a/src/main/java/org/redkale/net/client/ClientAddress.java b/src/main/java/org/redkale/net/client/ClientAddress.java index 91fa91804..5bd41f75e 100644 --- a/src/main/java/org/redkale/net/client/ClientAddress.java +++ b/src/main/java/org/redkale/net/client/ClientAddress.java @@ -23,7 +23,6 @@ public class ClientAddress implements java.io.Serializable { public ClientAddress() { } - public ClientAddress(SocketAddress address) { this.address = address; } @@ -31,7 +30,7 @@ public class ClientAddress implements java.io.Serializable { public CompletableFuture createClient(final boolean tcp, final AsyncGroup group, int readTimeoutSeconds, int writeTimeoutSeconds) { return group.createClient(tcp, address, readTimeoutSeconds, writeTimeoutSeconds); } - + public SocketAddress getAddress() { return address; } diff --git a/src/main/java/org/redkale/net/client/ClientCodec.java b/src/main/java/org/redkale/net/client/ClientCodec.java index a0c017a42..2bed6a7c6 100644 --- a/src/main/java/org/redkale/net/client/ClientCodec.java +++ b/src/main/java/org/redkale/net/client/ClientCodec.java @@ -39,7 +39,9 @@ public abstract class ClientCodec { } public List> removeResults() { - if (results.isEmpty()) return null; + if (results.isEmpty()) { + return null; + } List> rs = new ArrayList<>(results); this.results.clear(); return rs; diff --git a/src/main/java/org/redkale/net/client/ClientConnection.java b/src/main/java/org/redkale/net/client/ClientConnection.java index 87a933686..dc18ae821 100644 --- a/src/main/java/org/redkale/net/client/ClientConnection.java +++ b/src/main/java/org/redkale/net/client/ClientConnection.java @@ -58,11 +58,15 @@ public abstract class ClientConnection implements Co @Override public void completed(Integer result, Void attachment) { if (writeLastRequest != null && writeLastRequest == client.closeRequest) { - if (closeFuture != null) closeFuture.complete(null); + if (closeFuture != null) { + closeFuture.complete(null); + } closeFuture = null; return; } - if (continueWrite(false)) return; + if (continueWrite(false)) { + return; + } writePending.compareAndSet(true, false); readChannel(); } @@ -96,11 +100,15 @@ public abstract class ClientConnection implements Co ByteArray rw = conn.writeArray; rw.clear(); int pipelines = maxPipelines > 1 ? (maxPipelines - responseQueue.size()) : 1; - if (must && pipelines < 1) pipelines = 1; + if (must && pipelines < 1) { + pipelines = 1; + } int c = 0; AtomicBoolean pw = conn.pauseWriting; for (int i = 0; i < pipelines; i++) { - if (pw.get()) break; + if (pw.get()) { + break; + } R req; if (lastHalfRequest == null) { req = requestQueue.poll(); @@ -108,13 +116,17 @@ public abstract class ClientConnection implements Co req = lastHalfRequest; lastHalfRequest = null; } - if (req == null) break; + if (req == null) { + break; + } writeLastRequest = req; if (req.canMerge(conn)) { R r; while ((r = requestQueue.poll()) != null) { i++; - if (!req.merge(conn, r)) break; + if (!req.merge(conn, r)) { + break; + } req.respFuture.mergeCount++; } req.accept(conn, rw); @@ -136,7 +148,9 @@ public abstract class ClientConnection implements Co channel.write(rw, writeHandler); return true; } - if (pw.get()) writePending.compareAndSet(true, false); + if (pw.get()) { + writePending.compareAndSet(true, false); + } return false; } @@ -174,9 +188,13 @@ public abstract class ClientConnection implements Co } } respWaitingCounter.decrement(); - if (isAuthenticated() && client.respDoneCounter != null) client.respDoneCounter.increment(); + if (isAuthenticated() && client.respDoneCounter != null) { + client.respDoneCounter.increment(); + } try { - if (respFuture.timeout != null) respFuture.timeout.cancel(true); + if (respFuture.timeout != null) { + respFuture.timeout.cancel(true); + } ClientRequest request = respFuture.request; //if (client.finest) client.logger.log(Level.FINEST, Utility.nowMillis() + ": " + Thread.currentThread().getName() + ": " + ClientConnection.this + ", 回调处理, req=" + request + ", result=" + rs.result); preComplete(rs.result, (R) request, rs.exc); @@ -227,7 +245,9 @@ public abstract class ClientConnection implements Co if (mergeCount > 0) { for (int i = 0; i < mergeCount; i++) { respFuture = responseQueue.poll(); - if (respFuture != null) completeResponse(rs, respFuture); + if (respFuture != null) { + completeResponse(rs, respFuture); + } } } } @@ -315,7 +335,9 @@ public abstract class ClientConnection implements Co responseQueue.offer(respFuture); } requestQueue.offer(request); - if (isAuthenticated() && client.reqWritedCounter != null) client.reqWritedCounter.increment(); + if (isAuthenticated() && client.reqWritedCounter != null) { + client.reqWritedCounter.increment(); + } } if (responseQueue.size() < 2 && writePending.compareAndSet(false, true)) {//responseQueue.size() < 2 && 加了这句会存在偶尔不写数据的问题? continueWrite(true); @@ -358,7 +380,9 @@ public abstract class ClientConnection implements Co CompletableFuture f; respWaitingCounter.reset(); while ((f = responseQueue.poll()) != null) { - if (e == null) e = new ClosedChannelException(); + if (e == null) { + e = new ClosedChannelException(); + } f.completeExceptionally(e); } } @@ -383,9 +407,13 @@ public abstract class ClientConnection implements Co 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; } diff --git a/src/main/java/org/redkale/net/client/ClientFuture.java b/src/main/java/org/redkale/net/client/ClientFuture.java index c81c3c9d4..587a19870 100644 --- a/src/main/java/org/redkale/net/client/ClientFuture.java +++ b/src/main/java/org/redkale/net/client/ClientFuture.java @@ -60,7 +60,9 @@ public class ClientFuture extends CompletableFuture implements Runnable { @Override public void run() { - if (conn == null) return; + if (conn == null) { + return; + } AsyncConnection channel = conn.getChannel(); if (channel.inCurrThread()) { this.runTimeout(); @@ -71,7 +73,9 @@ public class ClientFuture extends CompletableFuture implements Runnable { private void runTimeout() { Queue responseQueue = conn.responseQueue; - if (responseQueue != null) responseQueue.remove(this); + if (responseQueue != null) { + responseQueue.remove(this); + } TimeoutException ex = new TimeoutException(); WorkThread workThread = null; if (request != null) { diff --git a/src/main/java/org/redkale/net/client/ClientResult.java b/src/main/java/org/redkale/net/client/ClientResult.java index e60592a49..97e52862d 100644 --- a/src/main/java/org/redkale/net/client/ClientResult.java +++ b/src/main/java/org/redkale/net/client/ClientResult.java @@ -42,7 +42,9 @@ public class ClientResult

{ @Override public String toString() { - if (exc != null) return "{\"exc\":" + exc + "}"; + if (exc != null) { + return "{\"exc\":" + exc + "}"; + } return "{\"result\":" + result + "}"; } } diff --git a/src/main/java/org/redkale/net/http/HttpDispatcherServlet.java b/src/main/java/org/redkale/net/http/HttpDispatcherServlet.java index 99612e821..65e6be5e9 100644 --- a/src/main/java/org/redkale/net/http/HttpDispatcherServlet.java +++ b/src/main/java/org/redkale/net/http/HttpDispatcherServlet.java @@ -5,16 +5,16 @@ */ package org.redkale.net.http; -import org.redkale.util.AnyValue.DefaultAnyValue; -import java.io.*; +import java.io.IOException; import java.util.*; import java.util.function.*; import java.util.logging.*; -import java.util.regex.*; +import java.util.regex.Pattern; import java.util.stream.Stream; -import org.redkale.net.*; +import org.redkale.net.DispatcherServlet; import org.redkale.net.http.Rest.RestDynSourceType; import org.redkale.service.Service; +import org.redkale.util.AnyValue.DefaultAnyValue; import org.redkale.util.*; /** @@ -81,7 +81,9 @@ public class HttpDispatcherServlet extends DispatcherServlet HttpServlet removeHttpServlet(Service service) { Predicate predicateEntry = (t) -> { - if (!Rest.isRestDyn(t.servlet)) return false; + if (!Rest.isRestDyn(t.servlet)) { + return false; + } Service s = Rest.getService(t.servlet); - if (s == service) return true; - if (s != null) return false; + if (s == service) { + return true; + } + if (s != null) { + return false; + } Map map = Rest.getServiceMap(t.servlet); - if (map == null) return false; + if (map == null) { + return false; + } boolean rs = map.values().contains(service); - if (rs && map.size() == 1) return true; + if (rs && map.size() == 1) { + return true; + } if (rs && map.size() > 1) { String key = null; for (Map.Entry en : map.entrySet()) { @@ -123,7 +135,9 @@ public class HttpDispatcherServlet extends DispatcherServlet HttpServlet removeHttpServlet(Class websocketOrServletType) { Predicate predicateEntry = (t) -> { Class type = t.servlet.getClass(); - if (type == websocketOrServletType) return true; + if (type == websocketOrServletType) { + return true; + } RestDynSourceType rdt = (RestDynSourceType) type.getAnnotation(RestDynSourceType.class); return (rdt != null && rdt.value() == websocketOrServletType); }; Predicate> predicateFilter = (t) -> { Class type = t.getValue().getClass(); - if (type == websocketOrServletType) return true; + if (type == websocketOrServletType) { + return true; + } RestDynSourceType rdt = (RestDynSourceType) type.getAnnotation(RestDynSourceType.class); return (rdt != null && rdt.value() == websocketOrServletType); }; @@ -153,10 +171,16 @@ public class HttpDispatcherServlet extends DispatcherServlet(); + if (forbidURIMaps != null && forbidURIMaps.containsKey(urlRegx)) { + return false; + } + if (forbidURIMaps == null) { + forbidURIMaps = new HashMap<>(); + } String mapping = urlRegx; if (Utility.contains(mapping, '*', '{', '[', '(', '|', '^', '$', '+', '?', '\\')) { //是否是正则表达式)) if (mapping.endsWith("/*")) { @@ -179,9 +203,13 @@ public class HttpDispatcherServlet extends DispatcherServlet predicate = forbidURIMaps.get(urlreg); forbidURIMaps.remove(urlreg); int index = -1; @@ -215,7 +243,9 @@ public class HttpDispatcherServlet extends DispatcherServlet servlets = getServlets(); servlets.forEach(s -> { s.preInit(application, context, getServletConf(s)); - if (application == null || !application.isCompileMode()) s.init(context, getServletConf(s)); + if (application == null || !application.isCompileMode()) { + s.init(context, getServletConf(s)); + } }); { //设置ResourceServlet AnyValue resConfig = config.getAnyValue("resource-servlet"); @@ -252,7 +282,9 @@ public class HttpDispatcherServlet extends DispatcherServlet[] forbidUrlPredicates = this.forbidURIPredicates; @@ -323,25 +357,37 @@ public class HttpDispatcherServlet extends DispatcherServlet { this.localHeader = null; this.localParameter = null; this.rpcAuthenticator = null; - if (req != null) initSimpleRequest(req, true); + if (req != null) { + initSimpleRequest(req, true); + } } protected HttpRequest initSimpleRequest(HttpSimpleRequest req, boolean needPath) { if (req != null) { this.rpc = req.rpc; this.traceid = req.traceid; - if (req.getBody() != null) this.array.put(req.getBody()); - if (req.getHeaders() != null) this.headers.putAll(req.getHeaders()); + if (req.getBody() != null) { + this.array.put(req.getBody()); + } + if (req.getHeaders() != null) { + this.headers.putAll(req.getHeaders()); + } this.frombody = req.isFrombody(); this.reqConvertType = req.getReqConvertType(); this.reqConvert = req.getReqConvertType() == null ? null : ConvertFactory.findConvert(req.getReqConvertType()); this.respConvertType = req.getRespConvertType(); this.respConvert = req.getRespConvertType() == null ? null : ConvertFactory.findConvert(req.getRespConvertType()); - if (req.getParams() != null) this.params.putAll(req.getParams()); + if (req.getParams() != null) { + this.params.putAll(req.getParams()); + } this.hashid = req.getHashid(); - if (req.getCurrentUserid() != null) this.currentUserid = req.getCurrentUserid(); + if (req.getCurrentUserid() != null) { + this.currentUserid = req.getCurrentUserid(); + } this.contentType = req.getContentType(); this.remoteAddr = req.getRemoteAddr(); this.locale = req.getLocale(); @@ -286,7 +295,9 @@ public class HttpRequest extends Request { ByteArray bytes = array; if (this.readState == READ_STATE_ROUTE) { int rs = readMethodLine(buffer); - if (rs != 0) return rs; + if (rs != 0) { + return rs; + } this.readState = READ_STATE_HEADER; } if (this.readState == READ_STATE_HEADER) { @@ -324,7 +335,9 @@ public class HttpRequest extends Request { this.headers.putAll(httplast.headers); } else if (context.lazyHeaders && getmethod) { //非GET必须要读header,会有Content-Length int rs = loadHeaderBytes(buffer); - if (rs != 0) return rs; + if (rs != 0) { + return rs; + } this.headerParsed = false; } else { int startpos = buffer.position(); @@ -340,22 +353,34 @@ public class HttpRequest extends Request { bytes.clear(); this.readState = READ_STATE_BODY; } - if (this.contentType != null && this.contentType.contains("boundary=")) this.boundary = true; - if (this.boundary) this.keepAlive = false; //文件上传必须设置keepAlive为false,因为文件过大时用户不一定会skip掉多余的数据 + if (this.contentType != null && this.contentType.contains("boundary=")) { + this.boundary = true; + } + if (this.boundary) { + this.keepAlive = false; //文件上传必须设置keepAlive为false,因为文件过大时用户不一定会skip掉多余的数据 + } if (this.readState == READ_STATE_BODY) { if (this.contentLength > 0 && (this.contentType == null || !this.boundary)) { - if (this.contentLength > context.getMaxbody()) return -1; + if (this.contentLength > context.getMaxbody()) { + return -1; + } bytes.put(buffer, Math.min((int) this.contentLength, buffer.remaining())); int lr = (int) this.contentLength - bytes.length(); if (lr == 0) { this.readState = READ_STATE_END; - if (bytes.isEmpty()) this.bodyParsed = true; //no body data + if (bytes.isEmpty()) { + this.bodyParsed = true; //no body data + } } return lr > 0 ? lr : 0; } - if (buffer.hasRemaining() && (this.boundary || !this.keepAlive)) bytes.put(buffer, buffer.remaining()); //文件上传、HTTP1.0或Connection:close + if (buffer.hasRemaining() && (this.boundary || !this.keepAlive)) { + bytes.put(buffer, buffer.remaining()); //文件上传、HTTP1.0或Connection:close + } this.readState = READ_STATE_END; - if (bytes.isEmpty()) this.bodyParsed = true; //no body data + if (bytes.isEmpty()) { + this.bodyParsed = true; //no body data + } } //暂不考虑是keep-alive且存在body却没有指定Content-Length的情况 return 0; @@ -390,9 +415,15 @@ public class HttpRequest extends Request { } } } - if (rn1 != 0) buffer.put(rn1); - if (rn2 != 0) buffer.put(rn2); - if (rn3 != 0) buffer.put(rn3); + if (rn1 != 0) { + buffer.put(rn1); + } + if (rn2 != 0) { + buffer.put(rn2); + } + if (rn3 != 0) { + buffer.put(rn3); + } } return 1; } @@ -443,7 +474,9 @@ public class HttpRequest extends Request { return 1; } byte b = buffer.get(); - if (b == ' ') break; + if (b == ' ') { + break; + } bytes.put(b); } size = bytes.length(); @@ -469,7 +502,9 @@ public class HttpRequest extends Request { return 1; } byte b = buffer.get(); - if (b == ' ') break; + if (b == ' ') { + break; + } if (b == '?' && qst < 0) { qst = bytes.length(); } else if (!decodeable && (b == '+' || b == '%')) { @@ -524,7 +559,9 @@ public class HttpRequest extends Request { buffer.put((byte) '\r'); return 1; } - if (buffer.get() != '\n') return -1; + if (buffer.get() != '\n') { + return -1; + } break; } bytes.put(b); @@ -560,7 +597,9 @@ public class HttpRequest extends Request { remain--; byte b1 = buffer.get(); byte b2 = buffer.get(); - if (b1 == '\r' && b2 == '\n') return 0; + if (b1 == '\r' && b2 == '\n') { + return 0; + } bytes.put(b1, b2); for (;;) { // name if (remain-- < 1) { @@ -569,7 +608,9 @@ public class HttpRequest extends Request { return 1; } byte b = buffer.get(); - if (b == ':') break; + if (b == ':') { + break; + } bytes.put(b); } String name = parseHeaderName(bytes, charset); @@ -604,7 +645,9 @@ public class HttpRequest extends Request { buffer.put((byte) '\r'); return 1; } - if (buffer.get() != '\n') return -1; + if (buffer.get() != '\n') { + return -1; + } break; } if (first) { @@ -716,9 +759,13 @@ public class HttpRequest extends Request { } private void parseHeader() { - if (headerParsed) return; + if (headerParsed) { + return; + } headerParsed = true; - if (headerBytes == null) return; + if (headerBytes == null) { + return; + } if (array.isEmpty()) { readHeaderLines(ByteBuffer.wrap(headerBytes), array); array.clear(); @@ -732,23 +779,33 @@ public class HttpRequest extends Request { final byte[] bs = bytes.content(); final byte first = bs[0]; if (first == 'H' && size == 4) { //Host - if (bs[1] == 'o' && bs[2] == 's' && bs[3] == 't') return KEY_HOST; + if (bs[1] == 'o' && bs[2] == 's' && bs[3] == 't') { + return KEY_HOST; + } } else if (first == 'A' && size == 6) { //Accept if (bs[1] == 'c' && bs[2] == 'c' && bs[3] == 'e' - && bs[4] == 'p' && bs[5] == 't') return KEY_ACCEPT; + && bs[4] == 'p' && bs[5] == 't') { + return KEY_ACCEPT; + } } else if (first == 'C') { if (size == 10) { //Connection if (bs[1] == 'o' && bs[2] == 'n' && bs[3] == 'n' && bs[4] == 'e' && bs[5] == 'c' && bs[6] == 't' - && bs[7] == 'i' && bs[8] == 'o' && bs[9] == 'n') return KEY_CONNECTION; + && bs[7] == 'i' && bs[8] == 'o' && bs[9] == 'n') { + return KEY_CONNECTION; + } } else if (size == 12) { //Content-Type if (bs[1] == 'o' && bs[2] == 'n' && bs[3] == 't' && bs[4] == 'e' && bs[5] == 'n' && bs[6] == 't' && bs[7] == '-' && bs[8] == 'T' && bs[9] == 'y' - && bs[10] == 'p' && bs[11] == 'e') return KEY_CONTENT_TYPE; + && bs[10] == 'p' && bs[11] == 'e') { + return KEY_CONTENT_TYPE; + } } else if (size == 6) { //Cookie if (bs[1] == 'o' && bs[2] == 'o' && bs[3] == 'k' - && bs[4] == 'i' && bs[5] == 'e') return KEY_COOKIE; + && bs[4] == 'i' && bs[5] == 'e') { + return KEY_COOKIE; + } } } return bytes.toString(charset); @@ -756,7 +813,9 @@ public class HttpRequest extends Request { @Override protected HttpRequest copyHeader() { - if (!pipelineSameHeaders || !context.lazyHeaders) return null; + if (!pipelineSameHeaders || !context.lazyHeaders) { + return null; + } HttpRequest req = new HttpRequest(context, this.array); req.headerLength = this.headerLength; req.headerBytes = this.headerBytes; @@ -835,7 +894,9 @@ public class HttpRequest extends Request { } private void parseBody() { - if (this.boundary || bodyParsed) return; + if (this.boundary || bodyParsed) { + return; + } bodyParsed = true; if (this.contentType != null && this.contentType.toLowerCase().contains("x-www-form-urlencoded")) { addParameter(array, 0, array.length()); @@ -843,17 +904,23 @@ public class HttpRequest extends Request { } private void addParameter(final ByteArray array, final int offset, final int len) { - if (len < 1) return; + if (len < 1) { + return; + } Charset charset = this.context.getCharset(); int limit = offset + len; int keypos = array.find(offset, limit, '='); int valpos = array.find(offset, limit, '&'); if (keypos <= 0 || (valpos >= 0 && valpos < keypos)) { - if (valpos > 0) addParameter(array, valpos + 1, limit - valpos - 1); + if (valpos > 0) { + addParameter(array, valpos + 1, limit - valpos - 1); + } return; } String name = toDecodeString(array, offset, keypos - offset, charset); - if (!name.isEmpty() && name.charAt(0) == '<') return; //内容可能是xml格式; 如: { } private static int hexBit(byte b) { - if ('0' <= b && '9' >= b) return b - '0'; - if ('a' <= b && 'z' >= b) return b - 'a' + 10; - if ('A' <= b && 'Z' >= b) return b - 'A' + 10; + if ('0' <= b && '9' >= b) { + return b - '0'; + } + if ('a' <= b && 'z' >= b) { + return b - 'a' + 10; + } + if ('A' <= b && 'Z' >= b) { + return b - 'A' + 10; + } return b; } @@ -976,8 +1049,12 @@ public class HttpRequest extends Request { */ @SuppressWarnings("unchecked") public int currentIntUserid() { - if (currentUserid == CURRUSERID_NIL || currentUserid == null) return 0; - if (this.currentUserid instanceof Number) return ((Number) this.currentUserid).intValue(); + if (currentUserid == CURRUSERID_NIL || currentUserid == null) { + return 0; + } + if (this.currentUserid instanceof Number) { + return ((Number) this.currentUserid).intValue(); + } String uid = this.currentUserid.toString(); return uid.isEmpty() ? 0 : Integer.parseInt(uid); } @@ -991,8 +1068,12 @@ public class HttpRequest extends Request { */ @SuppressWarnings("unchecked") public long currentLongUserid() { - if (currentUserid == CURRUSERID_NIL || currentUserid == null) return 0L; - if (this.currentUserid instanceof Number) return ((Number) this.currentUserid).longValue(); + if (currentUserid == CURRUSERID_NIL || currentUserid == null) { + return 0L; + } + if (this.currentUserid instanceof Number) { + return ((Number) this.currentUserid).longValue(); + } String uid = this.currentUserid.toString(); return uid.isEmpty() ? 0L : Long.parseLong(uid); } @@ -1010,22 +1091,34 @@ public class HttpRequest extends Request { @SuppressWarnings("unchecked") public T currentUserid(Class type) { if (currentUserid == CURRUSERID_NIL || currentUserid == null) { - if (type == int.class || type == Integer.class) return (T) (Integer) (int) 0; - if (type == long.class || type == Long.class) return (T) (Long) (long) 0; + if (type == int.class || type == Integer.class) { + return (T) (Integer) (int) 0; + } + if (type == long.class || type == Long.class) { + return (T) (Long) (long) 0; + } return null; } if (type == int.class || type == Integer.class) { - if (this.currentUserid instanceof Number) return (T) (Integer) ((Number) this.currentUserid).intValue(); + if (this.currentUserid instanceof Number) { + return (T) (Integer) ((Number) this.currentUserid).intValue(); + } String uid = this.currentUserid.toString(); return (T) (Integer) (uid.isEmpty() ? 0 : Integer.parseInt(uid)); } if (type == long.class || type == Long.class) { - if (this.currentUserid instanceof Number) return (T) (Long) ((Number) this.currentUserid).longValue(); + if (this.currentUserid instanceof Number) { + return (T) (Long) ((Number) this.currentUserid).longValue(); + } String uid = this.currentUserid.toString(); return (T) (Long) (uid.isEmpty() ? 0L : Long.parseLong(uid)); } - if (type == String.class) return (T) this.currentUserid.toString(); - if (this.currentUserid instanceof CharSequence) return JsonConvert.root().convertFrom(type, this.currentUserid.toString()); + if (type == String.class) { + return (T) this.currentUserid.toString(); + } + if (this.currentUserid instanceof CharSequence) { + return JsonConvert.root().convertFrom(type, this.currentUserid.toString()); + } return (T) this.currentUserid; } @@ -1087,7 +1180,9 @@ public class HttpRequest extends Request { */ @ConvertDisabled public Annotation[] getAnnotations() { - if (this.annotations == null) return new Annotation[0]; + if (this.annotations == null) { + return new Annotation[0]; + } Annotation[] newanns = new Annotation[this.annotations.length]; System.arraycopy(this.annotations, 0, newanns, 0, newanns.length); return newanns; @@ -1102,9 +1197,13 @@ public class HttpRequest extends Request { * @return Annotation */ public T getAnnotation(Class annotationClass) { - if (this.annotations == null) return null; + if (this.annotations == null) { + return null; + } for (Annotation ann : this.annotations) { - if (ann.getClass() == annotationClass) return (T) ann; + if (ann.getClass() == annotationClass) { + return (T) ann; + } } return null; } @@ -1118,7 +1217,9 @@ public class HttpRequest extends Request { * @return Annotation[] */ public T[] getAnnotationsByType(Class annotationClass) { - if (this.annotations == null) return (T[]) Array.newInstance(annotationClass, 0); + if (this.annotations == null) { + return (T[]) Array.newInstance(annotationClass, 0); + } T[] news = (T[]) Array.newInstance(annotationClass, this.annotations.length); int index = 0; for (Annotation ann : this.annotations) { @@ -1126,7 +1227,9 @@ public class HttpRequest extends Request { news[index++] = (T) ann; } } - if (index < 1) return (T[]) Array.newInstance(annotationClass, 0); + if (index < 1) { + return (T[]) Array.newInstance(annotationClass, 0); + } return Arrays.copyOf(news, index); } @@ -1147,7 +1250,9 @@ public class HttpRequest extends Request { * @return 地址 */ public String getRemoteAddr() { - if (this.remoteAddr != null) return this.remoteAddr; + if (this.remoteAddr != null) { + return this.remoteAddr; + } parseHeader(); if (remoteAddrHeader != null) { String val = getHeader(remoteAddrHeader); @@ -1157,7 +1262,9 @@ public class HttpRequest extends Request { } } SocketAddress addr = getRemoteAddress(); - if (addr == null) return ""; + if (addr == null) { + return ""; + } if (addr instanceof InetSocketAddress) { this.remoteAddr = ((InetSocketAddress) addr).getAddress().getHostAddress(); return this.remoteAddr; @@ -1172,7 +1279,9 @@ public class HttpRequest extends Request { * @return 国际化Locale */ public String getLocale() { - if (this.locale != null) return this.locale; + if (this.locale != null) { + return this.locale; + } if (localHeader != null) { String val = getHeader(localHeader); if (val != null) { @@ -1220,10 +1329,16 @@ public class HttpRequest extends Request { * @return 内容 */ public T getBodyJson(java.lang.reflect.Type type) { - if (array == null || array.isEmpty()) return null; + if (array == null || array.isEmpty()) { + return null; + } Convert convert = this.reqConvert; - if (convert == null) convert = context.getJsonConvert(); - if (type == byte[].class) return (T) array.getBytes(); + if (convert == null) { + convert = context.getJsonConvert(); + } + if (type == byte[].class) { + return (T) array.getBytes(); + } return (T) convert.convertFrom(type, array.content()); } @@ -1237,8 +1352,12 @@ public class HttpRequest extends Request { * @return 内容 */ public T getBodyJson(Convert convert, java.lang.reflect.Type type) { - if (array.isEmpty()) return null; - if (type == byte[].class) return (T) array.getBytes(); + if (array.isEmpty()) { + return null; + } + if (type == byte[].class) { + return (T) array.getBytes(); + } return (T) convert.convertFrom(type, array.content()); } @@ -1378,7 +1497,9 @@ public class HttpRequest extends Request { */ public HttpCookie[] getCookies() { parseHeader(); - if (this.cookies == null) this.cookies = parseCookies(this.cookie); + if (this.cookies == null) { + this.cookies = parseCookies(this.cookie); + } return this.cookies.length == 0 ? null : this.cookies; } @@ -1403,24 +1524,34 @@ public class HttpRequest extends Request { */ public String getCookie(String name, String dfvalue) { HttpCookie[] cs = getCookies(); - if (cs == null) return dfvalue; + if (cs == null) { + return dfvalue; + } for (HttpCookie c : cs) { - if (name.equals(c.getName())) return c.getValue(); + if (name.equals(c.getName())) { + return c.getValue(); + } } return dfvalue; } private static HttpCookie[] parseCookies(String cookiestr) { - if (cookiestr == null || cookiestr.isEmpty()) return new HttpCookie[0]; + if (cookiestr == null || cookiestr.isEmpty()) { + return new HttpCookie[0]; + } String str = cookiestr.replaceAll("(^;)|(;$)", "").replaceAll(";+", ";"); - if (str.isEmpty()) return new HttpCookie[0]; + if (str.isEmpty()) { + return new HttpCookie[0]; + } String[] strs = str.split(";"); HttpCookie[] cookies = new HttpCookie[strs.length]; for (int i = 0; i < strs.length; i++) { String s = strs[i]; int pos = s.indexOf('='); String v = (pos < 0 ? "" : s.substring(pos + 1)); - if (v.indexOf('"') == 0 && v.lastIndexOf('"') == v.length() - 1) v = v.substring(1, v.length() - 1); + if (v.indexOf('"') == 0 && v.lastIndexOf('"') == v.length() - 1) { + v = v.substring(1, v.length() - 1); + } cookies[i] = new HttpCookie((pos < 0 ? s : s.substring(0, pos)), v); } return cookies; @@ -1496,7 +1627,9 @@ public class HttpRequest extends Request { */ @ConvertDisabled public String getRequstURILastPath() { - if (requestURI == null) return ""; + if (requestURI == null) { + return ""; + } return requestURI.substring(requestURI.lastIndexOf('/') + 1); } @@ -1511,7 +1644,9 @@ public class HttpRequest extends Request { */ public short getRequstURILastPath(short defvalue) { String val = getRequstURILastPath(); - if (val.isEmpty()) return defvalue; + if (val.isEmpty()) { + return defvalue; + } try { return Short.parseShort(val); } catch (NumberFormatException e) { @@ -1531,7 +1666,9 @@ public class HttpRequest extends Request { */ public short getRequstURILastPath(int radix, short defvalue) { String val = getRequstURILastPath(); - if (val.isEmpty()) return defvalue; + if (val.isEmpty()) { + return defvalue; + } try { return Short.parseShort(val, radix); } catch (NumberFormatException e) { @@ -1658,7 +1795,9 @@ public class HttpRequest extends Request { * @return String[] */ public String[] getRequstURIPaths(String prefix) { - if (requestURI == null || prefix == null) return new String[0]; + if (requestURI == null || prefix == null) { + return new String[0]; + } return requestURI.substring(requestURI.indexOf(prefix) + prefix.length() + (prefix.endsWith("/") ? 0 : 1)).split("/"); } @@ -1673,9 +1812,13 @@ public class HttpRequest extends Request { * @return prefix截断后的值 */ public String getRequstURIPath(String prefix, String defvalue) { - if (requestURI == null || prefix == null || prefix.isEmpty()) return defvalue; + if (requestURI == null || prefix == null || prefix.isEmpty()) { + return defvalue; + } int pos = requestURI.indexOf(prefix); - if (pos < 0) return defvalue; + if (pos < 0) { + return defvalue; + } String sub = requestURI.substring(pos + prefix.length()); pos = sub.indexOf('/'); return pos < 0 ? sub : sub.substring(0, pos); @@ -1859,7 +2002,9 @@ public class HttpRequest extends Request { @ConvertDisabled public Map getHeadersToMap(Map map) { parseHeader(); - if (map == null) map = new LinkedHashMap<>(); + if (map == null) { + map = new LinkedHashMap<>(); + } final Map map0 = map; headers.forEach((k, v) -> map0.put(k, v)); return map0; @@ -1958,7 +2103,9 @@ public class HttpRequest extends Request { //return headers.getShortValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Short.decode(value); } catch (NumberFormatException e) { @@ -1979,7 +2126,9 @@ public class HttpRequest extends Request { //return headers.getShortValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Short.decode(value) : Short.parseShort(value, radix)); } catch (NumberFormatException e) { @@ -1999,7 +2148,9 @@ public class HttpRequest extends Request { //return headers.getShortValue(name, (short) defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return (short) defaultValue; + if (value == null || value.length() == 0) { + return (short) defaultValue; + } try { return Short.decode(value); } catch (NumberFormatException e) { @@ -2020,7 +2171,9 @@ public class HttpRequest extends Request { //return headers.getShortValue(radix, name, (short) defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return (short) defaultValue; + if (value == null || value.length() == 0) { + return (short) defaultValue; + } try { return (radix == 10 ? Short.decode(value) : Short.parseShort(value, radix)); } catch (NumberFormatException e) { @@ -2040,7 +2193,9 @@ public class HttpRequest extends Request { //return headers.getIntValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Integer.parseInt(value); } catch (NumberFormatException e) { @@ -2061,7 +2216,9 @@ public class HttpRequest extends Request { //return headers.getIntValue(radix, name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Integer.decode(value) : Integer.parseInt(value, radix)); } catch (NumberFormatException e) { @@ -2081,7 +2238,9 @@ public class HttpRequest extends Request { //return headers.getLongValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Long.decode(value); } catch (NumberFormatException e) { @@ -2102,7 +2261,9 @@ public class HttpRequest extends Request { //return headers.getLongValue(radix, name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Long.decode(value) : Long.parseLong(value, radix)); } catch (NumberFormatException e) { @@ -2122,7 +2283,9 @@ public class HttpRequest extends Request { //return headers.getFloatValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Float.parseFloat(value); } catch (NumberFormatException e) { @@ -2142,7 +2305,9 @@ public class HttpRequest extends Request { //return headers.getDoubleValue(name, defaultValue); parseHeader(); String value = headers.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Double.parseDouble(value); } catch (NumberFormatException e) { @@ -2170,7 +2335,9 @@ public class HttpRequest extends Request { */ @ConvertDisabled public Map getParametersToMap(Map map) { - if (map == null) map = new LinkedHashMap<>(); + if (map == null) { + map = new LinkedHashMap<>(); + } final Map map0 = map; getParameters().forEach((k, v) -> map0.put(k, v)); return map0; @@ -2198,7 +2365,9 @@ public class HttpRequest extends Request { */ public String getParametersToString(String prefix) { byte[] rbs = queryBytes; - if (rbs == null || rbs.length < 1) return ""; + if (rbs == null || rbs.length < 1) { + return ""; + } Charset charset = this.context.getCharset(); String str = charset == null ? new String(rbs, StandardCharsets.UTF_8) : new String(rbs, charset); return (prefix == null) ? str : (prefix + str); @@ -2225,9 +2394,13 @@ public class HttpRequest extends Request { */ public String getParameter(String name) { if (this.frombody) { - if (array.isEmpty()) return null; + if (array.isEmpty()) { + return null; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (String) convert.convertFrom(String.class, array.content()); } parseBody(); @@ -2244,9 +2417,13 @@ public class HttpRequest extends Request { */ public String getParameter(String name, String defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (String) convert.convertFrom(String.class, array.content()); } parseBody(); @@ -2264,10 +2441,16 @@ public class HttpRequest extends Request { */ public T getJsonParameter(java.lang.reflect.Type type, String name) { if (this.frombody) { - if (array.isEmpty()) return null; + if (array.isEmpty()) { + return null; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; - if (type == byte[].class) return (T) array.getBytes(); + if (convert == null) { + convert = jsonConvert; + } + if (type == byte[].class) { + return (T) array.getBytes(); + } return (T) convert.convertFrom(type, array.content()); } String v = getParameter(name); @@ -2299,9 +2482,13 @@ public class HttpRequest extends Request { */ public boolean getBooleanParameter(String name, boolean defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (boolean) convert.convertFrom(boolean.class, array.content()); } parseBody(); @@ -2319,14 +2506,20 @@ public class HttpRequest extends Request { */ public short getShortParameter(String name, short defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (short) convert.convertFrom(short.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Short.decode(value); } catch (NumberFormatException e) { @@ -2345,14 +2538,20 @@ public class HttpRequest extends Request { */ public short getShortParameter(int radix, String name, short defaultValue) { if (this.frombody) { - if (array.isEmpty()) return (short) defaultValue; + if (array.isEmpty()) { + return (short) defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (short) convert.convertFrom(short.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Short.decode(value) : Short.parseShort(value, radix)); } catch (NumberFormatException e) { @@ -2370,14 +2569,20 @@ public class HttpRequest extends Request { */ public short getShortParameter(String name, int defaultValue) { if (this.frombody) { - if (array.isEmpty()) return (short) defaultValue; + if (array.isEmpty()) { + return (short) defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (short) convert.convertFrom(short.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return (short) defaultValue; + if (value == null || value.length() == 0) { + return (short) defaultValue; + } try { return Short.decode(value); } catch (NumberFormatException e) { @@ -2395,14 +2600,20 @@ public class HttpRequest extends Request { */ public int getIntParameter(String name, int defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (int) convert.convertFrom(int.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Integer.decode(value); } catch (NumberFormatException e) { @@ -2421,14 +2632,20 @@ public class HttpRequest extends Request { */ public int getIntParameter(int radix, String name, int defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (int) convert.convertFrom(int.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Integer.decode(value) : Integer.parseInt(value, radix)); } catch (NumberFormatException e) { @@ -2446,14 +2663,20 @@ public class HttpRequest extends Request { */ public long getLongParameter(String name, long defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (long) convert.convertFrom(long.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Long.decode(value); } catch (NumberFormatException e) { @@ -2472,14 +2695,20 @@ public class HttpRequest extends Request { */ public long getLongParameter(int radix, String name, long defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (long) convert.convertFrom(long.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Long.decode(value) : Long.parseLong(value, radix)); } catch (NumberFormatException e) { @@ -2497,14 +2726,20 @@ public class HttpRequest extends Request { */ public float getFloatParameter(String name, float defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (float) convert.convertFrom(float.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Float.parseFloat(value); } catch (NumberFormatException e) { @@ -2522,14 +2757,20 @@ public class HttpRequest extends Request { */ public double getDoubleParameter(String name, double defaultValue) { if (this.frombody) { - if (array.isEmpty()) return defaultValue; + if (array.isEmpty()) { + return defaultValue; + } Convert convert = this.reqConvert; - if (convert == null) convert = jsonConvert; + if (convert == null) { + convert = jsonConvert; + } return (double) convert.convertFrom(double.class, array.content()); } parseBody(); String value = params.get(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Double.parseDouble(value); } catch (NumberFormatException e) { @@ -2608,8 +2849,12 @@ public class HttpRequest extends Request { } else if (flipper.getLimit() < 1 || (maxLimit > 0 && flipper.getLimit() > maxLimit)) { flipper.setLimit(maxLimit); } - if (flipper != null || !autoCreate) return flipper; - if (maxLimit < 1) maxLimit = org.redkale.source.Flipper.DEFAULT_LIMIT; + if (flipper != null || !autoCreate) { + return flipper; + } + if (maxLimit < 1) { + maxLimit = org.redkale.source.Flipper.DEFAULT_LIMIT; + } return new org.redkale.source.Flipper(maxLimit); } } diff --git a/src/main/java/org/redkale/net/http/HttpResourceServlet.java b/src/main/java/org/redkale/net/http/HttpResourceServlet.java index 54d7deb65..d35d17cac 100644 --- a/src/main/java/org/redkale/net/http/HttpResourceServlet.java +++ b/src/main/java/org/redkale/net/http/HttpResourceServlet.java @@ -8,6 +8,7 @@ package org.redkale.net.http; import java.io.*; import static java.nio.file.StandardWatchEventKinds.*; import java.nio.file.*; +import static java.nio.file.StandardWatchEventKinds.*; import java.util.AbstractMap.SimpleEntry; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -59,7 +60,9 @@ public class HttpResourceServlet extends HttpServlet { //logger.log(Level.FINEST, "file(" + uri + ") happen " + event.kind() + " event"); if (event.kind() == ENTRY_DELETE) { FileEntry en = files.remove(uri); - if (en != null) en.remove(); + if (en != null) { + en.remove(); + } } else if (event.kind() == ENTRY_MODIFY) { FileEntry en = files.get(uri); if (en != null && en.file != null) { @@ -67,7 +70,9 @@ public class HttpResourceServlet extends HttpServlet { for (;;) { d = en.file.lastModified(); Thread.sleep(2000L); - if (d == en.file.lastModified()) break; + if (d == en.file.lastModified()) { + break; + } } en.update(); } @@ -139,7 +144,9 @@ public class HttpResourceServlet extends HttpServlet { } this.locationRewrites = locations.isEmpty() ? null : locations.toArray(new SimpleEntry[locations.size()]); } - if (this.cachelimit < 1) return; //不缓存不需要开启WatchThread监听 + if (this.cachelimit < 1) { + return; //不缓存不需要开启WatchThread监听 + } if (this.root != null && this.watch) { try { this.watchThread = new WatchThread(this.root); @@ -158,12 +165,16 @@ public class HttpResourceServlet extends HttpServlet { } catch (IOException ex) { logger.log(Level.WARNING, HttpResourceServlet.class.getSimpleName() + " close watch-thread error", ex); } - if (this.watchThread.isAlive()) this.watchThread.interrupt(); + if (this.watchThread.isAlive()) { + this.watchThread.interrupt(); + } } } public void setRoot(String rootstr) { - if (rootstr == null) return; + if (rootstr == null) { + return; + } try { this.root = new File(rootstr).getCanonicalFile(); } catch (IOException ioe) { @@ -172,7 +183,9 @@ public class HttpResourceServlet extends HttpServlet { } public void setRoot(File file) { - if (file == null) return; + if (file == null) { + return; + } try { this.root = file.getCanonicalFile(); } catch (IOException ioe) { @@ -181,11 +194,19 @@ public class HttpResourceServlet extends HttpServlet { } protected static long parseLenth(String value, long defValue) { - if (value == null) return defValue; + if (value == null) { + return defValue; + } value = value.toUpperCase().replace("B", ""); - if (value.endsWith("G")) return Long.decode(value.replace("G", "")) * 1024 * 1024 * 1024; - if (value.endsWith("M")) return Long.decode(value.replace("M", "")) * 1024 * 1024; - if (value.endsWith("K")) return Long.decode(value.replace("K", "")) * 1024; + if (value.endsWith("G")) { + return Long.decode(value.replace("G", "")) * 1024 * 1024 * 1024; + } + if (value.endsWith("M")) { + return Long.decode(value.replace("M", "")) * 1024 * 1024; + } + if (value.endsWith("K")) { + return Long.decode(value.replace("K", "")) * 1024; + } return Long.decode(value); } @@ -193,7 +214,9 @@ public class HttpResourceServlet extends HttpServlet { public void execute(HttpRequest request, HttpResponse response) throws IOException { String uri = request.getRequestURI(); if (uri.contains("../")) { - if (logger.isLoggable(Level.FINEST)) logger.log(Level.FINEST, "Not found resource (404) be " + uri + ", request = " + request); + if (logger.isLoggable(Level.FINEST)) { + logger.log(Level.FINEST, "Not found resource (404) be " + uri + ", request = " + request); + } finish404(request, response); return; } @@ -230,7 +253,9 @@ public class HttpResourceServlet extends HttpServlet { entry = files.computeIfAbsent(uri, x -> createFileEntry(x)); } if (entry == null) { - if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "Not found resource (404), url = " + request.getRequestURI()); + if (logger.isLoggable(Level.FINER)) { + logger.log(Level.FINER, "Not found resource (404), url = " + request.getRequestURI()); + } finish404(request, response); } else { //file = null 表示资源内容在内存而不是在File中 @@ -242,11 +267,19 @@ public class HttpResourceServlet extends HttpServlet { protected FileEntry createFileEntry(String uri) { File rfile = new File(root, uri); File file = rfile; - if (file.isDirectory()) file = new File(rfile, this.indexHtml); - if (file.isDirectory()) file = new File(rfile, "index.html"); - if (!file.isFile() || !file.canRead()) return null; + if (file.isDirectory()) { + file = new File(rfile, this.indexHtml); + } + if (file.isDirectory()) { + file = new File(rfile, "index.html"); + } + if (!file.isFile() || !file.canRead()) { + return null; + } FileEntry en = new FileEntry(this, file); - if (watchThread == null) return en; + if (watchThread == null) { + return en; + } try { Path p = file.getParentFile().toPath(); keymaps.put(p.register(watchThread.watcher, ENTRY_MODIFY, ENTRY_DELETE), p); @@ -297,14 +330,20 @@ public class HttpResourceServlet extends HttpServlet { } public void update() { - if (this.file == null) return; + if (this.file == null) { + return; + } if (this.content != null) { this.servlet.cachedLength.add(0L - this.content.length()); this.content = null; } long length = this.file.length(); - if (length > this.servlet.cachelengthmax) return; - if (this.servlet.cachedLength.longValue() + length > this.servlet.cachelimit) return; //超过缓存总容量 + if (length > this.servlet.cachelengthmax) { + return; + } + if (this.servlet.cachedLength.longValue() + length > this.servlet.cachelimit) { + return; //超过缓存总容量 + } try { FileInputStream in = new FileInputStream(file); ByteArray out = new ByteArray((int) file.length()); @@ -322,7 +361,9 @@ public class HttpResourceServlet extends HttpServlet { } public void remove() { - if (this.content != null) this.servlet.cachedLength.add(0L - this.content.length()); + if (this.content != null) { + this.servlet.cachedLength.add(0L - this.content.length()); + } } public long getCachedLength() { diff --git a/src/main/java/org/redkale/net/http/HttpResponse.java b/src/main/java/org/redkale/net/http/HttpResponse.java index 555c8199c..6b00c48b8 100644 --- a/src/main/java/org/redkale/net/http/HttpResponse.java +++ b/src/main/java/org/redkale/net/http/HttpResponse.java @@ -10,7 +10,7 @@ import java.lang.reflect.Type; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.*; -import java.nio.file.*; +import java.nio.file.StandardOpenOption; import java.time.ZoneId; import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; import java.util.*; @@ -337,7 +337,9 @@ public class HttpResponse extends Response { */ @SuppressWarnings("unchecked") public H createAsyncHandler(Class handlerClass) { - if (handlerClass == null || handlerClass == CompletionHandler.class) return (H) createAsyncHandler(); + if (handlerClass == null || handlerClass == CompletionHandler.class) { + return (H) createAsyncHandler(); + } return context.loadAsyncHandlerCreator(handlerClass).create(createAsyncHandler()); } @@ -348,7 +350,9 @@ public class HttpResponse extends Response { */ public void finishJson(final Object obj) { this.contentType = this.jsonContentType; - if (this.recycleListener != null) this.output = obj; + if (this.recycleListener != null) { + this.output = obj; + } Convert c = request.getRespConvert(); if (c == jsonRootConvert) { JsonBytesWriter writer = jsonWriter; @@ -367,7 +371,9 @@ public class HttpResponse extends Response { */ public void finishJson(final JsonConvert convert, final Object obj) { this.contentType = this.jsonContentType; - if (this.recycleListener != null) this.output = obj; + if (this.recycleListener != null) { + this.output = obj; + } if (convert == jsonRootConvert) { JsonBytesWriter writer = jsonWriter; convert.convertTo(writer.clear(), obj); @@ -385,7 +391,9 @@ public class HttpResponse extends Response { */ public void finishJson(final Type type, final Object obj) { this.contentType = this.jsonContentType; - if (this.recycleListener != null) this.output = obj; + if (this.recycleListener != null) { + this.output = obj; + } Convert c = request.getRespConvert(); if (c == jsonRootConvert) { JsonBytesWriter writer = jsonWriter; @@ -405,7 +413,9 @@ public class HttpResponse extends Response { */ public void finishJson(final JsonConvert convert, final Type type, final Object obj) { this.contentType = this.jsonContentType; - if (this.recycleListener != null) this.output = obj; + if (this.recycleListener != null) { + this.output = obj; + } if (convert == jsonRootConvert) { JsonBytesWriter writer = jsonWriter; convert.convertTo(writer.clear(), type, obj); @@ -502,13 +512,17 @@ public class HttpResponse extends Response { if (this.retResultHandler != null) { ret = this.retResultHandler.apply(this.request, ret); } - if (this.recycleListener != null) this.output = ret; + if (this.recycleListener != null) { + this.output = ret; + } if (ret != null && !ret.isSuccess()) { this.header.addValue("retcode", String.valueOf(ret.getRetcode())); this.header.addValue("retinfo", ret.getRetinfo()); } Convert cc = ret == null ? null : ret.convert(); - if (cc == null) cc = request.getRespConvert(); + if (cc == null) { + cc = request.getRespConvert(); + } if (cc instanceof JsonConvert) { this.contentType = this.jsonContentType; } else if (cc instanceof TextConvert) { @@ -535,14 +549,20 @@ public class HttpResponse extends Response { if (this.retResultHandler != null) { ret = this.retResultHandler.apply(this.request, ret); } - if (this.recycleListener != null) this.output = ret; + if (this.recycleListener != null) { + this.output = ret; + } if (ret != null && !ret.isSuccess()) { this.header.addValue("retcode", String.valueOf(ret.getRetcode())); this.header.addValue("retinfo", ret.getRetinfo()); } Convert cc = convert; - if (cc == null && ret != null) cc = ret.convert(); - if (cc == null) cc = request.getRespConvert(); + if (cc == null && ret != null) { + cc = ret.convert(); + } + if (cc == null) { + cc = request.getRespConvert(); + } if (cc instanceof JsonConvert) { this.contentType = this.jsonContentType; } else if (cc instanceof TextConvert) { @@ -575,7 +595,9 @@ public class HttpResponse extends Response { * @param result HttpResult输出对象 */ public void finish(final Convert convert, Type resultType, HttpResult result) { - if (result.getContentType() != null) setContentType(result.getContentType()); + if (result.getContentType() != null) { + setContentType(result.getContentType()); + } addHeader(result.getHeaders()).addCookie(result.getCookies()).setStatus(result.getStatus() < 1 ? 200 : result.getStatus()); Object val = result.getResult(); if (val == null) { @@ -584,7 +606,9 @@ public class HttpResponse extends Response { finish(getStatus(), val.toString()); } else { Convert cc = result.convert(); - if (cc == null) cc = convert; + if (cc == null) { + cc = convert; + } finish(cc, resultType, val); } } @@ -717,8 +741,12 @@ public class HttpResponse extends Response { } if (httpRender != null) { setContentType(contentTypeHtmlUTF8); - if (result.getHeaders() != null) addHeader(result.getHeaders()); - if (result.getCookies() != null) addCookie(result.getCookies()); + if (result.getHeaders() != null) { + addHeader(result.getHeaders()); + } + if (result.getCookies() != null) { + addCookie(result.getCookies()); + } httpRender.renderTo(this.request, this, convert, result); return; } @@ -770,7 +798,9 @@ public class HttpResponse extends Response { //以下if条件会被Rest类第2440行左右的地方用到 if (val == null) { Convert cc = convert; - if (cc == null) cc = request.getRespConvert(); + if (cc == null) { + cc = request.getRespConvert(); + } if (cc instanceof JsonConvert) { this.contentType = this.jsonContentType; } else if (cc instanceof TextConvert) { @@ -798,13 +828,17 @@ public class HttpResponse extends Response { finish(convert, (HttpScope) val); } else { Convert cc = convert; - if (cc == null) cc = request.getRespConvert(); + if (cc == null) { + cc = request.getRespConvert(); + } if (cc instanceof JsonConvert) { this.contentType = this.jsonContentType; } else if (cc instanceof TextConvert) { this.contentType = this.plainContentType; } - if (this.recycleListener != null) this.output = val; + if (this.recycleListener != null) { + this.output = val; + } //this.channel == null为虚拟的HttpResponse if (type == null) { if (cc == jsonRootConvert) { @@ -842,7 +876,9 @@ public class HttpResponse extends Response { * @param message 输出内容 */ public void finish(int status, String message) { - if (isClosed()) return; + if (isClosed()) { + return; + } this.status = status; //if (status != 200) super.refuseAlive(); final byte[] val = message == null ? HttpRequest.EMPTY_BYTES : (context.getCharset() == null ? Utility.encodeUTF8(message) : message.getBytes(context.getCharset())); @@ -904,16 +940,24 @@ public class HttpResponse extends Response { * @param A */ protected void finish(boolean kill, final String contentType, final byte[] bs, int offset, int length, Consumer callback, A attachment) { - if (isClosed()) return; //避免重复关闭 + if (isClosed()) { + return; //避免重复关闭 + } if (this.headWritedSize < 0) { - if (contentType != null) this.contentType = contentType; + if (contentType != null) { + this.contentType = contentType; + } this.contentLength = length; createHeader(); } ByteArray data = headerArray; data.put(bs, offset, length); - if (callback != null) callback.accept(attachment); - if (cacheHandler != null) cacheHandler.accept(this, data.getBytes()); + if (callback != null) { + callback.accept(attachment); + } + if (cacheHandler != null) { + cacheHandler.accept(this, data.getBytes()); + } int pipelineIndex = request.getPipelineIndex(); if (pipelineIndex > 0) { @@ -1015,7 +1059,9 @@ public class HttpResponse extends Response { headerArray.put(serverNameBytes); if (!this.respHeadContainsConnection) { byte[] bs = this.request.isKeepAlive() ? connectAliveBytes : connectCloseBytes; - if (bs.length > 0) headerArray.put(bs); + if (bs.length > 0) { + headerArray.put(bs); + } } } if (!this.request.isWebSocket()) { @@ -1035,16 +1081,22 @@ public class HttpResponse extends Response { } } } - if (dateSupplier != null) headerArray.put(dateSupplier.get()); + if (dateSupplier != null) { + headerArray.put(dateSupplier.get()); + } if (this.defaultAddHeaders != null) { for (String[] headers : this.defaultAddHeaders) { if (headers.length > 3) { String v = request.getParameter(headers[2]); - if (v != null) this.header.addValue(headers[0], v); + if (v != null) { + this.header.addValue(headers[0], v); + } } else if (headers.length > 2) { String v = request.getHeader(headers[2]); - if (v != null) this.header.addValue(headers[0], v); + if (v != null) { + this.header.addValue(headers[0], v); + } } else { this.header.addValue(headers[0], headers[1]); } @@ -1054,10 +1106,14 @@ public class HttpResponse extends Response { for (String[] headers : this.defaultSetHeaders) { if (headers.length > 3) { String v = request.getParameter(headers[2]); - if (v != null) this.header.setValue(headers[0], v); + if (v != null) { + this.header.setValue(headers[0], v); + } } else if (headers.length > 2) { String v = request.getHeader(headers[2]); - if (v != null) this.header.setValue(headers[0], v); + if (v != null) { + this.header.setValue(headers[0], v); + } } else { this.header.setValue(headers[0], headers[1]); } @@ -1074,7 +1130,9 @@ public class HttpResponse extends Response { domain = "Domain=" + domain + "; "; } String path = defaultCookie == null ? null : defaultCookie.getPath(); - if (path == null || path.isEmpty()) path = "/"; + if (path == null || path.isEmpty()) { + path = "/"; + } if (request.newSessionid.isEmpty()) { headerArray.put(("Set-Cookie: " + HttpRequest.SESSIONID_NAME + "=; " + domain + "Path=/; Max-Age=0; HttpOnly\r\n").getBytes()); } else { @@ -1083,10 +1141,16 @@ public class HttpResponse extends Response { } if (this.cookies != null) { for (HttpCookie cookie : this.cookies) { - if (cookie == null) continue; + if (cookie == null) { + continue; + } if (defaultCookie != null) { - if (defaultCookie.getDomain() != null && cookie.getDomain() == null) cookie.setDomain(defaultCookie.getDomain()); - if (defaultCookie.getPath() != null && cookie.getPath() == null) cookie.setPath(defaultCookie.getPath()); + if (defaultCookie.getDomain() != null && cookie.getDomain() == null) { + cookie.setDomain(defaultCookie.getDomain()); + } + if (defaultCookie.getPath() != null && cookie.getPath() == null) { + cookie.setPath(defaultCookie.getPath()); + } } headerArray.put(("Set-Cookie: " + cookieString(cookie) + "\r\n").getBytes()); } @@ -1098,15 +1162,25 @@ public class HttpResponse extends Response { private CharSequence cookieString(HttpCookie cookie) { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()).append("=").append(cookie.getValue()).append("; Version=1"); - if (cookie.getDomain() != null) sb.append("; Domain=").append(cookie.getDomain()); - if (cookie.getPath() != null) sb.append("; Path=").append(cookie.getPath()); - if (cookie.getPortlist() != null) sb.append("; Port=").append(cookie.getPortlist()); + if (cookie.getDomain() != null) { + sb.append("; Domain=").append(cookie.getDomain()); + } + if (cookie.getPath() != null) { + sb.append("; Path=").append(cookie.getPath()); + } + if (cookie.getPortlist() != null) { + sb.append("; Port=").append(cookie.getPortlist()); + } if (cookie.getMaxAge() > 0) { sb.append("; Max-Age=").append(cookie.getMaxAge()); sb.append("; Expires=").append(RFC_1123_DATE_TIME.format(java.time.ZonedDateTime.now(ZONE_GMT).plusSeconds(cookie.getMaxAge()))); } - if (cookie.getSecure()) sb.append("; Secure"); - if (cookie.isHttpOnly()) sb.append("; HttpOnly"); + if (cookie.getSecure()) { + sb.append("; Secure"); + } + if (cookie.isHttpOnly()) { + sb.append("; HttpOnly"); + } return sb; } @@ -1119,7 +1193,9 @@ public class HttpResponse extends Response { */ protected void sendBody(ByteBuffer buffer, CompletionHandler handler) { if (this.headWritedSize < 0) { - if (this.contentLength < 0) this.contentLength = buffer == null ? 0 : buffer.remaining(); + if (this.contentLength < 0) { + this.contentLength = buffer == null ? 0 : buffer.remaining(); + } createHeader(); if (buffer == null) { super.send(headerArray, handler); @@ -1199,9 +1275,13 @@ public class HttpResponse extends Response { } } this.contentType = MimeType.getByFilename(filename == null || filename.isEmpty() ? file.getName() : filename); - if (this.contentType == null) this.contentType = "application/octet-stream"; + if (this.contentType == null) { + this.contentType = "application/octet-stream"; + } String range = request.getHeader("Range"); - if (range != null && (!range.startsWith("bytes=") || range.indexOf(',') >= 0)) range = null; + if (range != null && (!range.startsWith("bytes=") || range.indexOf(',') >= 0)) { + range = null; + } long start = -1; long len = -1; if (range != null) { @@ -1220,10 +1300,14 @@ public class HttpResponse extends Response { createHeader(); ByteArray data = headerArray; if (fileBody == null) { - if (this.recycleListener != null) this.output = file; + if (this.recycleListener != null) { + this.output = file; + } finishFile(data, file, start, len); } else { //一般HttpResourceServlet缓存file内容时fileBody不为空 - if (start >= 0) data.put(fileBody, (int) start, (int) ((len > 0) ? len : fileBody.length() - start)); + if (start >= 0) { + data.put(fileBody, (int) start, (int) ((len > 0) ? len : fileBody.length() - start)); + } super.finish(false, data.content(), 0, data.length()); } } @@ -1246,7 +1330,9 @@ public class HttpResponse extends Response { public void completed(Integer result, Void attachment) { try { if (fileChannel != null && sends >= limit) { - if (buffer != null) channel.offerBuffer(buffer); + if (buffer != null) { + channel.offerBuffer(buffer); + } try { fileChannel.close(); } catch (IOException ie) { @@ -1256,7 +1342,9 @@ public class HttpResponse extends Response { } if (fileChannel == null) { fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.READ); - if (offset > 0) fileChannel = fileChannel.position(offset); + if (offset > 0) { + fileChannel = fileChannel.position(offset); + } limit = length > 0 ? length : (file.length() - (offset > 0 ? offset : 0)); sends = 0; buffer = channel.ssl() ? channel.pollWriteSSLBuffer() : channel.pollWriteBuffer(); @@ -1264,7 +1352,9 @@ public class HttpResponse extends Response { buffer.clear(); int len = fileChannel.read(buffer); - if (len < 1) throw new IOException("read " + file + " error: " + len); + if (len < 1) { + throw new IOException("read " + file + " error: " + len); + } buffer.flip(); if (sends + len > limit) { buffer.limit((int) (len - limit + sends)); @@ -1286,8 +1376,12 @@ public class HttpResponse extends Response { @Override public void failed(Throwable exc, Void attachment) { - if (buffer != null) channel.offerBuffer(buffer); - if (logger.isLoggable(Level.FINER)) logger.log(Level.FINER, "finishFile error", exc); + if (buffer != null) { + channel.offerBuffer(buffer); + } + if (logger.isLoggable(Level.FINER)) { + logger.log(Level.FINER, "finishFile error", exc); + } finish(true); } }); @@ -1329,7 +1423,9 @@ public class HttpResponse extends Response { */ public HttpResponse setHeader(String name, Object value) { this.header.setValue(name, String.valueOf(value)); - if ("Connection".equalsIgnoreCase(name)) this.respHeadContainsConnection = true; + if ("Connection".equalsIgnoreCase(name)) { + this.respHeadContainsConnection = true; + } return this; } @@ -1343,7 +1439,9 @@ public class HttpResponse extends Response { */ public HttpResponse addHeader(String name, Object value) { this.header.addValue(name, String.valueOf(value)); - if ("Connection".equalsIgnoreCase(name)) this.respHeadContainsConnection = true; + if ("Connection".equalsIgnoreCase(name)) { + this.respHeadContainsConnection = true; + } return this; } @@ -1355,7 +1453,9 @@ public class HttpResponse extends Response { * @return HttpResponse */ public HttpResponse addHeader(Map map) { - if (map == null || map.isEmpty()) return this; + if (map == null || map.isEmpty()) { + return this; + } for (Map.Entry en : map.entrySet()) { this.header.addValue(en.getKey(), String.valueOf(en.getValue())); if (!respHeadContainsConnection && "Connection".equalsIgnoreCase(en.getKey())) { diff --git a/src/main/java/org/redkale/net/http/HttpResult.java b/src/main/java/org/redkale/net/http/HttpResult.java index 9a2a2c973..6fa359ecb 100644 --- a/src/main/java/org/redkale/net/http/HttpResult.java +++ b/src/main/java/org/redkale/net/http/HttpResult.java @@ -60,7 +60,9 @@ public class HttpResult { } public HttpResult header(String name, Serializable value) { - if (this.headers == null) this.headers = new HashMap<>(); + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(name, String.valueOf(value)); return this; } @@ -76,7 +78,9 @@ public class HttpResult { } public HttpResult cookie(HttpCookie cookie) { - if (this.cookies == null) this.cookies = new ArrayList<>(); + if (this.cookies == null) { + this.cookies = new ArrayList<>(); + } this.cookies.add(cookie); return this; } diff --git a/src/main/java/org/redkale/net/http/HttpScope.java b/src/main/java/org/redkale/net/http/HttpScope.java index 507a61f5e..e1d3a23c1 100644 --- a/src/main/java/org/redkale/net/http/HttpScope.java +++ b/src/main/java/org/redkale/net/http/HttpScope.java @@ -11,9 +11,9 @@ import java.net.HttpCookie; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.*; -import org.redkale.persistence.Transient; import org.redkale.convert.*; import org.redkale.convert.json.JsonConvert; +import org.redkale.persistence.Transient; import org.redkale.util.TypeToken; /** @@ -128,12 +128,16 @@ public class HttpScope { } public HttpScope appendAttrFunc(final String key, Supplier supplier) { - if (supplier == null) return this; + if (supplier == null) { + return this; + } return appendAttrFunc(k -> k.equals(key) ? supplier.get() : null); } public HttpScope appendAttrFunc(final Function attrFunc) { - if (attrFunc == null) return this; + if (attrFunc == null) { + return this; + } final Function old = this.attrFunction; if (old == null) { this.attrFunction = attrFunc; @@ -147,15 +151,23 @@ public class HttpScope { } public HttpScope attr(Map map) { - if (map == null) return this; - if (this.attributes == null) this.attributes = new LinkedHashMap<>(); + if (map == null) { + return this; + } + if (this.attributes == null) { + this.attributes = new LinkedHashMap<>(); + } this.attributes.putAll(map); return this; } public HttpScope attr(String name, Object value) { - if (name == null || value == null) return this; - if (this.attributes == null) this.attributes = new LinkedHashMap<>(); + if (name == null || value == null) { + return this; + } + if (this.attributes == null) { + this.attributes = new LinkedHashMap<>(); + } this.attributes.put(name, value); return this; } @@ -168,17 +180,23 @@ public class HttpScope { @SuppressWarnings("unchecked") public T find(HttpScope parent, String name) { T rs = this.attributes == null ? null : (T) this.attributes.get(name); - if (rs != null) return rs; + if (rs != null) { + return rs; + } return parent == null ? null : parent.find(name); } public void forEach(BiConsumer action) { - if (this.attributes == null) return; + if (this.attributes == null) { + return; + } this.attributes.forEach(action); } public HttpScope header(String name, Serializable value) { - if (this.headers == null) this.headers = new HashMap<>(); + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(name, String.valueOf(value)); return this; } @@ -194,7 +212,9 @@ public class HttpScope { } public HttpScope cookie(HttpCookie cookie) { - if (this.cookies == null) this.cookies = new ArrayList<>(); + if (this.cookies == null) { + this.cookies = new ArrayList<>(); + } this.cookies.add(cookie); return this; } @@ -242,7 +262,9 @@ public class HttpScope { public Map getAttributes() { final Function attrFunc = this.attrFunction; if (attrFunc != null) { - if (this.attributes == null) this.attributes = new LinkedHashMap<>(); + if (this.attributes == null) { + this.attributes = new LinkedHashMap<>(); + } return new LinkedHashMap(this.attributes) { @Override public Object get(Object key) { @@ -250,7 +272,9 @@ public class HttpScope { return super.get(key); } else { Object val = attrFunc.apply(key.toString()); - if (val == NIL) return null; + if (val == NIL) { + return null; + } put(key.toString(), val); return val; } diff --git a/src/main/java/org/redkale/net/http/HttpServer.java b/src/main/java/org/redkale/net/http/HttpServer.java index 62195e689..593a6d4f9 100644 --- a/src/main/java/org/redkale/net/http/HttpServer.java +++ b/src/main/java/org/redkale/net/http/HttpServer.java @@ -226,7 +226,9 @@ public class HttpServer extends Server T addRestWebSocketServlet(final ClassLoader classLoader, final Class webSocketType, MessageAgent messageAgent, final String prefix, final AnyValue conf) { T servlet = Rest.createRestWebSocketServlet(classLoader, webSocketType, messageAgent); - if (servlet != null) this.dispatcher.addServlet(servlet, prefix, conf); + if (servlet != null) { + this.dispatcher.addServlet(servlet, prefix, conf); + } return servlet; } @@ -269,8 +271,12 @@ public class HttpServer extends Server serviceType = Sncp.getServiceType(service); if (name != null) { for (final HttpServlet item : ((HttpDispatcherServlet) this.dispatcher).getServlets()) { - if (!(item instanceof HttpServlet)) continue; - if (item.getClass().getAnnotation(Rest.RestDyn.class) == null) continue; + if (!(item instanceof HttpServlet)) { + continue; + } + if (item.getClass().getAnnotation(Rest.RestDyn.class) == null) { + continue; + } try { Field field = item.getClass().getDeclaredField(Rest.REST_SERVICE_FIELD_NAME); if (serviceType.equals(field.getType())) { @@ -293,7 +299,9 @@ public class HttpServer extends Server 0) { for (AnyValue addHeader : addHeaders) { String val = addHeader.getValue("value"); - if (val == null) continue; + if (val == null) { + continue; + } if (val.startsWith("request.parameters.")) { defaultAddHeaders.add(new String[]{addHeader.getValue("name"), val, val.substring("request.parameters.".length()), null}); } else if (val.startsWith("request.headers.")) { defaultAddHeaders.add(new String[]{addHeader.getValue("name"), val, val.substring("request.headers.".length())}); } else if (val.startsWith("system.property.")) { String v = System.getProperty(val.substring("system.property.".length())); - if (v != null) defaultAddHeaders.add(new String[]{addHeader.getValue("name"), v}); + if (v != null) { + defaultAddHeaders.add(new String[]{addHeader.getValue("name"), v}); + } } else { defaultAddHeaders.add(new String[]{addHeader.getValue("name"), val}); } @@ -393,14 +413,18 @@ public class HttpServer extends Server 0) { for (AnyValue setHeader : setHeaders) { String val = setHeader.getValue("value"); - if (val == null) continue; + if (val == null) { + continue; + } if (val.startsWith("request.parameters.")) { defaultSetHeaders.add(new String[]{setHeader.getValue("name"), val, val.substring("request.parameters.".length()), null}); } else if (val.startsWith("request.headers.")) { defaultSetHeaders.add(new String[]{setHeader.getValue("name"), val, val.substring("request.headers.".length())}); } else if (val.startsWith("system.property.")) { String v = System.getProperty(val.substring("system.property.".length())); - if (v != null) defaultSetHeaders.add(new String[]{setHeader.getValue("name"), v}); + if (v != null) { + defaultSetHeaders.add(new String[]{setHeader.getValue("name"), v}); + } } else { defaultSetHeaders.add(new String[]{setHeader.getValue("name"), val}); } @@ -521,7 +545,9 @@ public class HttpServer extends Server bufferPool = ObjectPool.createSafePool(createCounter, cycleCounter, bufferPoolSize, (Object... params) -> ByteBuffer.allocateDirect(rcapacity), null, (e) -> { - if (e == null || e.isReadOnly() || e.capacity() != rcapacity) return false; + if (e == null || e.isReadOnly() || e.capacity() != rcapacity) { + return false; + } e.clear(); return true; }); diff --git a/src/main/java/org/redkale/net/http/HttpServlet.java b/src/main/java/org/redkale/net/http/HttpServlet.java index 2b34e9d6b..c708d4924 100644 --- a/src/main/java/org/redkale/net/http/HttpServlet.java +++ b/src/main/java/org/redkale/net/http/HttpServlet.java @@ -10,9 +10,9 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.function.*; -import org.redkale.asm.*; +import java.util.function.BiConsumer; import static org.redkale.asm.ClassWriter.COMPUTE_FRAMES; +import org.redkale.asm.*; import static org.redkale.asm.Opcodes.*; import org.redkale.boot.Application; import org.redkale.net.*; @@ -126,10 +126,14 @@ public class HttpServlet extends Servlet @SuppressWarnings("unchecked") void preInit(Application application, HttpContext context, AnyValue config) { - if (this.mappings != null) return; //无需重复preInit + if (this.mappings != null) { + return; //无需重复preInit + } String path = _prefix == null ? "" : _prefix; WebServlet ws = this.getClass().getAnnotation(WebServlet.class); - if (ws != null && !ws.repair()) path = ""; + if (ws != null && !ws.repair()) { + path = ""; + } HashMap map = this._actionmap != null ? this._actionmap : loadActionEntry(); this.mappings = new Map.Entry[map.size()]; int i = -1; @@ -241,29 +245,43 @@ public class HttpServlet extends Servlet final Class selfClz = this.getClass(); Class clz = this.getClass(); do { - if (java.lang.reflect.Modifier.isAbstract(clz.getModifiers())) break; + if (java.lang.reflect.Modifier.isAbstract(clz.getModifiers())) { + break; + } RedkaleClassLoader.putReflectionPublicMethods(clz.getName()); for (final Method method : clz.getMethods()) { //----------------------------------------------- String methodname = method.getName(); - if ("service".equals(methodname) || "preExecute".equals(methodname) || "execute".equals(methodname) || "authenticate".equals(methodname)) continue; + if ("service".equals(methodname) || "preExecute".equals(methodname) || "execute".equals(methodname) || "authenticate".equals(methodname)) { + continue; + } //----------------------------------------------- Class[] paramTypes = method.getParameterTypes(); - if (paramTypes.length != 2 || paramTypes[0] != HttpRequest.class || paramTypes[1] != HttpResponse.class) continue; + if (paramTypes.length != 2 || paramTypes[0] != HttpRequest.class || paramTypes[1] != HttpResponse.class) { + continue; + } //----------------------------------------------- Class[] exps = method.getExceptionTypes(); - if (exps.length > 0 && (exps.length != 1 || exps[0] != IOException.class)) continue; + if (exps.length > 0 && (exps.length != 1 || exps[0] != IOException.class)) { + continue; + } //----------------------------------------------- final HttpMapping mapping = method.getAnnotation(HttpMapping.class); - if (mapping == null) continue; + if (mapping == null) { + continue; + } final boolean inherited = mapping.inherited(); - if (!inherited && selfClz != clz) continue; //忽略不被继承的方法 + if (!inherited && selfClz != clz) { + continue; //忽略不被继承的方法 + } final int actionid = mapping.actionid(); final String name = mapping.url().trim(); final String[] methods = mapping.methods(); if (nameset.containsKey(name)) { - if (nameset.get(name) != clz) continue; + if (nameset.get(name) != clz) { + continue; + } throw new RuntimeException(this.getClass().getSimpleName() + " have two same " + HttpMapping.class.getSimpleName() + "(" + name + ")"); } nameset.put(name, clz); @@ -296,7 +314,9 @@ public class HttpServlet extends Servlet this.cache = cacheSeconds > 0 ? new ConcurrentHashMap<>() : null; this.cacheHandler = cacheSeconds > 0 ? (HttpResponse response, byte[] content) -> { int status = response.getStatus(); - if (status != 200) return; + if (status != 200) { + return; + } CacheEntry ce = new CacheEntry(response.getStatus(), response.getContentType(), content); cache.put(response.getRequest().getRequestURI(), ce); } : null; @@ -305,7 +325,9 @@ public class HttpServlet extends Servlet this.cache = null; this.cacheHandler = cacheSeconds > 0 ? (HttpResponse response, byte[] content) -> { int status = response.getStatus(); - if (status != 200) return; + if (status != 200) { + return; + } oneCache = new CacheEntry(response.getStatus(), response.getContentType(), content); } : null; } @@ -336,9 +358,13 @@ public class HttpServlet extends Servlet } boolean checkMethod(final String reqMethod) { - if (methods.length == 0) return true; + if (methods.length == 0) { + return true; + } for (String m : methods) { - if (reqMethod.equalsIgnoreCase(m)) return true; + if (reqMethod.equalsIgnoreCase(m)) { + return true; + } } return false; } diff --git a/src/main/java/org/redkale/net/http/HttpSimpleRequest.java b/src/main/java/org/redkale/net/http/HttpSimpleRequest.java index 77796ee2f..b208e810a 100644 --- a/src/main/java/org/redkale/net/http/HttpSimpleRequest.java +++ b/src/main/java/org/redkale/net/http/HttpSimpleRequest.java @@ -5,16 +5,15 @@ */ package org.redkale.net.http; -import java.io.*; +import java.io.Serializable; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; - import org.redkale.annotation.Comment; import org.redkale.convert.*; import org.redkale.convert.json.JsonConvert; -import org.redkale.util.*; +import org.redkale.util.Traces; /** * HttpRequest的缩减版, 只提供部分字段 @@ -105,11 +104,15 @@ public class HttpSimpleRequest implements java.io.Serializable { @ConvertDisabled public String getParametersToString() { - if (this.params == null || this.params.isEmpty()) return null; + if (this.params == null || this.params.isEmpty()) { + return null; + } final StringBuilder sb = new StringBuilder(); AtomicBoolean no2 = new AtomicBoolean(false); this.params.forEach((n, v) -> { - if (no2.get()) sb.append('&'); + if (no2.get()) { + sb.append('&'); + } sb.append(n).append('=').append(URLEncoder.encode(v, StandardCharsets.UTF_8)); no2.set(true); }); @@ -193,12 +196,16 @@ public class HttpSimpleRequest implements java.io.Serializable { } public HttpSimpleRequest removeHeader(String name) { - if (this.headers != null) this.headers.remove(name); + if (this.headers != null) { + this.headers.remove(name); + } return this; } public HttpSimpleRequest removeParam(String name) { - if (this.params != null) this.params.remove(name); + if (this.params != null) { + this.params.remove(name); + } return this; } @@ -213,55 +220,83 @@ public class HttpSimpleRequest implements java.io.Serializable { } public HttpSimpleRequest header(String key, String value) { - if (this.headers == null) this.headers = new HashMap<>(); + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(key, value); return this; } public HttpSimpleRequest header(String key, JsonConvert convert, Object value) { - if (value == null) return this; - if (this.headers == null) this.headers = new HashMap<>(); - if (convert == null) convert = JsonConvert.root(); + if (value == null) { + return this; + } + if (this.headers == null) { + this.headers = new HashMap<>(); + } + if (convert == null) { + convert = JsonConvert.root(); + } this.headers.put(key, convert.convertTo(value)); return this; } public HttpSimpleRequest header(String key, Object value) { - if (value == null) return this; - if (this.headers == null) this.headers = new HashMap<>(); + if (value == null) { + return this; + } + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(key, JsonConvert.root().convertTo(value)); return this; } public HttpSimpleRequest header(String key, int value) { - if (this.headers == null) this.headers = new HashMap<>(); + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(key, String.valueOf(value)); return this; } public HttpSimpleRequest header(String key, long value) { - if (this.headers == null) this.headers = new HashMap<>(); + if (this.headers == null) { + this.headers = new HashMap<>(); + } this.headers.put(key, String.valueOf(value)); return this; } public HttpSimpleRequest param(String key, String value) { - if (this.params == null) this.params = new HashMap<>(); + if (this.params == null) { + this.params = new HashMap<>(); + } this.params.put(key, value); return this; } public HttpSimpleRequest param(String key, JsonConvert convert, Object value) { - if (value == null) return this; - if (this.params == null) this.params = new HashMap<>(); - if (convert == null) convert = JsonConvert.root(); + if (value == null) { + return this; + } + if (this.params == null) { + this.params = new HashMap<>(); + } + if (convert == null) { + convert = JsonConvert.root(); + } this.params.put(key, convert.convertTo(value)); return this; } public HttpSimpleRequest param(String key, Object value) { - if (value == null) return this; - if (this.params == null) this.params = new HashMap<>(); + if (value == null) { + return this; + } + if (this.params == null) { + this.params = new HashMap<>(); + } this.params.put(key, value instanceof CharSequence ? value.toString() : JsonConvert.root().convertTo(value)); return this; } diff --git a/src/main/java/org/redkale/net/http/MultiContext.java b/src/main/java/org/redkale/net/http/MultiContext.java index fe3b5bd41..3b415993d 100644 --- a/src/main/java/org/redkale/net/http/MultiContext.java +++ b/src/main/java/org/redkale/net/http/MultiContext.java @@ -5,13 +5,13 @@ */ package org.redkale.net.http; -import org.redkale.util.ByteArray; import java.io.*; import java.nio.charset.*; import java.util.*; import java.util.concurrent.atomic.*; import java.util.logging.*; -import java.util.regex.*; +import java.util.regex.Pattern; +import org.redkale.util.ByteArray; /** * HTTP的文件上传请求的上下文对象 @@ -70,7 +70,9 @@ public final class MultiContext { } for (String str : contentType.split(";")) { int pos = str.indexOf("boundary="); - if (pos >= 0) return str.substring(pos + "boundary=".length()).trim(); + if (pos >= 0) { + return str.substring(pos + "boundary=".length()).trim(); + } } return null; } @@ -96,14 +98,22 @@ public final class MultiContext { * @throws IOException IOException */ public byte[] partsFirstBytes(final long max, final String filenameReg, final String contentTypeReg) throws IOException { - if (!isMultipart()) return null; + if (!isMultipart()) { + return null; + } byte[] tmpfile = null; boolean has = false; for (MultiPart part : parts()) { - if (has) continue;//不遍历完后面getParameter可能获取不到值 + if (has) { + continue;//不遍历完后面getParameter可能获取不到值 + } has = true; - if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) continue; - if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) continue; + if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) { + continue; + } + if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) { + continue; + } tmpfile = part.getContentBytes(max < 1 ? Long.MAX_VALUE : max); } return tmpfile; @@ -117,7 +127,9 @@ public final class MultiContext { * @return 上传的文件名 */ public static String getFileName(File file) { - if (file == null) return null; + if (file == null) { + return null; + } String name = file.getName(); return name.startsWith("redkale-") ? name.substring(name.indexOf('_') + 1) : name; } @@ -135,17 +147,27 @@ public final class MultiContext { * @throws IOException IOException */ public File partsFirstFile(final File home, final long max, final String filenameReg, final String contentTypeReg) throws IOException { - if (!isMultipart()) return null; + if (!isMultipart()) { + return null; + } File tmpfile = null; boolean has = false; for (MultiPart part : parts()) { - if (has) continue; //不遍历完后面getParameter可能获取不到值 + if (has) { + continue; //不遍历完后面getParameter可能获取不到值 + } has = true; - if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) continue; - if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) continue; + if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) { + continue; + } + if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) { + continue; + } File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFilename()); File parent = file.getParentFile(); - if (!parent.isDirectory()) parent.mkdirs(); + if (!parent.isDirectory()) { + parent.mkdirs(); + } boolean rs = part.save(max < 1 ? Long.MAX_VALUE : max, file); if (!rs) { file.delete(); @@ -170,21 +192,31 @@ public final class MultiContext { * @throws IOException IOException */ public File[] partsFiles(final File home, final long max, final String filenameReg, final String contentTypeReg) throws IOException { - if (!isMultipart()) return null; + if (!isMultipart()) { + return null; + } List files = null; for (MultiPart part : parts()) { - if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) continue; - if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) continue; + if (filenameReg != null && !filenameReg.isEmpty() && !part.getFilename().matches(filenameReg)) { + continue; + } + if (contentTypeReg != null && !contentTypeReg.isEmpty() && !part.getContentType().matches(contentTypeReg)) { + continue; + } File file = new File(home, "tmp/redkale-" + System.nanoTime() + "_" + part.getFilename()); File parent = file.getParentFile(); - if (!parent.isDirectory()) parent.mkdirs(); + if (!parent.isDirectory()) { + parent.mkdirs(); + } boolean rs = part.save(max < 1 ? Long.MAX_VALUE : max, file); if (!rs) { file.delete(); parent.delete(); continue; } - if (files == null) files = new ArrayList<>(); + if (files == null) { + files = new ArrayList<>(); + } files.add(file); } return files == null ? null : files.toArray(new File[files.size()]); @@ -197,7 +229,9 @@ public final class MultiContext { * @throws IOException IOException */ public Iterable parts() throws IOException { - if (!isMultipart()) return emptyIterable; + if (!isMultipart()) { + return emptyIterable; + } final String boundarystr = "--" + this.boundary; final Pattern fielnameReg = this.fielnamePattern; final String endboundary = boundarystr + "--"; @@ -217,9 +251,13 @@ public final class MultiContext { try { if (lastentry != null) { lastentry.skip(); - if (finaled.get()) return false; + if (finaled.get()) { + return false; + } + } + if (boundaryline == null) { + boundaryline = readBoundary(); } - if (boundaryline == null) boundaryline = readBoundary(); //if (debug) System.out.print("boundaryline=" + boundaryline + " "); if (endboundary.equals(boundaryline) || !boundarystr.equals(boundaryline)) { //结尾或异常 lastentry = null; @@ -232,7 +270,9 @@ public final class MultiContext { //读掉HTTP Header和空白行 通常情况下Content-Type后面就是内容,但是有些特殊情况下后面会跟其他如Content-Length: xxx等HTTP header,所以需要循环读取 String rl; while (!(rl = readLine()).isEmpty()) { - if (rl.startsWith("Content-Type:") || rl.startsWith("content-type:")) contentType = rl.substring(rl.indexOf(':') + 1).trim(); + if (rl.startsWith("Content-Type:") || rl.startsWith("content-type:")) { + contentType = rl.substring(rl.indexOf(':') + 1).trim(); + } } //if (debug) System.out.println("file.contentType=" + contentType); @@ -245,8 +285,12 @@ public final class MultiContext { return this.hasNext(); } else { int p1 = filename.lastIndexOf('/'); - if (p1 < 0) p1 = filename.lastIndexOf('\\'); - if (p1 >= 0) filename = filename.substring(p1 + 1); + if (p1 < 0) { + p1 = filename.lastIndexOf('\\'); + } + if (p1 >= 0) { + filename = filename.substring(p1 + 1); + } } final LongAdder counter = new LongAdder(); InputStream source = new InputStream() { @@ -257,10 +301,14 @@ public final class MultiContext { @Override public int read() throws IOException { - if (end) return -1; + if (end) { + return -1; + } final byte[] buf = buffer; int ch = (this.bufposition < buf.length) ? (buf[this.bufposition++] & 0xff) : input.read(); - if ((ch == '\r' && readBuffer())) return -1; + if ((ch == '\r' && readBuffer())) { + return -1; + } counter.increment(); return ch; } @@ -276,7 +324,9 @@ public final class MultiContext { int t = 0; while ((t = input.read(buf, s + readed, pos - readed)) > 0) { readed += t; - if (readed == pos) break; + if (readed == pos) { + break; + } } this.bufposition = 0; if (Arrays.equals(boundarray, buf)) { @@ -291,12 +341,18 @@ public final class MultiContext { @Override public long skip(long count) throws IOException { - if (end) return -1; - if (count <= 0) return 0; + if (end) { + return -1; + } + if (count <= 0) { + return 0; + } long s = 0; while (read() != -1) { s++; - if (--count <= 0) break; + if (--count <= 0) { + break; + } } return s; } @@ -343,24 +399,36 @@ public final class MultiContext { for (;;) { int b = in.read(); c++; - if (b == -1 || (lasted == '\r' && b == '\n')) break; - if (lasted != '\r') buf.put(lasted); + if (b == -1 || (lasted == '\r' && b == '\n')) { + break; + } + if (lasted != '\r') { + buf.put(lasted); + } lasted = (byte) b; if (bd && bc == c) { buf.put(lasted); - if (buf.equal(this.endboundarray)) break; + if (buf.equal(this.endboundarray)) { + break; + } buf.removeLastByte(); } } - if (buf.length() == 0) return ""; + if (buf.length() == 0) { + return ""; + } return buf.toString(this.charset).trim(); } private static String parseValue(final String str, String name) { - if (str == null) return null; + if (str == null) { + return null; + } final String key = "; " + name + "=\""; int pos = str.indexOf(key); - if (pos < 0) return null; + if (pos < 0) { + return null; + } String sub = str.substring(pos + key.length()); return sub.substring(0, sub.indexOf('"')); } diff --git a/src/main/java/org/redkale/net/http/MultiPart.java b/src/main/java/org/redkale/net/http/MultiPart.java index 534b1b769..85f429bd0 100644 --- a/src/main/java/org/redkale/net/http/MultiPart.java +++ b/src/main/java/org/redkale/net/http/MultiPart.java @@ -10,7 +10,9 @@ import java.util.concurrent.atomic.LongAdder; /** * - *

详情见: https://redkale.org + *

+ * 详情见: https://redkale.org + * * @author zhangjx */ public final class MultiPart { @@ -57,6 +59,7 @@ public final class MultiPart { * 将文件流读进bytes, 如果超出max指定的值则返回null * * @param max 最大长度限制 + * * @return 内容 * @throws IOException 异常 */ @@ -74,6 +77,7 @@ public final class MultiPart { * * @param max 最大长度限制 * @param out 输出流 + * * @return 是否成功 * @throws IOException 异常 */ @@ -82,7 +86,9 @@ public final class MultiPart { int pos; InputStream in0 = this.getInputStream(); while ((pos = in0.read(bytes)) != -1) { - if (max < 0) return false; + if (max < 0) { + return false; + } out.write(bytes, 0, pos); max -= pos; } diff --git a/src/main/java/org/redkale/net/http/Rest.java b/src/main/java/org/redkale/net/http/Rest.java index 5173e89da..637e4d449 100644 --- a/src/main/java/org/redkale/net/http/Rest.java +++ b/src/main/java/org/redkale/net/http/Rest.java @@ -118,15 +118,21 @@ public final class Rest { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { - if (java.lang.reflect.Modifier.isStatic(access)) return null; + if (java.lang.reflect.Modifier.isStatic(access)) { + return null; + } List fieldnames = new ArrayList<>(); String key = name + ":" + desc; - if (fieldmap.containsKey(key)) return null; + if (fieldmap.containsKey(key)) { + return null; + } fieldmap.put(key, fieldnames); return new MethodVisitor(Opcodes.ASM6) { @Override public void visitLocalVariable(String name, String description, String signature, Label start, Label end, int index) { - if (index < 1) return; + if (index < 1) { + return; + } int size = fieldnames.size(); //index并不会按顺序执行的 if (index > size) { @@ -144,13 +150,17 @@ public final class Rest { public static Map> getMethodParamNames(Map> map, Class clazz) { String n = clazz.getName(); InputStream in = clazz.getResourceAsStream(n.substring(n.lastIndexOf('.') + 1) + ".class"); - if (in == null) return map; + if (in == null) { + return map; + } try { new ClassReader(Utility.readBytesThenClose(in)).accept(new MethodParamClassVisitor(Opcodes.ASM6, map), 0); } catch (Exception e) { //无需理会 } Class superClass = clazz.getSuperclass(); - if (superClass == Object.class) return map; + if (superClass == Object.class) { + return map; + } return getMethodParamNames(map, superClass); } } @@ -160,7 +170,9 @@ public final class Rest { } public static JsonFactory createJsonFactory(boolean tiny, RestConvert[] converts, RestConvertCoder[] coders) { - if ((converts == null || converts.length < 1) && (coders == null || coders.length < 1)) return JsonFactory.root(); + if ((converts == null || converts.length < 1) && (coders == null || coders.length < 1)) { + return JsonFactory.root(); + } final JsonFactory childFactory = JsonFactory.create().tiny(tiny); List types = new ArrayList<>(); Set reloadTypes = new HashSet<>(); @@ -175,7 +187,9 @@ public final class Rest { if (rc.type() == void.class || rc.type() == Void.class) { return JsonFactory.create().skipAllIgnore(true); } - if (types.contains(rc.type())) throw new RuntimeException("@RestConvert type(" + rc.type() + ") repeat"); + if (types.contains(rc.type())) { + throw new RuntimeException("@RestConvert type(" + rc.type() + ") repeat"); + } if (rc.skipIgnore()) { childFactory.registerSkipIgnore(rc.type()); childFactory.reloadCoder(rc.type()); @@ -188,7 +202,9 @@ public final class Rest { childFactory.reloadCoder(rc.type()); } types.add(rc.type()); - if (tiny) childFactory.tiny(rc.tiny()); + if (tiny) { + childFactory.tiny(rc.tiny()); + } } } for (Class type : reloadTypes) { @@ -199,15 +215,23 @@ public final class Rest { static String getWebModuleNameLowerCase(Class serviceType) { final RestService controller = serviceType.getAnnotation(RestService.class); - if (controller == null) return serviceType.getSimpleName().replaceAll("Service.*$", "").toLowerCase(); - if (controller.ignore()) return null; + if (controller == null) { + return serviceType.getSimpleName().replaceAll("Service.*$", "").toLowerCase(); + } + if (controller.ignore()) { + return null; + } return (!controller.name().isEmpty()) ? controller.name().trim() : serviceType.getSimpleName().replaceAll("Service.*$", "").toLowerCase(); } static String getWebModuleName(Class serviceType) { final RestService controller = serviceType.getAnnotation(RestService.class); - if (controller == null) return serviceType.getSimpleName().replaceAll("Service.*$", ""); - if (controller.ignore()) return null; + if (controller == null) { + return serviceType.getSimpleName().replaceAll("Service.*$", ""); + } + if (controller.ignore()) { + return null; + } return (!controller.name().isEmpty()) ? controller.name().trim() : serviceType.getSimpleName().replaceAll("Service.*$", ""); } @@ -242,8 +266,12 @@ public final class Rest { * @return Service */ public static Service getService(HttpServlet servlet) { - if (servlet == null) return null; - if (!isRestDyn(servlet)) return null; + if (servlet == null) { + return null; + } + if (!isRestDyn(servlet)) { + return null; + } try { Field ts = servlet.getClass().getDeclaredField(REST_SERVICE_FIELD_NAME); ts.setAccessible(true); @@ -254,7 +282,9 @@ public final class Rest { } public static Map getServiceMap(HttpServlet servlet) { - if (servlet == null) return null; + if (servlet == null) { + return null; + } try { Field ts = servlet.getClass().getDeclaredField(REST_SERVICEMAP_FIELD_NAME); ts.setAccessible(true); @@ -266,7 +296,9 @@ public final class Rest { public static String getRestModule(Service service) { final RestService controller = service.getClass().getAnnotation(RestService.class); - if (controller != null && !controller.name().isEmpty()) return controller.name(); + if (controller != null && !controller.name().isEmpty()) { + return controller.name(); + } final Class serviceType = Sncp.getServiceType(service); return serviceType.getSimpleName().replaceAll("Service.*$", "").toLowerCase(); } @@ -297,7 +329,9 @@ public final class Rest { break; } } - if (!valid) throw new RuntimeException("Rest WebSocket Class(" + webSocketType + ") must have public or protected Constructor on createRestWebSocketServlet"); + if (!valid) { + throw new RuntimeException("Rest WebSocket Class(" + webSocketType + ") must have public or protected Constructor on createRestWebSocketServlet"); + } final String rwsname = ResourceFactory.formatResourceName(rws.name()); if (!checkName(rws.catalog())) { throw new RuntimeException(webSocketType.getName() + " have illegal " + RestWebSocket.class.getSimpleName() + ".catalog, only 0-9 a-z A-Z _ cannot begin 0-9"); @@ -313,8 +347,12 @@ public final class Rest { Class clzz = webSocketType; do { for (Field field : clzz.getDeclaredFields()) { - if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) continue; - if (resourcesFieldNameSet.contains(field.getName())) continue; + if (field.getAnnotation(Resource.class) == null && field.getAnnotation(javax.annotation.Resource.class) == null) { + continue; + } + if (resourcesFieldNameSet.contains(field.getName())) { + continue; + } if (Modifier.isStatic(field.getModifiers())) { throw new RuntimeException(field + " cannot static on createRestWebSocketServlet"); } @@ -348,15 +386,31 @@ public final class Rest { List mmethods = new ArrayList<>(); for (Method method : webSocketType.getMethods()) { RestOnMessage rom = method.getAnnotation(RestOnMessage.class); - if (rom == null) continue; + if (rom == null) { + continue; + } String name = rom.name(); - if (!"*".equals(name) && !checkName(name)) throw new RuntimeException("@RestOnMessage.name contains illegal characters on (" + method + ")"); - if (Modifier.isFinal(method.getModifiers())) throw new RuntimeException("@RestOnMessage method can not final but (" + method + ")"); - if (Modifier.isStatic(method.getModifiers())) throw new RuntimeException("@RestOnMessage method can not static but (" + method + ")"); - if (method.getReturnType() != void.class) throw new RuntimeException("@RestOnMessage method must return void but (" + method + ")"); - if (method.getExceptionTypes().length > 0) throw new RuntimeException("@RestOnMessage method can not throw exception but (" + method + ")"); - if (name.isEmpty()) throw new RuntimeException(method + " RestOnMessage.name is empty createRestWebSocketServlet"); - if (messageNames.contains(name)) throw new RuntimeException(method + " repeat RestOnMessage.name(" + name + ") createRestWebSocketServlet"); + if (!"*".equals(name) && !checkName(name)) { + throw new RuntimeException("@RestOnMessage.name contains illegal characters on (" + method + ")"); + } + if (Modifier.isFinal(method.getModifiers())) { + throw new RuntimeException("@RestOnMessage method can not final but (" + method + ")"); + } + if (Modifier.isStatic(method.getModifiers())) { + throw new RuntimeException("@RestOnMessage method can not static but (" + method + ")"); + } + if (method.getReturnType() != void.class) { + throw new RuntimeException("@RestOnMessage method must return void but (" + method + ")"); + } + if (method.getExceptionTypes().length > 0) { + throw new RuntimeException("@RestOnMessage method can not throw exception but (" + method + ")"); + } + if (name.isEmpty()) { + throw new RuntimeException(method + " RestOnMessage.name is empty createRestWebSocketServlet"); + } + if (messageNames.contains(name)) { + throw new RuntimeException(method + " repeat RestOnMessage.name(" + name + ") createRestWebSocketServlet"); + } messageNames.add(name); if ("*".equals(name)) { wildcardMethod = method; @@ -367,7 +421,9 @@ public final class Rest { final List messageMethods = new ArrayList<>(); messageMethods.addAll(mmethods); //wildcardMethod 必须放最后, _DynRestOnMessageConsumer 是按messageMethods顺序来判断的 - if (wildcardMethod != null) messageMethods.add(wildcardMethod); + if (wildcardMethod != null) { + messageMethods.add(wildcardMethod); + } //---------------------------------------------------------------------------------------- final String resDesc = Type.getDescriptor(Resource.class); final String wsDesc = Type.getDescriptor(WebSocket.class); @@ -391,7 +447,9 @@ public final class Rest { final String newDynConsumerFullName = newDynName + "$" + newDynConsumerSimpleName; try { Class clz = RedkaleClassLoader.findDynClass(newDynName.replace('/', '.')); - if (clz == null) clz = loader.loadClass(newDynName.replace('/', '.')); + if (clz == null) { + clz = loader.loadClass(newDynName.replace('/', '.')); + } T servlet = (T) clz.getDeclaredConstructor().newInstance(); Map msgclassToAnnotations = new HashMap<>(); for (int i = 0; i < messageMethods.size(); i++) { // _DyncXXXWebSocketMessage 子消息List @@ -407,7 +465,9 @@ public final class Rest { cryptorField.setAccessible(true); cryptorField.set(servlet, cryptor); } - if (messageAgent != null) ((WebSocketServlet) servlet).messageAgent = messageAgent; + if (messageAgent != null) { + ((WebSocketServlet) servlet).messageAgent = messageAgent; + } return servlet; } catch (Throwable e) { } @@ -574,7 +634,9 @@ public final class Rest { Set paramnames = new HashSet<>(); String methodesc = method.getName() + ":" + Type.getMethodDescriptor(method); List names = asmParamMap == null ? null : asmParamMap.get(methodesc); - if (names != null) while (names.remove(" ")); //删掉空元素 + if (names != null) { + while (names.remove(" ")); //删掉空元素 + } Parameter[] params = method.getParameters(); final LinkedHashMap paramap = new LinkedHashMap(); //必须使用LinkedHashMap确保顺序 for (int j = 0; j < params.length; j++) { //字段列表 @@ -586,7 +648,9 @@ public final class Rest { } else if (names != null && names.size() > j) { paramname = names.get(j); } - if (paramnames.contains(paramname)) throw new RuntimeException(method + " has same @RestParam.name"); + if (paramnames.contains(paramname)) { + throw new RuntimeException(method + " has same @RestParam.name"); + } paramnames.add(paramname); paramap.put(paramname, param); fv = cw2.visitField(ACC_PUBLIC, paramname, Type.getDescriptor(param.getType()), @@ -596,7 +660,9 @@ public final class Rest { if (method == wildcardMethod) { for (int j = 0; j < messageMethods.size(); j++) { Method method2 = messageMethods.get(j); - if (method2 == wildcardMethod) continue; + if (method2 == wildcardMethod) { + continue; + } String endfix2 = "_" + method2.getName() + "_" + (j > 9 ? j : ("0" + j)); String newDynSuperMessageFullName2 = newDynMessageFullName + (method2 == wildcardMethod ? "" : endfix2); cw2.visitInnerClass(newDynSuperMessageFullName2, newDynName, newDynMessageSimpleName + endfix2, ACC_PUBLIC + ACC_STATIC); @@ -900,7 +966,9 @@ public final class Rest { cryptorField.setAccessible(true); cryptorField.set(servlet, cryptor); } - if (messageAgent != null) ((WebSocketServlet) servlet).messageAgent = messageAgent; + if (messageAgent != null) { + ((WebSocketServlet) servlet).messageAgent = messageAgent; + } return servlet; } catch (Exception e) { throw new RuntimeException(e); @@ -910,10 +978,16 @@ public final class Rest { public static T createRestServlet(final ClassLoader classLoader, final Class userType0, final Class baseServletType, final Class serviceType) { - if (baseServletType == null || serviceType == null) throw new RuntimeException(" Servlet or Service is null Class on createRestServlet"); - if (!HttpServlet.class.isAssignableFrom(baseServletType)) throw new RuntimeException(baseServletType + " is not HttpServlet Class on createRestServlet"); + if (baseServletType == null || serviceType == null) { + throw new RuntimeException(" Servlet or Service is null Class on createRestServlet"); + } + if (!HttpServlet.class.isAssignableFrom(baseServletType)) { + throw new RuntimeException(baseServletType + " is not HttpServlet Class on createRestServlet"); + } int mod = baseServletType.getModifiers(); - if (!java.lang.reflect.Modifier.isPublic(mod)) throw new RuntimeException(baseServletType + " is not Public Class on createRestServlet"); + if (!java.lang.reflect.Modifier.isPublic(mod)) { + throw new RuntimeException(baseServletType + " is not Public Class on createRestServlet"); + } if (java.lang.reflect.Modifier.isAbstract(mod)) { for (Method m : baseServletType.getDeclaredMethods()) { if (java.lang.reflect.Modifier.isAbstract(m.getModifiers())) { //@since 2.4.0 @@ -963,7 +1037,9 @@ public final class Rest { final String supDynName = baseServletType.getName().replace('.', '/'); final RestService controller = serviceType.getAnnotation(RestService.class); - if (controller != null && controller.ignore()) throw new RuntimeException(serviceType + " is ignore Rest Service Class"); //标记为ignore=true不创建Servlet + if (controller != null && controller.ignore()) { + throw new RuntimeException(serviceType + " is ignore Rest Service Class"); //标记为ignore=true不创建Servlet + } final boolean serrpconly = controller != null && controller.rpconly(); ClassLoader loader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader; String stname = serviceType.getSimpleName(); @@ -977,7 +1053,9 @@ public final class Rest { try { Class newClazz = RedkaleClassLoader.findDynClass(newDynName.replace('/', '.')); - if (newClazz == null) newClazz = loader.loadClass(newDynName.replace('/', '.')); + if (newClazz == null) { + newClazz = loader.loadClass(newDynName.replace('/', '.')); + } T obj = (T) newClazz.getDeclaredConstructor().newInstance(); final String defmodulename = getWebModuleNameLowerCase(serviceType); @@ -998,24 +1076,42 @@ public final class Rest { final Method[] allMethods = serviceType.getMethods(); Arrays.sort(allMethods, (m1, m2) -> { //必须排序,否则paramTypes顺序容易乱 int s = m1.getName().compareTo(m2.getName()); - if (s != 0) return s; + if (s != 0) { + return s; + } s = Arrays.toString(m1.getParameterTypes()).compareTo(Arrays.toString(m2.getParameterTypes())); return s; }); int methodidex = 0; for (final Method method : allMethods) { - if (Modifier.isStatic(method.getModifiers())) continue; - if (method.isSynthetic()) continue; - if (EXCLUDERMETHODS.contains(method.getName())) continue; - if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { - if ("init".equals(method.getName())) continue; - if ("stop".equals(method.getName())) continue; - if ("destroy".equals(method.getName())) continue; + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + if (method.isSynthetic()) { + continue; + } + if (EXCLUDERMETHODS.contains(method.getName())) { + continue; + } + if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { + if ("init".equals(method.getName())) { + continue; + } + if ("stop".equals(method.getName())) { + continue; + } + if ("destroy".equals(method.getName())) { + continue; + } + } + if (controller == null) { + continue; } - if (controller == null) continue; RestMapping[] mappings = method.getAnnotationsByType(RestMapping.class); - if (!controller.automapping() && mappings.length < 1) continue; + if (!controller.automapping() && mappings.length < 1) { + continue; + } boolean ignore = false; for (RestMapping mapping : mappings) { if (mapping.ignore()) { @@ -1023,7 +1119,9 @@ public final class Rest { break; } } - if (ignore) continue; + if (ignore) { + continue; + } paramTypes.add(TypeToken.getGenericType(method.getGenericParameterTypes(), serviceType)); retvalTypes.add(formatRestReturnType(method, serviceType)); if (mappings.length == 0) { //没有Mapping,设置一个默认值 @@ -1108,11 +1206,21 @@ public final class Rest { comment = ""; } RestParam annpara = param.getAnnotation(RestParam.class); - if (annpara != null) radix = annpara.radix(); - if (annpara != null) comment = annpara.comment(); - if (annpara != null) required = annpara.required(); - if (n == null) n = (annpara == null || annpara.name().isEmpty()) ? null : annpara.name(); - if (n == null && ptype == userType) n = "&"; //用户类型特殊处理 + if (annpara != null) { + radix = annpara.radix(); + } + if (annpara != null) { + comment = annpara.comment(); + } + if (annpara != null) { + required = annpara.required(); + } + if (n == null) { + n = (annpara == null || annpara.name().isEmpty()) ? null : annpara.name(); + } + if (n == null && ptype == userType) { + n = "&"; //用户类型特殊处理 + } if (n == null) { if (param.isNamePresent()) { n = param.getName(); @@ -1126,8 +1234,12 @@ public final class Rest { } for (Object[] ps : paramlist) { //{param, n, ptype, radix, comment, required, annpara, annsid, annaddr, annlocale, annhead, anncookie, annbody, annfile, annuri, annuserid, annheaders, annparams, paramtype} final boolean isuserid = ((RestUserid) ps[headIndex + 5]) != null; //是否取userid - if ((ps[1] != null && ps[1].toString().indexOf('&') >= 0) || isuserid) continue; //@RestUserid 不需要生成 @HttpParam - if (((RestAddress) ps[8]) != null) continue; //@RestAddress 不需要生成 @HttpParam + if ((ps[1] != null && ps[1].toString().indexOf('&') >= 0) || isuserid) { + continue; //@RestUserid 不需要生成 @HttpParam + } + if (((RestAddress) ps[8]) != null) { + continue; //@RestAddress 不需要生成 @HttpParam + } java.lang.reflect.Type pgtype = TypeToken.getGenericType(((Parameter) ps[0]).getParameterizedType(), serviceType); if (pgtype != (Class) ps[2]) { String refid = typeRefs.get(pgtype); @@ -1179,11 +1291,19 @@ public final class Rest { Set fields = new HashSet<>(); Map attrParaNames = new LinkedHashMap<>(); do { - if (loop == null || loop.isInterface()) break; //接口时getSuperclass可能会得到null + if (loop == null || loop.isInterface()) { + break; //接口时getSuperclass可能会得到null + } for (Field field : loop.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) continue; - if (Modifier.isFinal(field.getModifiers())) continue; - if (fields.contains(field.getName())) continue; + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + if (Modifier.isFinal(field.getModifiers())) { + continue; + } + if (fields.contains(field.getName())) { + continue; + } RestHeader rh = field.getAnnotation(RestHeader.class); RestCookie rc = field.getAnnotation(RestCookie.class); RestSessionid rs = field.getAnnotation(RestSessionid.class); @@ -1192,7 +1312,9 @@ public final class Rest { RestBody rb = field.getAnnotation(RestBody.class); RestUploadFile ru = field.getAnnotation(RestUploadFile.class); RestURI ri = field.getAnnotation(RestURI.class); - if (rh == null && rc == null && ra == null && rl == null && rb == null && rs == null && ru == null && ri == null) continue; + if (rh == null && rc == null && ra == null && rl == null && rb == null && rs == null && ru == null && ri == null) { + continue; + } org.redkale.util.Attribute attr = org.redkale.util.Attribute.create(loop, field); String attrFieldName; @@ -1284,10 +1406,14 @@ public final class Rest { ParameterizedType ptgrt = (ParameterizedType) grt; grt = ptgrt.getActualTypeArguments()[0]; rtc = TypeToken.typeToClass(grt); - if (rtc == null) rtc = Object.class; //应该不会发生吧? + if (rtc == null) { + rtc = Object.class; //应该不会发生吧? + } } else if (Flows.maybePublisherClass(returnType)) { java.lang.reflect.Type grt0 = Flows.maybePublisherSubType(grt); - if (grt0 != null) grt = grt0; + if (grt0 != null) { + grt = grt0; + } } if (grt != rtc) { String refid = typeRefs.get(grt); @@ -1344,7 +1470,9 @@ public final class Rest { HashMap innerEntryMap = (HashMap) restactMethod.invoke(obj); for (Map.Entry en : innerEntryMap.entrySet()) { Method m = mappingurlToMethod.get(en.getKey()); - if (m != null) en.getValue().annotations = HttpServlet.ActionEntry.annotations(m); + if (m != null) { + en.getValue().annotations = HttpServlet.ActionEntry.annotations(m); + } } tmpentrysfield.set(obj, innerEntryMap); return obj; @@ -1356,8 +1484,12 @@ public final class Rest { final String defmodulename = getWebModuleNameLowerCase(serviceType); final String bigmodulename = getWebModuleName(serviceType); final String catalog = controller == null ? "" : controller.catalog(); - if (!checkName(catalog)) throw new RuntimeException(serviceType.getName() + " have illegal " + RestService.class.getSimpleName() + ".catalog, only 0-9 a-z A-Z _ cannot begin 0-9"); - if (!checkName(defmodulename)) throw new RuntimeException(serviceType.getName() + " have illegal " + RestService.class.getSimpleName() + ".value, only 0-9 a-z A-Z _ cannot begin 0-9"); + if (!checkName(catalog)) { + throw new RuntimeException(serviceType.getName() + " have illegal " + RestService.class.getSimpleName() + ".catalog, only 0-9 a-z A-Z _ cannot begin 0-9"); + } + if (!checkName(defmodulename)) { + throw new RuntimeException(serviceType.getName() + " have illegal " + RestService.class.getSimpleName() + ".value, only 0-9 a-z A-Z _ cannot begin 0-9"); + } ClassWriter cw = new ClassWriter(COMPUTE_FRAMES); FieldVisitor fv; MethodDebugVisitor mv; @@ -1395,23 +1527,41 @@ public final class Rest { final Method[] allMethods = serviceType.getMethods(); Arrays.sort(allMethods, (m1, m2) -> { //必须排序,否则paramTypes顺序容易乱 int s = m1.getName().compareTo(m2.getName()); - if (s != 0) return s; + if (s != 0) { + return s; + } s = Arrays.toString(m1.getParameterTypes()).compareTo(Arrays.toString(m2.getParameterTypes())); return s; }); for (final Method method : allMethods) { - if (Modifier.isStatic(method.getModifiers())) continue; - if (method.isSynthetic()) continue; - if (EXCLUDERMETHODS.contains(method.getName())) continue; - if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { - if ("init".equals(method.getName())) continue; - if ("stop".equals(method.getName())) continue; - if ("destroy".equals(method.getName())) continue; + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + if (method.isSynthetic()) { + continue; + } + if (EXCLUDERMETHODS.contains(method.getName())) { + continue; + } + if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { + if ("init".equals(method.getName())) { + continue; + } + if ("stop".equals(method.getName())) { + continue; + } + if ("destroy".equals(method.getName())) { + continue; + } + } + if (controller == null) { + continue; } - if (controller == null) continue; RestMapping[] mappings = method.getAnnotationsByType(RestMapping.class); - if (!controller.automapping() && mappings.length < 1) continue; + if (!controller.automapping() && mappings.length < 1) { + continue; + } boolean ignore = false; for (RestMapping mapping : mappings) { if (mapping.ignore()) { @@ -1419,7 +1569,9 @@ public final class Rest { break; } } - if (ignore) continue; + if (ignore) { + continue; + } Class[] extypes = method.getExceptionTypes(); if (extypes.length > 0) { @@ -1436,19 +1588,24 @@ public final class Rest { retvalTypes.add(formatRestReturnType(method, serviceType)); if (mappings.length == 0) { //没有Mapping,设置一个默认值 MappingEntry entry = new MappingEntry(serrpconly, methodidex, null, bigmodulename, method); - if (entrys.contains(entry)) throw new RuntimeException(serviceType.getName() + " on " + method.getName() + " 's mapping(" + entry.name + ") is repeat"); + if (entrys.contains(entry)) { + throw new RuntimeException(serviceType.getName() + " on " + method.getName() + " 's mapping(" + entry.name + ") is repeat"); + } entrys.add(entry); } else { for (RestMapping mapping : mappings) { MappingEntry entry = new MappingEntry(serrpconly, methodidex, mapping, defmodulename, method); - if (entrys.contains(entry)) throw new RuntimeException(serviceType.getName() + " on " + method.getName() + " 's mapping(" + entry.name + ") is repeat"); + if (entrys.contains(entry)) { + throw new RuntimeException(serviceType.getName() + " on " + method.getName() + " 's mapping(" + entry.name + ") is repeat"); + } entrys.add(entry); } } methodidex++; } - if (entrys.isEmpty()) return null; //没有可HttpMapping的方法 - + if (entrys.isEmpty()) { + return null; //没有可HttpMapping的方法 + } Collections.sort(entrys); RestClassLoader newLoader = new RestClassLoader(loader); final int moduleid = controller == null ? 0 : controller.moduleid(); @@ -1483,12 +1640,16 @@ public final class Rest { break; } } - if (match) continue; + if (match) { + continue; + } } urlpath += "," + suburl; av1.visit(null, suburl); } - if (urlpath.length() > 0) urlpath = urlpath.substring(1); + if (urlpath.length() > 0) { + urlpath = urlpath.substring(1); + } } else { urlpath = (catalog.isEmpty() ? "/" : ("/" + catalog + "/")) + defmodulename + "/*"; av1.visit(null, urlpath); @@ -1609,7 +1770,9 @@ public final class Rest { int maxLocals = 4; List asmParamNames = asmParamMap == null ? null : asmParamMap.get(method.getName() + ":" + Type.getMethodDescriptor(method)); - if (asmParamNames != null) while (asmParamNames.remove(" ")); //删掉空元素 + if (asmParamNames != null) { + while (asmParamNames.remove(" ")); //删掉空元素 + } List paramlist = new ArrayList<>(); //解析方法中的每个参数 for (int i = 0; i < params.length; i++) { @@ -1622,137 +1785,281 @@ public final class Rest { RestHeader annhead = param.getAnnotation(RestHeader.class); if (annhead != null) { - if (ptype != String.class && ptype != InetSocketAddress.class) throw new RuntimeException("@RestHeader must on String or InetSocketAddress Parameter in " + method); + if (ptype != String.class && ptype != InetSocketAddress.class) { + throw new RuntimeException("@RestHeader must on String or InetSocketAddress Parameter in " + method); + } n = annhead.name(); radix = annhead.radix(); comment = annhead.comment(); required = false; - if (n.isEmpty()) throw new RuntimeException("@RestHeader.value is illegal in " + method); + if (n.isEmpty()) { + throw new RuntimeException("@RestHeader.value is illegal in " + method); + } } RestCookie anncookie = param.getAnnotation(RestCookie.class); if (anncookie != null) { - if (annhead != null) throw new RuntimeException("@RestCookie and @RestHeader cannot on the same Parameter in " + method); - if (ptype != String.class) throw new RuntimeException("@RestCookie must on String Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestCookie and @RestHeader cannot on the same Parameter in " + method); + } + if (ptype != String.class) { + throw new RuntimeException("@RestCookie must on String Parameter in " + method); + } n = anncookie.name(); radix = anncookie.radix(); comment = anncookie.comment(); required = false; - if (n.isEmpty()) throw new RuntimeException("@RestCookie.value is illegal in " + method); + if (n.isEmpty()) { + throw new RuntimeException("@RestCookie.value is illegal in " + method); + } } RestSessionid annsid = param.getAnnotation(RestSessionid.class); if (annsid != null) { - if (annhead != null) throw new RuntimeException("@RestSessionid and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestSessionid and @RestCookie cannot on the same Parameter in " + method); - if (ptype != String.class) throw new RuntimeException("@RestSessionid must on String Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestSessionid and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestSessionid and @RestCookie cannot on the same Parameter in " + method); + } + if (ptype != String.class) { + throw new RuntimeException("@RestSessionid must on String Parameter in " + method); + } required = false; } RestAddress annaddr = param.getAnnotation(RestAddress.class); if (annaddr != null) { - if (annhead != null) throw new RuntimeException("@RestAddress and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestAddress and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestAddress and @RestSessionid cannot on the same Parameter in " + method); - if (ptype != String.class) throw new RuntimeException("@RestAddress must on String Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestAddress and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestAddress and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestAddress and @RestSessionid cannot on the same Parameter in " + method); + } + if (ptype != String.class) { + throw new RuntimeException("@RestAddress must on String Parameter in " + method); + } comment = annaddr.comment(); required = false; } RestLocale annlocale = param.getAnnotation(RestLocale.class); if (annlocale != null) { - if (annhead != null) throw new RuntimeException("@RestLocale and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestLocale and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestLocale and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestLocale and @RestAddress cannot on the same Parameter in " + method); - if (ptype != String.class) throw new RuntimeException("@RestAddress must on String Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestLocale and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestLocale and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestLocale and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestLocale and @RestAddress cannot on the same Parameter in " + method); + } + if (ptype != String.class) { + throw new RuntimeException("@RestAddress must on String Parameter in " + method); + } comment = annlocale.comment(); required = false; } RestBody annbody = param.getAnnotation(RestBody.class); if (annbody != null) { - if (annhead != null) throw new RuntimeException("@RestBody and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestBody and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestBody and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestBody and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestBody and @RestLocale cannot on the same Parameter in " + method); - if (ptype.isPrimitive()) throw new RuntimeException("@RestBody cannot on primitive type Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestBody and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestBody and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestBody and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestBody and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestBody and @RestLocale cannot on the same Parameter in " + method); + } + if (ptype.isPrimitive()) { + throw new RuntimeException("@RestBody cannot on primitive type Parameter in " + method); + } comment = annbody.comment(); } RestUploadFile annfile = param.getAnnotation(RestUploadFile.class); if (annfile != null) { - if (mupload != null) throw new RuntimeException("@RestUploadFile repeat in " + method); + if (mupload != null) { + throw new RuntimeException("@RestUploadFile repeat in " + method); + } mupload = annfile; muploadType = ptype; - if (annhead != null) throw new RuntimeException("@RestUploadFile and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestUploadFile and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestUploadFile and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestUploadFile and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestUploadFile and @RestLocale cannot on the same Parameter in " + method); - if (annbody != null) throw new RuntimeException("@RestUploadFile and @RestBody cannot on the same Parameter in " + method); - if (ptype != byte[].class && ptype != File.class && ptype != File[].class) throw new RuntimeException("@RestUploadFile must on byte[] or File or File[] Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestUploadFile and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestUploadFile and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestUploadFile and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestUploadFile and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestUploadFile and @RestLocale cannot on the same Parameter in " + method); + } + if (annbody != null) { + throw new RuntimeException("@RestUploadFile and @RestBody cannot on the same Parameter in " + method); + } + if (ptype != byte[].class && ptype != File.class && ptype != File[].class) { + throw new RuntimeException("@RestUploadFile must on byte[] or File or File[] Parameter in " + method); + } comment = annfile.comment(); } RestURI annuri = param.getAnnotation(RestURI.class); if (annuri != null) { - if (annhead != null) throw new RuntimeException("@RestURI and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestURI and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestURI and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestURI and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestURI and @RestLocale cannot on the same Parameter in " + method); - if (annbody != null) throw new RuntimeException("@RestURI and @RestBody cannot on the same Parameter in " + method); - if (annfile != null) throw new RuntimeException("@RestURI and @RestUploadFile cannot on the same Parameter in " + method); - if (ptype != String.class) throw new RuntimeException("@RestURI must on String Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestURI and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestURI and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestURI and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestURI and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestURI and @RestLocale cannot on the same Parameter in " + method); + } + if (annbody != null) { + throw new RuntimeException("@RestURI and @RestBody cannot on the same Parameter in " + method); + } + if (annfile != null) { + throw new RuntimeException("@RestURI and @RestUploadFile cannot on the same Parameter in " + method); + } + if (ptype != String.class) { + throw new RuntimeException("@RestURI must on String Parameter in " + method); + } comment = annuri.comment(); } RestUserid userid = param.getAnnotation(RestUserid.class); if (userid != null) { - if (annhead != null) throw new RuntimeException("@RestUserid and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestUserid and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestUserid and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestUserid and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestUserid and @RestLocale cannot on the same Parameter in " + method); - if (annbody != null) throw new RuntimeException("@RestUserid and @RestBody cannot on the same Parameter in " + method); - if (annfile != null) throw new RuntimeException("@RestUserid and @RestUploadFile cannot on the same Parameter in " + method); - if (!ptype.isPrimitive() && !java.io.Serializable.class.isAssignableFrom(ptype)) throw new RuntimeException("@RestUserid must on java.io.Serializable Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestUserid and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestUserid and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestUserid and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestUserid and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestUserid and @RestLocale cannot on the same Parameter in " + method); + } + if (annbody != null) { + throw new RuntimeException("@RestUserid and @RestBody cannot on the same Parameter in " + method); + } + if (annfile != null) { + throw new RuntimeException("@RestUserid and @RestUploadFile cannot on the same Parameter in " + method); + } + if (!ptype.isPrimitive() && !java.io.Serializable.class.isAssignableFrom(ptype)) { + throw new RuntimeException("@RestUserid must on java.io.Serializable Parameter in " + method); + } comment = ""; required = false; } RestHeaders annheaders = param.getAnnotation(RestHeaders.class); if (annheaders != null) { - if (annhead != null) throw new RuntimeException("@RestHeaders and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestHeaders and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestHeaders and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestHeaders and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestHeaders and @RestLocale cannot on the same Parameter in " + method); - if (annbody != null) throw new RuntimeException("@RestHeaders and @RestBody cannot on the same Parameter in " + method); - if (annfile != null) throw new RuntimeException("@RestHeaders and @RestUploadFile cannot on the same Parameter in " + method); - if (userid != null) throw new RuntimeException("@RestHeaders and @RestUserid cannot on the same Parameter in " + method); - if (!TYPE_MAP_STRING_STRING.equals(param.getParameterizedType())) throw new RuntimeException("@RestHeaders must on Map Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestHeaders and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestHeaders and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestHeaders and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestHeaders and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestHeaders and @RestLocale cannot on the same Parameter in " + method); + } + if (annbody != null) { + throw new RuntimeException("@RestHeaders and @RestBody cannot on the same Parameter in " + method); + } + if (annfile != null) { + throw new RuntimeException("@RestHeaders and @RestUploadFile cannot on the same Parameter in " + method); + } + if (userid != null) { + throw new RuntimeException("@RestHeaders and @RestUserid cannot on the same Parameter in " + method); + } + if (!TYPE_MAP_STRING_STRING.equals(param.getParameterizedType())) { + throw new RuntimeException("@RestHeaders must on Map Parameter in " + method); + } comment = ""; required = false; } RestParams annparams = param.getAnnotation(RestParams.class); if (annparams != null) { - if (annhead != null) throw new RuntimeException("@RestParams and @RestHeader cannot on the same Parameter in " + method); - if (anncookie != null) throw new RuntimeException("@RestParams and @RestCookie cannot on the same Parameter in " + method); - if (annsid != null) throw new RuntimeException("@RestParams and @RestSessionid cannot on the same Parameter in " + method); - if (annaddr != null) throw new RuntimeException("@RestParams and @RestAddress cannot on the same Parameter in " + method); - if (annlocale != null) throw new RuntimeException("@RestParams and @RestLocale cannot on the same Parameter in " + method); - if (annbody != null) throw new RuntimeException("@RestParams and @RestBody cannot on the same Parameter in " + method); - if (annfile != null) throw new RuntimeException("@RestParams and @RestUploadFile cannot on the same Parameter in " + method); - if (userid != null) throw new RuntimeException("@RestParams and @RestUserid cannot on the same Parameter in " + method); - if (annheaders != null) throw new RuntimeException("@RestParams and @RestHeaders cannot on the same Parameter in " + method); - if (!TYPE_MAP_STRING_STRING.equals(param.getParameterizedType())) throw new RuntimeException("@RestParams must on Map Parameter in " + method); + if (annhead != null) { + throw new RuntimeException("@RestParams and @RestHeader cannot on the same Parameter in " + method); + } + if (anncookie != null) { + throw new RuntimeException("@RestParams and @RestCookie cannot on the same Parameter in " + method); + } + if (annsid != null) { + throw new RuntimeException("@RestParams and @RestSessionid cannot on the same Parameter in " + method); + } + if (annaddr != null) { + throw new RuntimeException("@RestParams and @RestAddress cannot on the same Parameter in " + method); + } + if (annlocale != null) { + throw new RuntimeException("@RestParams and @RestLocale cannot on the same Parameter in " + method); + } + if (annbody != null) { + throw new RuntimeException("@RestParams and @RestBody cannot on the same Parameter in " + method); + } + if (annfile != null) { + throw new RuntimeException("@RestParams and @RestUploadFile cannot on the same Parameter in " + method); + } + if (userid != null) { + throw new RuntimeException("@RestParams and @RestUserid cannot on the same Parameter in " + method); + } + if (annheaders != null) { + throw new RuntimeException("@RestParams and @RestHeaders cannot on the same Parameter in " + method); + } + if (!TYPE_MAP_STRING_STRING.equals(param.getParameterizedType())) { + throw new RuntimeException("@RestParams must on Map Parameter in " + method); + } comment = ""; } RestParam annpara = param.getAnnotation(RestParam.class); - if (annpara != null) radix = annpara.radix(); - if (annpara != null) comment = annpara.comment(); - if (annpara != null) required = annpara.required(); - if (n == null) n = (annpara == null || annpara.name().isEmpty()) ? null : annpara.name(); - if (n == null && ptype == userType) n = "&"; //用户类型特殊处理 - if (n == null && asmParamNames != null && asmParamNames.size() > i) n = asmParamNames.get(i); + if (annpara != null) { + radix = annpara.radix(); + } + if (annpara != null) { + comment = annpara.comment(); + } + if (annpara != null) { + required = annpara.required(); + } + if (n == null) { + n = (annpara == null || annpara.name().isEmpty()) ? null : annpara.name(); + } + if (n == null && ptype == userType) { + n = "&"; //用户类型特殊处理 + } + if (n == null && asmParamNames != null && asmParamNames.size() > i) { + n = asmParamNames.get(i); + } if (n == null) { if (param.isNamePresent()) { n = param.getName(); @@ -1767,13 +2074,23 @@ public final class Rest { && !ptype.getName().startsWith("java") && n.charAt(0) != '#' && !"&".equals(n)) { //判断Json对象是否包含@RestUploadFile Class loop = ptype; do { - if (loop == null || loop.isInterface()) break; //接口时getSuperclass可能会得到null + if (loop == null || loop.isInterface()) { + break; //接口时getSuperclass可能会得到null + } for (Field field : loop.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) continue; - if (Modifier.isFinal(field.getModifiers())) continue; + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + if (Modifier.isFinal(field.getModifiers())) { + continue; + } RestUploadFile ruf = field.getAnnotation(RestUploadFile.class); - if (ruf == null) continue; - if (mupload != null) throw new RuntimeException("@RestUploadFile repeat in " + method + " or field " + field); + if (ruf == null) { + continue; + } + if (mupload != null) { + throw new RuntimeException("@RestUploadFile repeat in " + method + " or field " + field); + } mupload = ruf; muploadType = field.getType(); } @@ -1800,7 +2117,9 @@ public final class Rest { } av0 = mv.visitAnnotation(mappingDesc, true); String url = (catalog.isEmpty() ? "/" : ("/" + catalog + "/")) + (defmodulename.isEmpty() ? "" : (defmodulename + "/")) + entry.name + (reqpath ? "/" : ""); - if ("//".equals(url)) url = "/"; + if ("//".equals(url)) { + url = "/"; + } av0.visit("url", url); av0.visit("name", (defmodulename.isEmpty() ? "" : (defmodulename + "_")) + entry.name); av0.visit("example", entry.example); @@ -1824,7 +2143,9 @@ public final class Rest { ParameterizedType ptgrt = (ParameterizedType) returnGenericNoFutureType; returnGenericNoFutureType = ptgrt.getActualTypeArguments()[0]; rtc = TypeToken.typeToClass(returnGenericNoFutureType); - if (rtc == null) rtc = Object.class; //应该不会发生吧? + if (rtc == null) { + rtc = Object.class; //应该不会发生吧? + } } av0.visit("result", Type.getType(Type.getDescriptor(rtc))); if (returnGenericNoFutureType != rtc) { @@ -1898,9 +2219,15 @@ public final class Rest { for (Object[] ps : paramlist) { //{param, n, ptype, radix, comment, required, annpara, annsid, annaddr, annlocale, annhead, anncookie, annbody, annfile, annuri, annuserid, annheaders, annparams, paramtype} String n = ps[1].toString(); final boolean isuserid = ((RestUserid) ps[headIndex + 5]) != null; //是否取userid - if (n.indexOf('&') >= 0 || isuserid) continue; //@RestUserid 不需要生成 @HttpParam - if (((RestAddress) ps[8]) != null) continue; //@RestAddress 不需要生成 @HttpParam - if (((RestLocale) ps[9]) != null) continue; //@RestLocale 不需要生成 @HttpParam + if (n.indexOf('&') >= 0 || isuserid) { + continue; //@RestUserid 不需要生成 @HttpParam + } + if (((RestAddress) ps[8]) != null) { + continue; //@RestAddress 不需要生成 @HttpParam + } + if (((RestLocale) ps[9]) != null) { + continue; //@RestLocale 不需要生成 @HttpParam + } final boolean ishead = ((RestHeader) ps[headIndex]) != null; //是否取getHeader 而不是 getParameter final boolean iscookie = ((RestCookie) ps[headIndex + 1]) != null; //是否取getCookie final boolean isbody = ((RestBody) ps[headIndex + 2]) != null; //是否取getBody @@ -2001,7 +2328,9 @@ public final class Rest { RestHeaders annheaders = (RestHeaders) ps[headIndex + 6]; RestParams annparams = (RestParams) ps[headIndex + 7]; java.lang.reflect.Type pgentype = (java.lang.reflect.Type) ps[headIndex + 8]; - if (dynsimple && (annsid != null || annaddr != null || annlocale != null || annhead != null || anncookie != null || annfile != null || annheaders != null)) dynsimple = false; + if (dynsimple && (annsid != null || annaddr != null || annlocale != null || annhead != null || anncookie != null || annfile != null || annheaders != null)) { + dynsimple = false; + } final boolean ishead = annhead != null; //是否取getHeader 而不是 getParameter final boolean iscookie = anncookie != null; //是否取getCookie @@ -2382,11 +2711,19 @@ public final class Rest { Set fields = new HashSet<>(); Map attrParaNames = new LinkedHashMap<>(); do { - if (loop == null || loop.isInterface()) break; //接口时getSuperclass可能会得到null + if (loop == null || loop.isInterface()) { + break; //接口时getSuperclass可能会得到null + } for (Field field : loop.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) continue; - if (Modifier.isFinal(field.getModifiers())) continue; - if (fields.contains(field.getName())) continue; + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + if (Modifier.isFinal(field.getModifiers())) { + continue; + } + if (fields.contains(field.getName())) { + continue; + } RestHeader rh = field.getAnnotation(RestHeader.class); RestCookie rc = field.getAnnotation(RestCookie.class); RestSessionid rs = field.getAnnotation(RestSessionid.class); @@ -2395,18 +2732,34 @@ public final class Rest { RestBody rb = field.getAnnotation(RestBody.class); RestUploadFile ru = field.getAnnotation(RestUploadFile.class); RestURI ri = field.getAnnotation(RestURI.class); - if (rh == null && rc == null && ra == null && rl == null && rb == null && rs == null && ru == null && ri == null) continue; - if (rh != null && field.getType() != String.class && field.getType() != InetSocketAddress.class) throw new RuntimeException("@RestHeader must on String Field in " + field); - if (rc != null && field.getType() != String.class) throw new RuntimeException("@RestCookie must on String Field in " + field); - if (rs != null && field.getType() != String.class) throw new RuntimeException("@RestSessionid must on String Field in " + field); - if (ra != null && field.getType() != String.class) throw new RuntimeException("@RestAddress must on String Field in " + field); - if (rl != null && field.getType() != String.class) throw new RuntimeException("@RestLocale must on String Field in " + field); - if (rb != null && field.getType().isPrimitive()) throw new RuntimeException("@RestBody must on cannot on primitive type Field in " + field); + if (rh == null && rc == null && ra == null && rl == null && rb == null && rs == null && ru == null && ri == null) { + continue; + } + if (rh != null && field.getType() != String.class && field.getType() != InetSocketAddress.class) { + throw new RuntimeException("@RestHeader must on String Field in " + field); + } + if (rc != null && field.getType() != String.class) { + throw new RuntimeException("@RestCookie must on String Field in " + field); + } + if (rs != null && field.getType() != String.class) { + throw new RuntimeException("@RestSessionid must on String Field in " + field); + } + if (ra != null && field.getType() != String.class) { + throw new RuntimeException("@RestAddress must on String Field in " + field); + } + if (rl != null && field.getType() != String.class) { + throw new RuntimeException("@RestLocale must on String Field in " + field); + } + if (rb != null && field.getType().isPrimitive()) { + throw new RuntimeException("@RestBody must on cannot on primitive type Field in " + field); + } if (ru != null && field.getType() != byte[].class && field.getType() != File.class && field.getType() != File[].class) { throw new RuntimeException("@RestUploadFile must on byte[] or File or File[] Field in " + field); } - if (ri != null && field.getType() != String.class) throw new RuntimeException("@RestURI must on String Field in " + field); + if (ri != null && field.getType() != String.class) { + throw new RuntimeException("@RestURI must on String Field in " + field); + } org.redkale.util.Attribute attr = org.redkale.util.Attribute.create(loop, field); String attrFieldName; String restname = ""; @@ -3046,7 +3399,9 @@ public final class Rest { HashMap innerEntryMap = (HashMap) restactMethod.invoke(obj); for (Map.Entry en : innerEntryMap.entrySet()) { Method m = mappingurlToMethod.get(en.getKey()); - if (m != null) en.getValue().annotations = HttpServlet.ActionEntry.annotations(m); + if (m != null) { + en.getValue().annotations = HttpServlet.ActionEntry.annotations(m); + } } tmpentrysfield.set(obj, innerEntryMap); RedkaleClassLoader.putReflectionField(HttpServlet.class.getName(), tmpentrysfield); @@ -3062,7 +3417,9 @@ public final class Rest { if (method.getReturnType() == void.class) { return RetResult.TYPE_RET_STRING; } else if (HttpResult.class.isAssignableFrom(returnType)) { - if (!(t instanceof ParameterizedType)) return Object.class; + if (!(t instanceof ParameterizedType)) { + return Object.class; + } ParameterizedType pt = (ParameterizedType) t; return pt.getActualTypeArguments()[0]; } else if (CompletionStage.class.isAssignableFrom(returnType)) { @@ -3070,7 +3427,9 @@ public final class Rest { java.lang.reflect.Type grt = pt.getActualTypeArguments()[0]; Class gct = TypeToken.typeToClass(grt); if (HttpResult.class.isAssignableFrom(gct)) { - if (!(grt instanceof ParameterizedType)) return Object.class; + if (!(grt instanceof ParameterizedType)) { + return Object.class; + } ParameterizedType pt2 = (ParameterizedType) grt; return pt2.getActualTypeArguments()[0]; } else if (gct == void.class || gct == Void.class) { @@ -3085,8 +3444,12 @@ public final class Rest { } private static boolean checkName(String name) { //只能是字母、数字和下划线,且不能以数字开头 - if (name.isEmpty()) return true; - if (name.charAt(0) >= '0' && name.charAt(0) <= '9') return false; + if (name.isEmpty()) { + return true; + } + if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { + return false; + } for (char ch : name.toCharArray()) { if (!((ch >= '0' && ch <= '9') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { //不能含特殊字符 return false; @@ -3096,8 +3459,12 @@ public final class Rest { } private static boolean checkName2(String name) { //只能是字母、数字、短横、点和下划线,且不能以数字开头 - if (name.isEmpty()) return true; - if (name.charAt(0) >= '0' && name.charAt(0) <= '9') return false; + if (name.isEmpty()) { + return true; + } + if (name.charAt(0) >= '0' && name.charAt(0) <= '9') { + return false; + } for (char ch : name.toCharArray()) { if (!((ch >= '0' && ch <= '9') || ch == '_' || ch == '-' || ch == '.' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { //不能含特殊字符 return false; @@ -3117,7 +3484,9 @@ public final class Rest { @Override protected Class findClass(String name) throws ClassNotFoundException { byte[] classData = classes.get(name); - if (classData == null) return super.findClass(name); + if (classData == null) { + return super.findClass(name); + } return super.defineClass(name, classData, 0, classData.length); } @@ -3143,11 +3512,15 @@ public final class Rest { } public MappingEntry(final boolean serrpconly, int methodidx, RestMapping mapping, final String defmodulename, Method method) { - if (mapping == null) mapping = DEFAULT__MAPPING; + if (mapping == null) { + mapping = DEFAULT__MAPPING; + } this.methodidx = methodidx; this.ignore = mapping.ignore(); String n = mapping.name(); - if (n.isEmpty()) n = method.getName(); + if (n.isEmpty()) { + n = method.getName(); + } this.name = n.trim(); this.example = mapping.example(); this.mappingMethod = method; @@ -3212,8 +3585,12 @@ public final class Rest { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } return this.name.equals(((MappingEntry) obj).name); } diff --git a/src/main/java/org/redkale/net/http/RestBody.java b/src/main/java/org/redkale/net/http/RestBody.java index 0dbc85cfb..d0bad80cf 100644 --- a/src/main/java/org/redkale/net/http/RestBody.java +++ b/src/main/java/org/redkale/net/http/RestBody.java @@ -5,9 +5,10 @@ */ package org.redkale.net.http; -import java.lang.annotation.*; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import java.lang.annotation.*; +import static java.lang.annotation.ElementType.*; /** * 只能注解于RestService类的方法的String/byte[]/JavaBean参数或参数内的String/byte[]/JavaBean字段 @@ -31,14 +32,14 @@ public @interface RestBody { * @return boolean */ boolean required() default true; - + /** * for OpenAPI Specification 3.1.0 - * + * * @return String */ - String example() default ""; - + String example() default ""; + /** * 备注描述, 对应@HttpParam.comment * diff --git a/src/main/java/org/redkale/net/http/WebSocketAddress.java b/src/main/java/org/redkale/net/http/WebSocketAddress.java index f04a1e130..4996d8fc1 100644 --- a/src/main/java/org/redkale/net/http/WebSocketAddress.java +++ b/src/main/java/org/redkale/net/http/WebSocketAddress.java @@ -44,9 +44,15 @@ public class WebSocketAddress implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } final WebSocketAddress other = (WebSocketAddress) obj; return Objects.equals(this.topic, other.topic) && Objects.equals(this.addr, other.addr); } diff --git a/src/main/java/org/redkale/net/http/WebSocketEngine.java b/src/main/java/org/redkale/net/http/WebSocketEngine.java index 9f64f312b..f2458100e 100644 --- a/src/main/java/org/redkale/net/http/WebSocketEngine.java +++ b/src/main/java/org/redkale/net/http/WebSocketEngine.java @@ -5,21 +5,19 @@ */ package org.redkale.net.http; -import static org.redkale.net.http.WebSocketServlet.DEFAILT_LIVEINTERVAL; -import java.io.*; +import java.io.Serializable; import java.util.*; import java.util.concurrent.*; -import java.util.concurrent.atomic.*; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.*; import java.util.logging.*; -import java.util.stream.*; - +import java.util.stream.Stream; import org.redkale.annotation.Comment; import org.redkale.convert.Convert; import org.redkale.net.Cryptor; import static org.redkale.net.http.WebSocket.RETCODE_GROUP_EMPTY; import static org.redkale.net.http.WebSocketServlet.*; -import org.redkale.util.*; +import org.redkale.util.AnyValue; /** * @@ -103,13 +101,25 @@ public class WebSocketEngine { void init(AnyValue conf) { AnyValue props = conf; - if (conf != null && conf.getAnyValue("properties") != null) props = conf.getAnyValue("properties"); + if (conf != null && conf.getAnyValue("properties") != null) { + props = conf.getAnyValue("properties"); + } this.liveinterval = props == null ? (liveinterval < 0 ? DEFAILT_LIVEINTERVAL : liveinterval) : props.getIntValue(WEBPARAM__LIVEINTERVAL, (liveinterval < 0 ? DEFAILT_LIVEINTERVAL : liveinterval)); - if (liveinterval <= 0) return; - if (props != null) this.wsmaxconns = props.getIntValue(WEBPARAM__WSMAXCONNS, this.wsmaxconns); - if (props != null) this.wsthreads = props.getIntValue(WEBPARAM__WSTHREADS, this.wsthreads); - if (props != null) this.wsmaxbody = props.getIntValue(WEBPARAM__WSMAXBODY, this.wsmaxbody); - if (scheduler != null) return; + if (liveinterval <= 0) { + return; + } + if (props != null) { + this.wsmaxconns = props.getIntValue(WEBPARAM__WSMAXCONNS, this.wsmaxconns); + } + if (props != null) { + this.wsthreads = props.getIntValue(WEBPARAM__WSTHREADS, this.wsthreads); + } + if (props != null) { + this.wsmaxbody = props.getIntValue(WEBPARAM__WSMAXBODY, this.wsmaxbody); + } + if (scheduler != null) { + return; + } this.scheduler = new ScheduledThreadPoolExecutor(1, (Runnable r) -> { final Thread t = new Thread(r, "Redkale-" + engineid + "-WebSocket-LiveInterval-Thread"); t.setDaemon(true); @@ -125,11 +135,15 @@ public class WebSocketEngine { logger.log(Level.SEVERE, "WebSocketEngine schedule(interval=" + liveinterval + "s) ping error", t); } }, delay, liveinterval, TimeUnit.SECONDS); - if (logger.isLoggable(Level.FINEST)) logger.finest(this.getClass().getSimpleName() + "(" + engineid + ")" + " start keeplive(wsmaxconns:" + wsmaxconns + ", delay:" + delay + "s, interval:" + liveinterval + "s) scheduler executor"); + if (logger.isLoggable(Level.FINEST)) { + logger.finest(this.getClass().getSimpleName() + "(" + engineid + ")" + " start keeplive(wsmaxconns:" + wsmaxconns + ", delay:" + delay + "s, interval:" + liveinterval + "s) scheduler executor"); + } } void destroy(AnyValue conf) { - if (scheduler != null) scheduler.shutdownNow(); + if (scheduler != null) { + scheduler.shutdownNow(); + } } @Comment("添加WebSocket") @@ -146,18 +160,24 @@ public class WebSocketEngine { currconns.incrementAndGet(); list.add(socket); } - if (node != null) return node.connect(socket._userid); + if (node != null) { + return node.connect(socket._userid); + } return null; } @Comment("从WebSocketEngine删除指定WebSocket") CompletableFuture removeLocalThenDisconnect(WebSocket socket) { Serializable userid = socket._userid; - if (userid == null) return null; //尚未登录成功 + if (userid == null) { + return null; //尚未登录成功 + } if (single) { currconns.decrementAndGet(); websockets.remove(userid); - if (node != null) return node.disconnect(userid); + if (node != null) { + return node.disconnect(userid); + } } else { //非线程安全, 在常规场景中无需锁 List list = websockets2.get(userid); if (list != null) { @@ -174,7 +194,9 @@ public class WebSocketEngine { @Comment("更改WebSocket的userid") CompletableFuture changeLocalUserid(WebSocket socket, final Serializable newuserid) { - if (newuserid == null) throw new NullPointerException("newuserid is null"); + if (newuserid == null) { + throw new NullPointerException("newuserid is null"); + } final Serializable olduserid = socket._userid; socket._userid = newuserid; if (single) { @@ -184,7 +206,9 @@ public class WebSocketEngine { List oldlist = websockets2.get(olduserid); if (oldlist != null) { oldlist.remove(socket); - if (oldlist.isEmpty()) websockets2.remove(olduserid); + if (oldlist.isEmpty()) { + websockets2.remove(olduserid); + } } List newlist = websockets2.get(newuserid); if (newlist == null) { @@ -193,7 +217,9 @@ public class WebSocketEngine { } newlist.add(socket); } - if (node != null) return node.changeUserid(olduserid, newuserid); + if (node != null) { + return node.changeUserid(olduserid, newuserid); + } return CompletableFuture.completedFuture(null); } @@ -201,12 +227,16 @@ public class WebSocketEngine { public int forceCloseLocalWebSocket(Serializable userid) { if (single) { WebSocket ws = websockets.get(userid); - if (ws == null) return 0; + if (ws == null) { + return 0; + } ws.close(); return 1; } List list = websockets2.get(userid); - if (list == null || list.isEmpty()) return 0; + if (list == null || list.isEmpty()) { + return 0; + } List list2 = new ArrayList<>(list); for (WebSocket ws : list2) { ws.close(); @@ -276,13 +306,17 @@ public class WebSocketEngine { CompletableFuture future = null; if (single) { for (WebSocket websocket : websockets.values()) { - if (predicate != null && !predicate.test(websocket)) continue; + if (predicate != null && !predicate.test(websocket)) { + continue; + } future = future == null ? websocket.send(message, last) : future.thenCombine(websocket.send(message, last), (a, b) -> a | (Integer) b); } } else { for (List list : websockets2.values()) { for (WebSocket websocket : list) { - if (predicate != null && !predicate.test(websocket)) continue; + if (predicate != null && !predicate.test(websocket)) { + continue; + } future = future == null ? websocket.send(message, last) : future.thenCombine(websocket.send(message, last), (a, b) -> a | (Integer) b); } } @@ -355,13 +389,17 @@ public class WebSocketEngine { if (single) { for (Serializable userid : userids) { WebSocket websocket = websockets.get(userid); - if (websocket == null) continue; + if (websocket == null) { + continue; + } future = future == null ? websocket.send(message, last) : future.thenCombine(websocket.send(message, last), (a, b) -> a | (Integer) b); } } else { for (Serializable userid : userids) { List list = websockets2.get(userid); - if (list == null) continue; + if (list == null) { + continue; + } for (WebSocket websocket : list) { future = future == null ? websocket.send(message, last) : future.thenCombine(websocket.send(message, last), (a, b) -> a | (Integer) b); } @@ -404,13 +442,17 @@ public class WebSocketEngine { if (single) { for (Serializable userid : userids) { WebSocket websocket = websockets.get(userid); - if (websocket == null) continue; + if (websocket == null) { + continue; + } future = future == null ? websocket.action(action) : future.thenCombine(websocket.action(action), (a, b) -> a | (Integer) b); } } else { for (Serializable userid : userids) { List list = websockets2.get(userid); - if (list == null) continue; + if (list == null) { + continue; + } for (WebSocket websocket : list) { future = future == null ? websocket.action(action) : future.thenCombine(websocket.action(action), (a, b) -> a | (Integer) b); } @@ -431,13 +473,17 @@ public class WebSocketEngine { @Comment("连接数是否达到上限") public boolean isLocalConnLimited() { - if (this.wsmaxconns < 1) return false; + if (this.wsmaxconns < 1) { + return false; + } return currconns.get() >= this.wsmaxconns; } @Comment("获取所有连接") public Collection getLocalWebSockets() { - if (single) return websockets.values(); + if (single) { + return websockets.values(); + } List list = new ArrayList<>(); websockets2.values().forEach(x -> list.addAll(x)); return list; @@ -445,7 +491,9 @@ public class WebSocketEngine { @Comment("获取所有连接") public void forEachLocalWebSocket(Consumer consumer) { - if (consumer == null) return; + if (consumer == null) { + return; + } if (single) { websockets.values().stream().forEach(consumer); } else { @@ -455,7 +503,9 @@ public class WebSocketEngine { @Comment("获取当前连接总数") public int getLocalWebSocketSize() { - if (single) return websockets.size(); + if (single) { + return websockets.size(); + } return (int) websockets2.values().stream().mapToInt(sublist -> sublist.size()).count(); } @@ -471,7 +521,9 @@ public class WebSocketEngine { @Comment("适用于单用户单连接模式") public WebSocket findLocalWebSocket(Serializable userid) { - if (single) return websockets.get(userid); + if (single) { + return websockets.get(userid); + } List list = websockets2.get(userid); return (list == null || list.isEmpty()) ? null : list.get(list.size() - 1); } diff --git a/src/main/java/org/redkale/net/http/WebSocketNodeService.java b/src/main/java/org/redkale/net/http/WebSocketNodeService.java index 670e341ff..61f846bae 100644 --- a/src/main/java/org/redkale/net/http/WebSocketNodeService.java +++ b/src/main/java/org/redkale/net/http/WebSocketNodeService.java @@ -1,17 +1,16 @@ package org.redkale.net.http; - -import java.io.*; -import java.net.*; +import java.io.Serializable; +import java.net.InetSocketAddress; import java.util.*; -import java.util.concurrent.*; +import java.util.concurrent.CompletableFuture; import java.util.logging.Level; -import static org.redkale.net.http.WebSocket.RETCODE_GROUP_EMPTY; - import org.redkale.annotation.AutoLoad; import org.redkale.annotation.ResourceType; +import static org.redkale.net.http.WebSocket.RETCODE_GROUP_EMPTY; +import org.redkale.net.http.WebSocketNodeService; import org.redkale.service.*; -import org.redkale.util.*; +import org.redkale.util.AnyValue; /** * @@ -40,8 +39,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { @Override public CompletableFuture> getWebSocketAddresses(@RpcTargetTopic String topic, final @RpcTargetAddress InetSocketAddress targetAddress, final Serializable groupid) { - if ((topic == null || !topic.equals(this.wsNodeAddress.getTopic())) && (localSncpAddress == null || !localSncpAddress.equals(targetAddress))) return remoteWebSocketAddresses(topic, targetAddress, groupid); - if (this.localEngine == null) return CompletableFuture.completedFuture(new ArrayList<>()); + if ((topic == null || !topic.equals(this.wsNodeAddress.getTopic())) && (localSncpAddress == null || !localSncpAddress.equals(targetAddress))) { + return remoteWebSocketAddresses(topic, targetAddress, groupid); + } + if (this.localEngine == null) { + return CompletableFuture.completedFuture(new ArrayList<>()); + } final List rs = new ArrayList<>(); this.localEngine.getLocalWebSockets(groupid).forEach(x -> rs.add(x.getRemoteAddr())); return CompletableFuture.completedFuture(rs); @@ -49,31 +52,41 @@ public class WebSocketNodeService extends WebSocketNode implements Service { @Override public CompletableFuture sendMessage(@RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress, Object message, boolean last, Serializable... userids) { - if (this.localEngine == null) return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + if (this.localEngine == null) { + return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + } return this.localEngine.sendLocalMessage(message, last, userids); } @Override public CompletableFuture broadcastMessage(@RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress, final WebSocketRange wsrange, Object message, boolean last) { - if (this.localEngine == null) return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + if (this.localEngine == null) { + return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + } return this.localEngine.broadcastLocalMessage(wsrange, message, last); } @Override public CompletableFuture sendAction(@RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress, final WebSocketAction action, Serializable... userids) { - if (this.localEngine == null) return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + if (this.localEngine == null) { + return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + } return this.localEngine.sendLocalAction(action, userids); } @Override public CompletableFuture broadcastAction(@RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress, final WebSocketAction action) { - if (this.localEngine == null) return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + if (this.localEngine == null) { + return CompletableFuture.completedFuture(RETCODE_GROUP_EMPTY); + } return this.localEngine.broadcastLocalAction(action); } @Override public CompletableFuture getUserSize(@RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress) { - if (this.localEngine == null) return CompletableFuture.completedFuture(0); + if (this.localEngine == null) { + return CompletableFuture.completedFuture(0); + } return CompletableFuture.completedFuture(this.localEngine.getLocalUserSize()); } @@ -89,8 +102,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { public CompletableFuture connect(Serializable userid, WebSocketAddress wsaddr) { tryAcquireSemaphore(); CompletableFuture future = source.saddAsync(WS_SOURCE_KEY_USERID_PREFIX + userid, WebSocketAddress.class, wsaddr); - if (semaphore != null) future.whenComplete((r, e) -> releaseSemaphore()); - if (logger.isLoggable(Level.FINEST)) logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " connect from " + wsaddr); + if (semaphore != null) { + future.whenComplete((r, e) -> releaseSemaphore()); + } + if (logger.isLoggable(Level.FINEST)) { + logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " connect from " + wsaddr); + } return future; } @@ -106,8 +123,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { public CompletableFuture disconnect(Serializable userid, WebSocketAddress wsaddr) { tryAcquireSemaphore(); CompletableFuture future = source.sremAsync(WS_SOURCE_KEY_USERID_PREFIX + userid, WebSocketAddress.class, wsaddr); - if (semaphore != null) future.whenComplete((r, e) -> releaseSemaphore()); - if (logger.isLoggable(Level.FINEST)) logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " disconnect from " + wsaddr); + if (semaphore != null) { + future.whenComplete((r, e) -> releaseSemaphore()); + } + if (logger.isLoggable(Level.FINEST)) { + logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " disconnect from " + wsaddr); + } return future.thenApply(v -> null); } @@ -125,8 +146,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { tryAcquireSemaphore(); CompletableFuture future = source.saddAsync(WS_SOURCE_KEY_USERID_PREFIX + newuserid, WebSocketAddress.class, wsaddr); future = future.thenAccept((a) -> source.sremAsync(WS_SOURCE_KEY_USERID_PREFIX + olduserid, WebSocketAddress.class, wsaddr)); - if (semaphore != null) future.whenComplete((r, e) -> releaseSemaphore()); - if (logger.isLoggable(Level.FINEST)) logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + olduserid + " changeUserid to " + newuserid + " from " + wsaddr); + if (semaphore != null) { + future.whenComplete((r, e) -> releaseSemaphore()); + } + if (logger.isLoggable(Level.FINEST)) { + logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + olduserid + " changeUserid to " + newuserid + " from " + wsaddr); + } return future; } @@ -141,8 +166,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { */ @Override public CompletableFuture existsWebSocket(Serializable userid, @RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress) { - if (logger.isLoggable(Level.FINEST)) logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " existsWebSocket from " + targetAddress); - if (localEngine == null) return CompletableFuture.completedFuture(false); + if (logger.isLoggable(Level.FINEST)) { + logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " existsWebSocket from " + targetAddress); + } + if (localEngine == null) { + return CompletableFuture.completedFuture(false); + } return CompletableFuture.completedFuture(localEngine.existsLocalWebSocket(userid)); } @@ -158,8 +187,12 @@ public class WebSocketNodeService extends WebSocketNode implements Service { @Override public CompletableFuture forceCloseWebSocket(Serializable userid, @RpcTargetTopic String topic, @RpcTargetAddress InetSocketAddress targetAddress) { //不能从sncpNodeAddresses中移除,因为engine.forceCloseWebSocket 会调用到disconnect - if (logger.isLoggable(Level.FINEST)) logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " forceCloseWebSocket from " + targetAddress); - if (localEngine == null) return CompletableFuture.completedFuture(0); + if (logger.isLoggable(Level.FINEST)) { + logger.finest(WebSocketNodeService.class.getSimpleName() + ".event: " + userid + " forceCloseWebSocket from " + targetAddress); + } + if (localEngine == null) { + return CompletableFuture.completedFuture(0); + } return CompletableFuture.completedFuture(localEngine.forceCloseLocalWebSocket(userid)); } } diff --git a/src/main/java/org/redkale/net/http/WebSocketPacket.java b/src/main/java/org/redkale/net/http/WebSocketPacket.java index 4cc22bc0e..3a2f6e6e7 100644 --- a/src/main/java/org/redkale/net/http/WebSocketPacket.java +++ b/src/main/java/org/redkale/net/http/WebSocketPacket.java @@ -5,7 +5,7 @@ */ package org.redkale.net.http; -import java.io.*; +import java.io.Serializable; import java.nio.charset.StandardCharsets; import org.redkale.net.http.WebSocketPacket.FrameType; @@ -111,7 +111,9 @@ public final class WebSocketPacket { } public String toSimpleString() { - if (payload == null) return null; + if (payload == null) { + return null; + } return type == FrameType.TEXT ? new String(payload, StandardCharsets.UTF_8) : ("bytes(" + payload.length + ")"); } diff --git a/src/main/java/org/redkale/net/http/WebSocketReadHandler.java b/src/main/java/org/redkale/net/http/WebSocketReadHandler.java index 98d455398..6ea8256c7 100644 --- a/src/main/java/org/redkale/net/http/WebSocketReadHandler.java +++ b/src/main/java/org/redkale/net/http/WebSocketReadHandler.java @@ -5,14 +5,13 @@ */ package org.redkale.net.http; -import java.util.logging.*; import java.nio.ByteBuffer; import java.nio.channels.CompletionHandler; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; -import java.util.logging.Level; +import java.util.logging.*; import org.redkale.convert.Convert; import static org.redkale.net.http.WebSocket.*; import org.redkale.net.http.WebSocketPacket.FrameType; @@ -97,8 +96,12 @@ public class WebSocketReadHandler implements CompletionHandler 6) logger.log(Level.FINEST, "read websocket message's length = " + realbuf.remaining()); - if (!realbuf.hasRemaining()) return; + if (debug && realbuf.remaining() > 6) { + logger.log(Level.FINEST, "read websocket message's length = " + realbuf.remaining()); + } + if (!realbuf.hasRemaining()) { + return; + } ByteBuffer buffer = realbuf; byte frameOpcode; byte frameCrcode; @@ -117,7 +120,9 @@ public class WebSocketReadHandler implements CompletionHandler65535 this.halfFrameBytes.putLong((long) length); } - if (masks0 != null) this.halfFrameBytes.put(masks0); + if (masks0 != null) { + this.halfFrameBytes.put(masks0); + } this.halfFrameBytes.put(realbuf); this.halfFrameOpcode = opcode0; this.halfFrameCrcode = crcode0; @@ -233,14 +242,18 @@ public class WebSocketReadHandler implements CompletionHandler groups, final Collection addresses) { - if (!isSncpDyn(service)) return false; + if (!isSncpDyn(service)) { + return false; + } SncpClient client = getSncpClient(service); client.setRemoteGroups(groups); if (client.getRemoteGroupTransport() != null) { @@ -190,14 +218,18 @@ public abstract class Sncp { } static void checkAsyncModifier(Class param, Method method) { - if (param == CompletionHandler.class) return; + if (param == CompletionHandler.class) { + return; + } if (Modifier.isFinal(param.getModifiers())) { throw new RuntimeException("CompletionHandler Type Parameter on {" + method + "} cannot final modifier"); } if (!Modifier.isPublic(param.getModifiers())) { throw new RuntimeException("CompletionHandler Type Parameter on {" + method + "} must be public modifier"); } - if (param.isInterface()) return; + if (param.isInterface()) { + return; + } boolean constructorflag = false; RedkaleClassLoader.putReflectionDeclaredConstructors(param, param.getName()); for (Constructor c : param.getDeclaredConstructors()) { @@ -209,8 +241,12 @@ public abstract class Sncp { } } } - if (param.getDeclaredConstructors().length == 0) constructorflag = true; - if (!constructorflag) throw new RuntimeException(param + " must have a empty parameter Constructor"); + if (param.getDeclaredConstructors().length == 0) { + constructorflag = true; + } + if (!constructorflag) { + throw new RuntimeException(param + " must have a empty parameter Constructor"); + } for (Method m : param.getMethods()) { if (m.getName().equals("completed") && Modifier.isFinal(m.getModifiers())) { throw new RuntimeException(param + "'s completed method cannot final modifier"); @@ -295,12 +331,20 @@ public abstract class Sncp { */ @SuppressWarnings("unchecked") protected static Class createLocalServiceClass(ClassLoader classLoader, final String name, final Class serviceImplClass) { - if (serviceImplClass == null) return null; - if (!Service.class.isAssignableFrom(serviceImplClass)) return serviceImplClass; + if (serviceImplClass == null) { + return null; + } + if (!Service.class.isAssignableFrom(serviceImplClass)) { + return serviceImplClass; + } ResourceFactory.checkResourceName(name); int mod = serviceImplClass.getModifiers(); - if (!java.lang.reflect.Modifier.isPublic(mod)) return serviceImplClass; - if (java.lang.reflect.Modifier.isAbstract(mod)) return serviceImplClass; + if (!java.lang.reflect.Modifier.isPublic(mod)) { + return serviceImplClass; + } + if (java.lang.reflect.Modifier.isAbstract(mod)) { + return serviceImplClass; + } final String supDynName = serviceImplClass.getName().replace('.', '/'); final String clientName = SncpClient.class.getName().replace('.', '/'); final String resDesc = Type.getDescriptor(Resource.class); @@ -313,9 +357,13 @@ public abstract class Sncp { if (!name.isEmpty()) { boolean normal = true; for (char ch : name.toCharArray()) { - if (!((ch >= '0' && ch <= '9') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) normal = false; + if (!((ch >= '0' && ch <= '9') || ch == '_' || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) { + normal = false; + } + } + if (!normal) { + throw new RuntimeException(serviceImplClass + "'s resource name is illegal, must be 0-9 _ a-z A-Z"); } - if (!normal) throw new RuntimeException(serviceImplClass + "'s resource name is illegal, must be 0-9 _ a-z A-Z"); newDynName += "_" + (normal ? name : hash(name)); } try { @@ -344,7 +392,9 @@ public abstract class Sncp { } { //给新类加上 原有的Annotation for (Annotation ann : serviceImplClass.getAnnotations()) { - if (ann instanceof Resource || ann instanceof SncpDyn || ann instanceof ResourceType) continue; + if (ann instanceof Resource || ann instanceof SncpDyn || ann instanceof ResourceType) { + continue; + } MethodDebugVisitor.visitAnnotation(cw.visitAnnotation(Type.getDescriptor(ann.annotationType()), true), ann); } } @@ -462,15 +512,23 @@ public abstract class Sncp { RedkaleClassLoader.putReflectionDeclaredFields(loop.getName()); for (Field field : loop.getDeclaredFields()) { int mod = field.getModifiers(); - if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) continue; - if (field.getAnnotation(RpcRemote.class) == null) continue; - if (!field.getType().isAssignableFrom(newClazz)) continue; + if (Modifier.isFinal(mod) || Modifier.isStatic(mod)) { + continue; + } + if (field.getAnnotation(RpcRemote.class) == null) { + continue; + } + if (!field.getType().isAssignableFrom(newClazz)) { + continue; + } field.setAccessible(true); RedkaleClassLoader.putReflectionField(loop.getName(), field); if (remoteService == null && clientSncpAddress != null) { remoteService = createRemoteService(classLoader, name, serviceImplClass, messageAgent, transportFactory, clientSncpAddress, groups, conf); } - if (remoteService != null) field.set(service, remoteService); + if (remoteService != null) { + field.set(service, remoteService); + } } } while ((loop = loop.getSuperclass()) != Object.class); } @@ -481,7 +539,9 @@ public abstract class Sncp { c.setAccessible(true); client = new SncpClient(name, serviceImplClass, service, messageAgent, transportFactory, false, newClazz, clientSncpAddress); c.set(service, client); - if (transportFactory != null) transportFactory.addSncpService(service); + if (transportFactory != null) { + transportFactory.addSncpService(service); + } } catch (NoSuchFieldException ne) { ne.printStackTrace(); } @@ -491,7 +551,9 @@ public abstract class Sncp { c.setAccessible(true); c.set(service, messageAgent); } - if (client == null) return service; + if (client == null) { + return service; + } { Field c = newClazz.getDeclaredField(FIELDPREFIX + "_conf"); c.setAccessible(true); @@ -568,13 +630,19 @@ public abstract class Sncp { final InetSocketAddress clientAddress, final Set groups0, final AnyValue conf) { - if (serviceTypeOrImplClass == null) return null; - if (!Service.class.isAssignableFrom(serviceTypeOrImplClass)) return null; + if (serviceTypeOrImplClass == null) { + return null; + } + if (!Service.class.isAssignableFrom(serviceTypeOrImplClass)) { + return null; + } final Set groups = groups0 == null ? new HashSet<>() : groups0; ResourceFactory.checkResourceName(name); final int mod = serviceTypeOrImplClass.getModifiers(); boolean realed = !(java.lang.reflect.Modifier.isAbstract(mod) || serviceTypeOrImplClass.isInterface()); - if (!java.lang.reflect.Modifier.isPublic(mod)) return null; + if (!java.lang.reflect.Modifier.isPublic(mod)) { + return null; + } final String supDynName = serviceTypeOrImplClass.getName().replace('.', '/'); final String clientName = SncpClient.class.getName().replace('.', '/'); final String resDesc = Type.getDescriptor(Resource.class); @@ -590,7 +658,9 @@ public abstract class Sncp { T service = (T) newClazz.getDeclaredConstructor().newInstance(); SncpClient client = new SncpClient(name, serviceTypeOrImplClass, service, messageAgent, transportFactory, true, realed ? createLocalServiceClass(loader, name, serviceTypeOrImplClass) : serviceTypeOrImplClass, clientAddress); client.setRemoteGroups(groups); - if (transportFactory != null) client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups)); + if (transportFactory != null) { + client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups)); + } { Field c = newClazz.getDeclaredField(FIELDPREFIX + "_client"); c.setAccessible(true); @@ -611,7 +681,9 @@ public abstract class Sncp { c.setAccessible(true); c.set(service, conf); } - if (transportFactory != null) transportFactory.addSncpService(service); + if (transportFactory != null) { + transportFactory.addSncpService(service); + } return service; } catch (Throwable ex) { } @@ -641,7 +713,9 @@ public abstract class Sncp { } { //给新类加上 原有的Annotation for (Annotation ann : serviceTypeOrImplClass.getAnnotations()) { - if (ann instanceof Resource || ann instanceof SncpDyn || ann instanceof ResourceType) continue; + if (ann instanceof Resource || ann instanceof SncpDyn || ann instanceof ResourceType) { + continue; + } MethodDebugVisitor.visitAnnotation(cw.visitAnnotation(Type.getDescriptor(ann.annotationType()), true), ann); } } @@ -802,7 +876,9 @@ public abstract class Sncp { T service = (T) newClazz.getDeclaredConstructor().newInstance(); SncpClient client = new SncpClient(name, serviceTypeOrImplClass, service, messageAgent, transportFactory, true, realed ? createLocalServiceClass(loader, name, serviceTypeOrImplClass) : serviceTypeOrImplClass, clientAddress); client.setRemoteGroups(groups); - if (transportFactory != null) client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups)); + if (transportFactory != null) { + client.setRemoteGroupTransport(transportFactory.loadTransport(clientAddress, groups)); + } { Field c = newClazz.getDeclaredField(FIELDPREFIX + "_client"); c.setAccessible(true); @@ -827,7 +903,9 @@ public abstract class Sncp { c.set(service, conf); RedkaleClassLoader.putReflectionField(newDynName.replace('/', '.'), c); } - if (transportFactory != null) transportFactory.addSncpService(service); + if (transportFactory != null) { + transportFactory.addSncpService(service); + } return service; } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/src/main/java/org/redkale/net/sncp/SncpClient.java b/src/main/java/org/redkale/net/sncp/SncpClient.java index b584688bf..3afdf3148 100644 --- a/src/main/java/org/redkale/net/sncp/SncpClient.java +++ b/src/main/java/org/redkale/net/sncp/SncpClient.java @@ -94,7 +94,9 @@ public final class SncpClient { this.actions = methodens.toArray(new SncpAction[methodens.size()]); this.addrBytes = clientSncpAddress == null ? new byte[4] : clientSncpAddress.getAddress().getAddress(); this.addrPort = clientSncpAddress == null ? 0 : clientSncpAddress.getPort(); - if (this.addrBytes.length != 4) throw new RuntimeException("SNCP clientAddress only support IPv4"); + if (this.addrBytes.length != 4) { + throw new RuntimeException("SNCP clientAddress only support IPv4"); + } } static List getSncpActions(final Class serviceClass) { @@ -145,7 +147,9 @@ public final class SncpClient { @Override public String toString() { String service = serviceClass.getName(); - if (remote) service = service.replace("DynLocalService", "DynRemoteService"); + if (remote) { + service = service.replace("DynLocalService", "DynRemoteService"); + } return this.getClass().getSimpleName() + "(service = " + service + ", serviceid = " + serviceid + ", serviceVersion = " + serviceVersion + ", name = '" + name + "', address = " + (clientSncpAddress == null ? "" : (clientSncpAddress.getHostString() + ":" + clientSncpAddress.getPort())) + ", actions.size = " + actions.length + ")"; @@ -157,7 +161,9 @@ public final class SncpClient { return service + "(serviceid=" + serviceid + ", name='" + name + "', actions.size=" + actions.length + ")"; } String service = serviceClass.getAnnotation(SncpDyn.class) == null ? serviceClass.getName() : serviceClass.getSuperclass().getSimpleName(); - if (remote) service = service.replace("DynLocalService", "DynRemoteService"); + if (remote) { + service = service.replace("DynLocalService", "DynRemoteService"); + } return service + "(name = '" + name + "', serviceid = " + serviceid + ", serviceVersion = " + serviceVersion + ", clientaddr = " + (clientSncpAddress == null ? "" : (clientSncpAddress.getHostString() + ":" + clientSncpAddress.getPort())) + ((remoteGroups == null || remoteGroups.isEmpty()) ? "" : ", remoteGroups = " + remoteGroups) @@ -170,23 +176,40 @@ public final class SncpClient { final List multis = new ArrayList<>(); final Map actionids = new HashMap<>(); for (final java.lang.reflect.Method method : serviceClass.getMethods()) { - if (method.isSynthetic()) continue; - if (Modifier.isStatic(method.getModifiers())) continue; - if (Modifier.isFinal(method.getModifiers())) continue; - if (method.getAnnotation(Local.class) != null) continue; - if (method.getName().equals("getClass") || method.getName().equals("toString")) continue; - if (method.getName().equals("equals") || method.getName().equals("hashCode")) continue; - if (method.getName().equals("notify") || method.getName().equals("notifyAll") || method.getName().equals("wait")) continue; + if (method.isSynthetic()) { + continue; + } + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + if (Modifier.isFinal(method.getModifiers())) { + continue; + } + if (method.getAnnotation(Local.class) != null) { + continue; + } + if (method.getName().equals("getClass") || method.getName().equals("toString")) { + continue; + } + if (method.getName().equals("equals") || method.getName().equals("hashCode")) { + continue; + } + if (method.getName().equals("notify") || method.getName().equals("notifyAll") || method.getName().equals("wait")) { + continue; + } if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { - if (method.getName().equals("init") || method.getName().equals("stop") || method.getName().equals("destroy")) continue; + if (method.getName().equals("init") || method.getName().equals("stop") || method.getName().equals("destroy")) { + continue; + } } //if (onlySncpDyn && method.getAnnotation(SncpDyn.class) == null) continue; DLong actionid = Sncp.hash(method); Method old = actionids.get(actionid); if (old != null) { - if (old.getDeclaringClass().equals(method.getDeclaringClass())) + if (old.getDeclaringClass().equals(method.getDeclaringClass())) { throw new RuntimeException(serviceClass.getName() + " have one more same action(Method=" + method + ", " + old + ", actionid=" + actionid + ")"); + } continue; } actionids.put(actionid, method); @@ -198,8 +221,12 @@ public final class SncpClient { } multis.sort((m1, m2) -> m1.getAnnotation(SncpDyn.class).index() - m2.getAnnotation(SncpDyn.class).index()); list.sort((Method o1, Method o2) -> { - if (!o1.getName().equals(o2.getName())) return o1.getName().compareTo(o2.getName()); - if (o1.getParameterCount() != o2.getParameterCount()) return o1.getParameterCount() - o2.getParameterCount(); + if (!o1.getName().equals(o2.getName())) { + return o1.getName().compareTo(o2.getName()); + } + if (o1.getParameterCount() != o2.getParameterCount()) { + return o1.getParameterCount() - o2.getParameterCount(); + } return 0; }); //带SncpDyn必须排在前面 @@ -211,7 +238,9 @@ public final class SncpClient { public T remote(final int index, final Object... params) { final SncpAction action = actions[index]; final CompletionHandler handlerFunc = action.handlerFuncParamIndex >= 0 ? (CompletionHandler) params[action.handlerFuncParamIndex] : null; - if (action.handlerFuncParamIndex >= 0) params[action.handlerFuncParamIndex] = null; + if (action.handlerFuncParamIndex >= 0) { + params[action.handlerFuncParamIndex] = null; + } final BsonReader reader = bsonConvert.pollBsonReader(); CompletableFuture future = remote0(handlerFunc, remoteGroupTransport, null, action, params); if (action.boolReturnTypeFuture) { //与handlerFuncIndex互斥 @@ -239,7 +268,9 @@ public final class SncpClient { }); //需要获取 Executor return (T) result; } - if (handlerFunc != null) return null; + if (handlerFunc != null) { + return null; + } try { reader.setBytes(future.get(5, TimeUnit.SECONDS)); byte i; @@ -263,15 +294,21 @@ public final class SncpClient { final String traceid = Traces.currTraceid(); final Type[] myparamtypes = action.paramTypes; final Class[] myparamclass = action.paramClass; - if (action.addressSourceParamIndex >= 0) params[action.addressSourceParamIndex] = this.clientSncpAddress; - if (bsonConvert == null) bsonConvert = BsonConvert.root(); + if (action.addressSourceParamIndex >= 0) { + params[action.addressSourceParamIndex] = this.clientSncpAddress; + } + if (bsonConvert == null) { + bsonConvert = BsonConvert.root(); + } final BsonWriter writer = bsonConvert.pollBsonWriter(); // 将head写入 writer.writeTo(DEFAULT_HEADER); for (int i = 0; i < params.length; i++) { //params 可能包含: 3 个 boolean BsonConvert bcc = bsonConvert; if (params[i] instanceof org.redkale.service.RetResult) { org.redkale.convert.Convert cc = ((org.redkale.service.RetResult) params[i]).convert(); - if (cc instanceof BsonConvert) bcc = (BsonConvert) cc; + if (cc instanceof BsonConvert) { + bcc = (BsonConvert) cc; + } } bcc.convertTo(writer, CompletionHandler.class.isAssignableFrom(myparamclass[i]) ? CompletionHandler.class : myparamtypes[i], params[i]); } @@ -282,7 +319,9 @@ public final class SncpClient { final ByteArray reqbytes = writer.toByteArray(); fillHeader(reqbytes, seqid, actionid, traceid, reqBodyLength); String targetTopic = action.topicTargetParamIndex >= 0 ? (String) params[action.topicTargetParamIndex] : this.topic; - if (targetTopic == null) targetTopic = this.topic; + if (targetTopic == null) { + targetTopic = this.topic; + } MessageRecord message = messageClient.createMessageRecord(targetTopic, null, reqbytes.getBytes()); final String tt = targetTopic; if (logger.isLoggable(Level.FINER)) { @@ -454,15 +493,25 @@ public final class SncpClient { private void checkResult(long seqid, final SncpAction action, ByteBuffer buffer) { long rseqid = buffer.getLong(); - if (rseqid != seqid) throw new RuntimeException("sncp(" + action.method + ") response.seqid = " + seqid + ", but request.seqid =" + rseqid); - if (buffer.getChar() != HEADER_SIZE) throw new RuntimeException("sncp(" + action.method + ") buffer receive header.length not " + HEADER_SIZE); + if (rseqid != seqid) { + throw new RuntimeException("sncp(" + action.method + ") response.seqid = " + seqid + ", but request.seqid =" + rseqid); + } + if (buffer.getChar() != HEADER_SIZE) { + throw new RuntimeException("sncp(" + action.method + ") buffer receive header.length not " + HEADER_SIZE); + } DLong rserviceid = DLong.read(buffer); - if (!rserviceid.equals(this.serviceid)) throw new RuntimeException("sncp(" + action.method + ") response.serviceid = " + serviceid + ", but request.serviceid =" + rserviceid); + if (!rserviceid.equals(this.serviceid)) { + throw new RuntimeException("sncp(" + action.method + ") response.serviceid = " + serviceid + ", but request.serviceid =" + rserviceid); + } int version = buffer.getInt(); - if (version != this.serviceVersion) throw new RuntimeException("sncp(" + action.method + ") response.serviceVersion = " + serviceVersion + ", but request.serviceVersion =" + version); + if (version != this.serviceVersion) { + throw new RuntimeException("sncp(" + action.method + ") response.serviceVersion = " + serviceVersion + ", but request.serviceVersion =" + version); + } DLong raction = DLong.read(buffer); DLong actid = action.actionid; - if (!actid.equals(raction)) throw new RuntimeException("sncp(" + action.method + ") response.actionid = " + action.actionid + ", but request.actionid =(" + raction + ")"); + if (!actid.equals(raction)) { + throw new RuntimeException("sncp(" + action.method + ") response.actionid = " + action.actionid + ", but request.actionid =(" + raction + ")"); + } buffer.getInt(); //地址 buffer.getChar(); //端口 } diff --git a/src/main/java/org/redkale/net/sncp/SncpDispatcherServlet.java b/src/main/java/org/redkale/net/sncp/SncpDispatcherServlet.java index ffb85dde7..1925fcbb5 100644 --- a/src/main/java/org/redkale/net/sncp/SncpDispatcherServlet.java +++ b/src/main/java/org/redkale/net/sncp/SncpDispatcherServlet.java @@ -5,9 +5,8 @@ */ package org.redkale.net.sncp; -import org.redkale.net.DispatcherServlet; -import org.redkale.util.AnyValue; import java.io.IOException; +import org.redkale.net.DispatcherServlet; import org.redkale.service.Service; import org.redkale.util.*; @@ -26,7 +25,9 @@ public class SncpDispatcherServlet extends DispatcherServlet s.init(context, getServletConf(s))); } diff --git a/src/main/java/org/redkale/net/sncp/SncpDynServlet.java b/src/main/java/org/redkale/net/sncp/SncpDynServlet.java index 89d6a52e8..9f65968ab 100644 --- a/src/main/java/org/redkale/net/sncp/SncpDynServlet.java +++ b/src/main/java/org/redkale/net/sncp/SncpDynServlet.java @@ -52,15 +52,31 @@ public final class SncpDynServlet extends SncpServlet { Set actionids = new HashSet<>(); RedkaleClassLoader.putReflectionPublicMethods(service.getClass().getName()); for (java.lang.reflect.Method method : service.getClass().getMethods()) { - if (method.isSynthetic()) continue; - if (Modifier.isStatic(method.getModifiers())) continue; - if (Modifier.isFinal(method.getModifiers())) continue; - if (method.getAnnotation(Local.class) != null) continue; - if (method.getName().equals("getClass") || method.getName().equals("toString")) continue; - if (method.getName().equals("equals") || method.getName().equals("hashCode")) continue; - if (method.getName().equals("notify") || method.getName().equals("notifyAll") || method.getName().equals("wait")) continue; + if (method.isSynthetic()) { + continue; + } + if (Modifier.isStatic(method.getModifiers())) { + continue; + } + if (Modifier.isFinal(method.getModifiers())) { + continue; + } + if (method.getAnnotation(Local.class) != null) { + continue; + } + if (method.getName().equals("getClass") || method.getName().equals("toString")) { + continue; + } + if (method.getName().equals("equals") || method.getName().equals("hashCode")) { + continue; + } + if (method.getName().equals("notify") || method.getName().equals("notifyAll") || method.getName().equals("wait")) { + continue; + } if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == AnyValue.class) { - if (method.getName().equals("init") || method.getName().equals("stop") || method.getName().equals("destroy")) continue; + if (method.getName().equals("init") || method.getName().equals("stop") || method.getName().equals("destroy")) { + continue; + } } final DLong actionid = Sncp.hash(method); @@ -104,10 +120,14 @@ public final class SncpDynServlet extends SncpServlet { @Override public int compareTo(SncpServlet o0) { - if (!(o0 instanceof SncpDynServlet)) return 1; + if (!(o0 instanceof SncpDynServlet)) { + return 1; + } SncpDynServlet o = (SncpDynServlet) o0; int rs = this.type.getName().compareTo(o.type.getName()); - if (rs == 0) rs = this.serviceName.compareTo(o.serviceName); + if (rs == 0) { + rs = this.serviceName.compareTo(o.serviceName); + } return rs; } @@ -198,7 +218,9 @@ public final class SncpDynServlet extends SncpServlet { if (paramAttrs != null) { for (int i = 1; i < paramAttrs.length; i++) { org.redkale.util.Attribute attr = paramAttrs[i]; - if (attr == null) continue; + if (attr == null) { + continue; + } out.writeByte((byte) i); convert.convertTo(out, attr.genericType(), attr.get(params[i - 1])); } @@ -610,7 +632,9 @@ public final class SncpDynServlet extends SncpServlet { } catch (Exception e) { } for (java.lang.reflect.Type t : originalParamTypes) { - if (t.toString().startsWith("java.lang.")) continue; + if (t.toString().startsWith("java.lang.")) { + continue; + } BsonFactory.root().loadDecoder(t); } if (originalReturnType != void.class && originalReturnType != Void.class) { @@ -658,7 +682,9 @@ public final class SncpDynServlet extends SncpServlet { } } } - if (hasattr) instance.paramAttrs = atts; + if (hasattr) { + instance.paramAttrs = atts; + } newClazz.getField("service").set(instance, service); return instance; } catch (Exception ex) { diff --git a/src/main/java/org/redkale/net/sncp/SncpRequest.java b/src/main/java/org/redkale/net/sncp/SncpRequest.java index 5a22ab11c..b6fa6ad47 100644 --- a/src/main/java/org/redkale/net/sncp/SncpRequest.java +++ b/src/main/java/org/redkale/net/sncp/SncpRequest.java @@ -5,13 +5,12 @@ */ package org.redkale.net.sncp; -import java.net.*; -import java.nio.*; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.redkale.convert.bson.*; -import org.redkale.net.*; -import org.redkale.util.*; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.util.logging.*; +import org.redkale.convert.bson.BsonConvert; +import org.redkale.net.Request; +import org.redkale.util.DLong; /** * @@ -64,17 +63,23 @@ public class SncpRequest extends Request { @Override //request.header与response.header数据格式保持一致 protected int readHeader(ByteBuffer buffer, Request last) { if (buffer.remaining() == Sncp.PING_BUFFER.remaining()) { - if (buffer.hasRemaining()) buffer.get(new byte[buffer.remaining()]); + if (buffer.hasRemaining()) { + buffer.get(new byte[buffer.remaining()]); + } this.ping = true; //Sncp.PING_BUFFER this.readState = READ_STATE_END; return 0; } //---------------------head---------------------------------- if (this.readState == READ_STATE_ROUTE) { - if (buffer.remaining() < HEADER_SIZE) return 1; //小于60 + if (buffer.remaining() < HEADER_SIZE) { + return 1; //小于60 + } this.seqid = buffer.getLong(); //8 if (buffer.getChar() != HEADER_SIZE) { //2 - if (context.getLogger().isLoggable(Level.FINEST)) context.getLogger().finest("sncp buffer header.length not " + HEADER_SIZE); + if (context.getLogger().isLoggable(Level.FINEST)) { + context.getLogger().finest("sncp buffer header.length not " + HEADER_SIZE); + } return -1; } this.serviceid = DLong.read(buffer); //16 @@ -84,7 +89,9 @@ public class SncpRequest extends Request { this.bodyLength = buffer.getInt(); //4 if (buffer.getInt() != 0) { //4 - if (context.getLogger().isLoggable(Level.FINEST)) context.getLogger().finest("sncp buffer header.retcode not 0"); + if (context.getLogger().isLoggable(Level.FINEST)) { + context.getLogger().finest("sncp buffer header.retcode not 0"); + } return -1; } this.body = new byte[this.bodyLength]; @@ -96,7 +103,9 @@ public class SncpRequest extends Request { buffer.get(body, 0, len); this.bodyOffset = len; int rs = bodyLength - len; - if (rs == 0) this.readState = READ_STATE_END; + if (rs == 0) { + this.readState = READ_STATE_END; + } return rs; } return 0; @@ -159,7 +168,9 @@ public class SncpRequest extends Request { } public InetSocketAddress getRemoteAddress() { - if (addrBytes[0] == 0) return null; + if (addrBytes[0] == 0) { + return null; + } return new InetSocketAddress((0xff & addrBytes[0]) + "." + (0xff & addrBytes[1]) + "." + (0xff & addrBytes[2]) + "." + (0xff & addrBytes[3]), ((0xff00 & (addrBytes[4] << 8)) | (0xff & addrBytes[5]))); } diff --git a/src/main/java/org/redkale/net/sncp/SncpResponse.java b/src/main/java/org/redkale/net/sncp/SncpResponse.java index 15636232d..f92285361 100644 --- a/src/main/java/org/redkale/net/sncp/SncpResponse.java +++ b/src/main/java/org/redkale/net/sncp/SncpResponse.java @@ -5,10 +5,10 @@ */ package org.redkale.net.sncp; +import java.nio.ByteBuffer; +import org.redkale.convert.bson.BsonWriter; +import org.redkale.net.Response; import static org.redkale.net.sncp.SncpRequest.HEADER_SIZE; -import java.nio.*; -import org.redkale.convert.bson.*; -import org.redkale.net.*; import org.redkale.util.*; /** @@ -33,10 +33,18 @@ public class SncpResponse extends Response { private final int addrPort; public static String getRetCodeInfo(int retcode) { - if (retcode == RETCODE_ILLSERVICEID) return "The serviceid is invalid"; - if (retcode == RETCODE_ILLSERVICEVER) return "The serviceVersion is invalid"; - if (retcode == RETCODE_ILLACTIONID) return "The actionid is invalid"; - if (retcode == RETCODE_THROWEXCEPTION) return "Inner exception"; + if (retcode == RETCODE_ILLSERVICEID) { + return "The serviceid is invalid"; + } + if (retcode == RETCODE_ILLSERVICEVER) { + return "The serviceVersion is invalid"; + } + if (retcode == RETCODE_ILLACTIONID) { + return "The actionid is invalid"; + } + if (retcode == RETCODE_THROWEXCEPTION) { + return "Inner exception"; + } return null; } diff --git a/src/main/java/org/redkale/net/sncp/SncpServer.java b/src/main/java/org/redkale/net/sncp/SncpServer.java index 85ee80cc4..cabf900c7 100644 --- a/src/main/java/org/redkale/net/sncp/SncpServer.java +++ b/src/main/java/org/redkale/net/sncp/SncpServer.java @@ -43,9 +43,13 @@ public class SncpServer extends Server bufferPool = ObjectPool.createSafePool(createCounter, cycleCounter, bufferPoolSize, (Object... params) -> ByteBuffer.allocateDirect(rcapacity), null, (e) -> { - if (e == null || e.isReadOnly() || e.capacity() != rcapacity) return false; + if (e == null || e.isReadOnly() || e.capacity() != rcapacity) { + return false; + } e.clear(); return true; }); diff --git a/src/main/java/org/redkale/service/RetResult.java b/src/main/java/org/redkale/service/RetResult.java index 308651af2..3e3c7416c 100644 --- a/src/main/java/org/redkale/service/RetResult.java +++ b/src/main/java/org/redkale/service/RetResult.java @@ -10,9 +10,9 @@ import java.lang.reflect.Type; import java.util.*; import java.util.concurrent.*; import java.util.function.Function; -import org.redkale.persistence.Column; import org.redkale.convert.*; -import org.redkale.convert.json.*; +import org.redkale.convert.json.JsonConvert; +import org.redkale.persistence.Column; import org.redkale.util.*; /** @@ -135,7 +135,9 @@ public class RetResult implements Serializable { //@since 2.7.0 public T join() { - if (isSuccess()) return result; + if (isSuccess()) { + return result; + } throw new RetcodeException(this.retcode, this.retinfo); } @@ -244,7 +246,9 @@ public class RetResult implements Serializable { @Deprecated public RetResult attach(String key, Object value) { System.err.println("RetResult.attach is deprecated"); - if (this.attach == null) this.attach = new HashMap<>(); + if (this.attach == null) { + this.attach = new HashMap<>(); + } boolean canstr = value != null && (value instanceof CharSequence || value instanceof Number || value.getClass().isPrimitive()); this.attach.put(key, value == null ? null : (canstr ? String.valueOf(value) : JsonConvert.root().convertTo(value))); return this; diff --git a/src/main/java/org/redkale/service/RpcCallArrayAttribute.java b/src/main/java/org/redkale/service/RpcCallArrayAttribute.java index 633a473bc..80c263322 100644 --- a/src/main/java/org/redkale/service/RpcCallArrayAttribute.java +++ b/src/main/java/org/redkale/service/RpcCallArrayAttribute.java @@ -42,7 +42,9 @@ public class RpcCallArrayAttribute implements Attribute { @Override public F get(final T[] objs) { - if (objs == null || objs.length == 0) return null; + if (objs == null || objs.length == 0) { + return null; + } final Attribute attr = RpcCallAttribute.load(objs[0].getClass()); final Object keys = Array.newInstance(attr.type(), objs.length); for (int i = 0; i < objs.length; i++) { @@ -53,7 +55,9 @@ public class RpcCallArrayAttribute implements Attribute { @Override public void set(final T[] objs, final F keys) { - if (objs == null || objs.length == 0) return; + if (objs == null || objs.length == 0) { + return; + } final Attribute attr = RpcCallAttribute.load(objs[0].getClass()); for (int i = 0; i < objs.length; i++) { attr.set(objs[i], (Serializable) Array.get(keys, i)); diff --git a/src/main/java/org/redkale/service/RpcCallAttribute.java b/src/main/java/org/redkale/service/RpcCallAttribute.java index e8e760e14..8613207f1 100644 --- a/src/main/java/org/redkale/service/RpcCallAttribute.java +++ b/src/main/java/org/redkale/service/RpcCallAttribute.java @@ -6,7 +6,7 @@ package org.redkale.service; import java.io.Serializable; -import java.lang.reflect.*; +import java.lang.reflect.Field; import java.util.concurrent.ConcurrentHashMap; import org.redkale.util.Attribute; @@ -27,7 +27,9 @@ public class RpcCallAttribute implements Attribute { static Attribute load(final Class clazz) { Attribute rs = attributes.get(clazz); - if (rs != null) return rs; + if (rs != null) { + return rs; + } synchronized (attributes) { rs = attributes.get(clazz); if (rs == null) { @@ -64,13 +66,17 @@ public class RpcCallAttribute implements Attribute { @Override public Serializable get(final Object obj) { - if (obj == null) return null; + if (obj == null) { + return null; + } return load(obj.getClass()).get(obj); } @Override public void set(final Object obj, final Serializable key) { - if (obj == null) return; + if (obj == null) { + return; + } load(obj.getClass()).set(obj, key); } diff --git a/src/main/java/org/redkale/source/AbstractCacheSource.java b/src/main/java/org/redkale/source/AbstractCacheSource.java index cdfba5356..df4cfaed5 100644 --- a/src/main/java/org/redkale/source/AbstractCacheSource.java +++ b/src/main/java/org/redkale/source/AbstractCacheSource.java @@ -71,14 +71,18 @@ public abstract class AbstractCacheSource extends AbstractService implements Cac Iterator it = ServiceLoader.load(CacheSourceProvider.class, serverClassLoader).iterator(); while (it.hasNext()) { CacheSourceProvider provider = it.next(); - if (provider != null) RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); + if (provider != null) { + RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); + } if (provider != null && provider.acceptsConf(sourceConf)) { providers.add(provider); } } for (CacheSourceProvider provider : InstanceProvider.sort(providers)) { source = provider.createInstance(); - if (source != null) break; + if (source != null) { + break; + } } if (source == null) { if (CacheMemorySource.acceptsConf(sourceConf)) { diff --git a/src/main/java/org/redkale/source/AbstractDataSource.java b/src/main/java/org/redkale/source/AbstractDataSource.java index bd74de4ca..99651807e 100644 --- a/src/main/java/org/redkale/source/AbstractDataSource.java +++ b/src/main/java/org/redkale/source/AbstractDataSource.java @@ -128,14 +128,18 @@ public abstract class AbstractDataSource extends AbstractService implements Data Iterator it = ServiceLoader.load(DataSourceProvider.class, serverClassLoader).iterator(); while (it.hasNext()) { DataSourceProvider provider = it.next(); - if (provider != null) RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); + if (provider != null) { + RedkaleClassLoader.putReflectionPublicConstructors(provider.getClass(), provider.getClass().getName()); + } if (provider != null && provider.acceptsConf(sourceConf)) { providers.add(provider); } } for (DataSourceProvider provider : InstanceProvider.sort(providers)) { source = provider.createInstance(); - if (source != null) break; + if (source != null) { + break; + } } if (source == null) { if (DataMemorySource.acceptsConf(sourceConf)) { @@ -162,7 +166,9 @@ public abstract class AbstractDataSource extends AbstractService implements Data public static String parseDbtype(String url) { String dbtype = null; - if (url == null) return dbtype; + if (url == null) { + return dbtype; + } if (url.startsWith("http://") || url.startsWith("https://") || url.startsWith("search://") || url.startsWith("searchs://")) { //elasticsearch or opensearch dbtype = "search"; } else { @@ -179,24 +185,32 @@ public abstract class AbstractDataSource extends AbstractService implements Data } else { //jdbc:oracle:thin:@localhost:1521 String url0 = url.substring(url.indexOf(":") + 1); pos = url0.indexOf(':'); - if (pos > 0) dbtype = url0.substring(0, pos); + if (pos > 0) { + dbtype = url0.substring(0, pos); + } } } - if ("mariadb".equals(dbtype)) return "mysql"; + if ("mariadb".equals(dbtype)) { + return "mysql"; + } return dbtype; } protected SourceUrlInfo parseSourceUrl(final String url) { final SourceUrlInfo info = new SourceUrlInfo(); info.url = url; - if (url.startsWith("jdbc:h2:")) return info; + if (url.startsWith("jdbc:h2:")) { + return info; + } String url0 = url.substring(url.indexOf("://") + 3); int pos = url0.indexOf('?'); //127.0.0.1:5432/db?charset=utr8&xxx=yy if (pos > 0) { String params = url0.substring(pos + 1).replace("&", "&"); for (String param : params.split("&")) { int p = param.indexOf('='); - if (p < 1) continue; + if (p < 1) { + continue; + } info.attributes.put(param.substring(0, p), param.substring(p + 1)); } url0 = url0.substring(0, pos); @@ -357,7 +371,9 @@ public abstract class AbstractDataSource extends AbstractService implements Data * @return CompletableFuture */ protected CompletableFuture checkEntity(String action, boolean async, T... entitys) { - if (entitys.length < 1) return null; + if (entitys.length < 1) { + return null; + } Class clazz = null; for (T val : entitys) { if (clazz == null) { @@ -509,25 +525,33 @@ public abstract class AbstractDataSource extends AbstractService implements Data @Override public final int insert(final Collection entitys) { - if (entitys == null || entitys.isEmpty()) return 0; + if (entitys == null || entitys.isEmpty()) { + return 0; + } return insert(entitys.toArray()); } @Override public final int insert(final Stream entitys) { - if (entitys == null) return 0; + if (entitys == null) { + return 0; + } return insert(entitys.toArray()); } @Override public final CompletableFuture insertAsync(final Collection entitys) { - if (entitys == null || entitys.isEmpty()) return CompletableFuture.completedFuture(0); + if (entitys == null || entitys.isEmpty()) { + return CompletableFuture.completedFuture(0); + } return insertAsync(entitys.toArray()); } @Override public final CompletableFuture insertAsync(final Stream entitys) { - if (entitys == null) return CompletableFuture.completedFuture(0); + if (entitys == null) { + return CompletableFuture.completedFuture(0); + } return insertAsync(entitys.toArray()); } diff --git a/src/main/java/org/redkale/source/CacheMemorySource.java b/src/main/java/org/redkale/source/CacheMemorySource.java index b0603c0db..35253ba2a 100644 --- a/src/main/java/org/redkale/source/CacheMemorySource.java +++ b/src/main/java/org/redkale/source/CacheMemorySource.java @@ -55,7 +55,9 @@ public final class CacheMemorySource extends AbstractCacheSource { protected final ConcurrentHashMap> container = new ConcurrentHashMap<>(); protected final BiConsumer futureCompleteConsumer = (r, t) -> { - if (t != null) logger.log(Level.SEVERE, "CompletableFuture complete error", (Throwable) t); + if (t != null) { + logger.log(Level.SEVERE, "CompletableFuture complete error", (Throwable) t); + } }; public CacheMemorySource(String resourceName) { @@ -84,8 +86,12 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override @SuppressWarnings("unchecked") public void init(AnyValue conf) { - if (this.convert == null) this.convert = this.defaultConvert; - if (this.convert == null) this.convert = JsonConvert.root(); + if (this.convert == null) { + this.convert = this.defaultConvert; + } + if (this.convert == null) { + this.convert = JsonConvert.root(); + } final CacheMemorySource self = this; AnyValue prop = conf == null ? null : conf.getAnyValue("properties"); String expireHandlerClass = prop == null ? null : prop.getValue("expirehandler"); @@ -116,7 +122,9 @@ public final class CacheMemorySource extends AbstractCacheSource { }); for (String key : keys) { CacheEntry entry = container.remove(key); - if (expireHandler != null && entry != null) expireHandler.accept(entry); + if (expireHandler != null && entry != null) { + expireHandler.accept(entry); + } } } catch (Throwable t) { logger.log(Level.SEVERE, "CacheMemorySource schedule(interval=" + 10 + "s) error", t); @@ -138,7 +146,9 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public void destroy(AnyValue conf) { - if (scheduler != null) scheduler.shutdownNow(); + if (scheduler != null) { + scheduler.shutdownNow(); + } } //----------- hxxx -------------- @@ -146,9 +156,13 @@ public final class CacheMemorySource extends AbstractCacheSource { public int hdel(final String key, String... fields) { int count = 0; CacheEntry entry = container.get(key); - if (entry == null || entry.mapValue == null) return 0; + if (entry == null || entry.mapValue == null) { + return 0; + } for (String field : fields) { - if (entry.mapValue.remove(field) != null) count++; + if (entry.mapValue.remove(field) != null) { + count++; + } } return count; } @@ -157,7 +171,9 @@ public final class CacheMemorySource extends AbstractCacheSource { public List hkeys(final String key) { List list = new ArrayList<>(); CacheEntry entry = container.get(key); - if (entry == null || entry.mapValue == null) return list; + if (entry == null || entry.mapValue == null) { + return list; + } list.addAll(entry.mapValue.keySet()); return list; } @@ -165,7 +181,9 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public int hlen(final String key) { CacheEntry entry = container.get(key); - if (entry == null || entry.mapValue == null) return 0; + if (entry == null || entry.mapValue == null) { + return 0; + } return entry.mapValue.keySet().size(); } @@ -246,9 +264,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public boolean hexists(final String key, String field) { - if (key == null) return false; + if (key == null) { + return false; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return false; + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return false; + } return entry.mapValue.contains(field); } @@ -306,9 +328,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public List hmget(final String key, final Type type, final String... fields) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return null; + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return null; + } List rs = new ArrayList<>(fields.length); for (int i = 0; i < fields.length; i++) { Serializable val = (Serializable) entry.mapValue.get(fields[i]); @@ -328,42 +354,62 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public Map hmap(final String key, final Type type, int offset, int limit, String pattern) { - if (key == null) return new HashMap(); + if (key == null) { + return new HashMap(); + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return new HashMap(); + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return new HashMap(); + } return new HashMap(entry.mapValue); } @Override public T hget(final String key, final String field, final Type type) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return null; + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return null; + } return (T) entry.mapValue.get(field); } @Override public String hgetString(final String key, final String field) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return null; + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return null; + } return (String) entry.mapValue.get(field); } @Override public long hgetLong(final String key, final String field, long defValue) { - if (key == null) return defValue; + if (key == null) { + return defValue; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired() || entry.mapValue == null) return defValue; + if (entry == null || entry.isExpired() || entry.mapValue == null) { + return defValue; + } return ((Number) entry.mapValue.getOrDefault(field, defValue)).longValue(); } //----------- hxxx -------------- @Override public boolean exists(String key) { - if (key == null) return false; + if (key == null) { + return false; + } CacheEntry entry = container.get(key); - if (entry == null) return false; + if (entry == null) { + return false; + } return !entry.isExpired(); } @@ -374,19 +420,31 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public T get(final String key, final Type type) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; - if (entry.isListCacheType()) return (T) (entry.listValue == null ? null : new ArrayList(entry.listValue)); - if (entry.isSetCacheType()) return (T) (entry.csetValue == null ? null : new HashSet(entry.csetValue)); + if (entry == null || entry.isExpired()) { + return null; + } + if (entry.isListCacheType()) { + return (T) (entry.listValue == null ? null : new ArrayList(entry.listValue)); + } + if (entry.isSetCacheType()) { + return (T) (entry.csetValue == null ? null : new HashSet(entry.csetValue)); + } return entry.cacheType == CacheEntryType.DOUBLE ? (T) (Double) Double.longBitsToDouble(((AtomicLong) entry.objectValue).intValue()) : (T) entry.objectValue; } @Override public String getString(String key) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; + if (entry == null || entry.isExpired()) { + return null; + } return (String) entry.objectValue; } @@ -399,9 +457,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public long getLong(String key, long defValue) { - if (key == null) return defValue; + if (key == null) { + return defValue; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return defValue; + if (entry == null || entry.isExpired()) { + return defValue; + } return entry.objectValue == null ? defValue : (entry.objectValue instanceof AtomicLong ? ((AtomicLong) entry.objectValue).get() : (Long) entry.objectValue); } @@ -561,22 +623,34 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public T getex(final String key, final int expireSeconds, final Type type) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; + if (entry == null || entry.isExpired()) { + return null; + } entry.lastAccessed = (int) (System.currentTimeMillis() / 1000); entry.expireSeconds = expireSeconds; - if (entry.isListCacheType()) return (T) (entry.listValue == null ? null : new ArrayList(entry.listValue)); - if (entry.isSetCacheType()) return (T) (entry.csetValue == null ? null : new HashSet(entry.csetValue)); + if (entry.isListCacheType()) { + return (T) (entry.listValue == null ? null : new ArrayList(entry.listValue)); + } + if (entry.isSetCacheType()) { + return (T) (entry.csetValue == null ? null : new HashSet(entry.csetValue)); + } return (T) entry.objectValue; } @Override @SuppressWarnings("unchecked") public String getexString(String key, final int expireSeconds) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; + if (entry == null || entry.isExpired()) { + return null; + } entry.lastAccessed = (int) (System.currentTimeMillis() / 1000); entry.expireSeconds = expireSeconds; return (String) entry.objectValue; @@ -584,9 +658,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public long getexLong(String key, final int expireSeconds, long defValue) { - if (key == null) return defValue; + if (key == null) { + return defValue; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return defValue; + if (entry == null || entry.isExpired()) { + return defValue; + } entry.lastAccessed = (int) (System.currentTimeMillis() / 1000); entry.expireSeconds = expireSeconds; return entry.objectValue == null ? defValue : (entry.objectValue instanceof AtomicLong ? ((AtomicLong) entry.objectValue).get() : (Long) entry.objectValue); @@ -609,7 +687,9 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void set(CacheEntryType cacheType, String key, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null) { entry = new CacheEntry(cacheType, key, value, null, null, null); @@ -622,7 +702,9 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void setnx(CacheEntryType cacheType, String key, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null) { entry = new CacheEntry(cacheType, key, value, null, null, null); @@ -634,7 +716,9 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void hset(CacheEntryType cacheType, String key, String field, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null) { entry = new CacheEntry(CacheEntryType.MAP, key, value, null, null, new ConcurrentHashMap<>()); @@ -648,7 +732,9 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void hsetnx(CacheEntryType cacheType, String key, String field, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null) { entry = new CacheEntry(CacheEntryType.MAP, key, value, null, null, new ConcurrentHashMap<>()); @@ -811,13 +897,17 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void set(CacheEntryType cacheType, int expireSeconds, String key, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null) { entry = new CacheEntry(cacheType, expireSeconds, key, value, null, null, null); container.putIfAbsent(key, entry); } else { - if (expireSeconds > 0) entry.expireSeconds = expireSeconds; + if (expireSeconds > 0) { + entry.expireSeconds = expireSeconds; + } entry.lastAccessed = (int) (System.currentTimeMillis() / 1000); entry.objectValue = value; } @@ -865,9 +955,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public void expire(String key, int expireSeconds) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); - if (entry == null) return; + if (entry == null) { + return; + } entry.expireSeconds = expireSeconds; } @@ -878,7 +972,9 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public int del(final String... keys) { - if (keys == null) return 0; + if (keys == null) { + return 0; + } int count = 0; for (String key : keys) { count += container.remove(key) == null ? 0 : 1; @@ -982,7 +1078,9 @@ public final class CacheMemorySource extends AbstractCacheSource { Map> map = new HashMap<>(); for (String key : keys) { Set s = (Set) get(key, componentType); - if (s != null) map.put(key, s); + if (s != null) { + map.put(key, s); + } } return map; } @@ -992,7 +1090,9 @@ public final class CacheMemorySource extends AbstractCacheSource { Map> map = new HashMap<>(); for (String key : keys) { List s = (List) get(key, componentType); - if (s != null) map.put(key, s); + if (s != null) { + map.put(key, s); + } } return map; } @@ -1002,7 +1102,9 @@ public final class CacheMemorySource extends AbstractCacheSource { Map> map = new HashMap<>(); for (String key : keys) { Collection s = (Collection) get(key, componentType); - if (s != null) map.put(key, s); + if (s != null) { + map.put(key, s); + } } return map; } @@ -1017,7 +1119,9 @@ public final class CacheMemorySource extends AbstractCacheSource { Map> map = new HashMap<>(); for (String key : keys) { Collection s = (Collection) get(key, String.class); - if (s != null) map.put(key, s); + if (s != null) { + map.put(key, s); + } } return map; } @@ -1167,7 +1271,9 @@ public final class CacheMemorySource extends AbstractCacheSource { Map> map = new HashMap<>(); for (String key : keys) { Collection s = (Collection) get(key, long.class); - if (s != null) map.put(key, s); + if (s != null) { + map.put(key, s); + } } return map; } @@ -1319,14 +1425,20 @@ public final class CacheMemorySource extends AbstractCacheSource { } protected void appendListItem(CacheEntryType cacheType, String key, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null || !entry.isListCacheType() || entry.listValue == null) { ConcurrentLinkedQueue list = new ConcurrentLinkedQueue(); entry = new CacheEntry(cacheType, key, null, null, list, null); CacheEntry old = container.putIfAbsent(key, entry); - if (old != null) list = old.listValue; - if (list != null) list.add(value); + if (old != null) { + list = old.listValue; + } + if (list != null) { + list.add(value); + } } else { entry.listValue.add(value); } @@ -1364,25 +1476,37 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public int lrem(String key, final Type componentType, T value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.listValue == null) return 0; + if (entry == null || entry.listValue == null) { + return 0; + } return entry.listValue.remove(value) ? 1 : 0; } @Override public int lremString(String key, String value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.listValue == null) return 0; + if (entry == null || entry.listValue == null) { + return 0; + } return entry.listValue.remove(value) ? 1 : 0; } @Override public int lremLong(String key, long value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.listValue == null) return 0; + if (entry == null || entry.listValue == null) { + return 0; + } return entry.listValue.remove(value) ? 1 : 0; } @@ -1423,16 +1547,22 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public T spop(final String key, final Type componentType) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); if (entry == null || !entry.isSetCacheType() || entry.csetValue == null) { return null; } - if (entry.csetValue.isEmpty()) return null; + if (entry.csetValue.isEmpty()) { + return null; + } Iterator it = entry.csetValue.iterator(); if (it.hasNext()) { Object obj = it.next(); - if (obj != null && componentType == long.class) obj = ((Number) obj).longValue(); + if (obj != null && componentType == long.class) { + obj = ((Number) obj).longValue(); + } it.remove(); return (T) obj; } @@ -1441,34 +1571,48 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public Set spop(final String key, final int count, final Type componentType) { - if (key == null) return new LinkedHashSet<>(); + if (key == null) { + return new LinkedHashSet<>(); + } CacheEntry entry = container.get(key); if (entry == null || !entry.isSetCacheType() || entry.csetValue == null) { return new LinkedHashSet<>(); } - if (entry.csetValue.isEmpty()) return new LinkedHashSet<>(); + if (entry.csetValue.isEmpty()) { + return new LinkedHashSet<>(); + } Iterator it = entry.csetValue.iterator(); Set list = new LinkedHashSet<>(); int index = 0; while (it.hasNext()) { Object obj = it.next(); - if (obj != null && componentType == long.class) obj = ((Number) obj).longValue(); + if (obj != null && componentType == long.class) { + obj = ((Number) obj).longValue(); + } list.add((T) obj); it.remove(); - if (++index >= count) break; + if (++index >= count) { + break; + } } return list; } protected void appendSetItem(CacheEntryType cacheType, String key, Object value) { - if (key == null) return; + if (key == null) { + return; + } CacheEntry entry = container.get(key); if (entry == null || !entry.isSetCacheType() || entry.csetValue == null) { CopyOnWriteArraySet set = new CopyOnWriteArraySet(); entry = new CacheEntry(cacheType, key, null, set, null, null); CacheEntry old = container.putIfAbsent(key, entry); - if (old != null) set = old.csetValue; - if (set != null) set.add(value); + if (old != null) { + set = old.csetValue; + } + if (set != null) { + set.add(value); + } } else { entry.csetValue.add(value); } @@ -1506,25 +1650,37 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public int srem(String key, Type type, T value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.csetValue == null) return 0; + if (entry == null || entry.csetValue == null) { + return 0; + } return entry.csetValue.remove(value) ? 1 : 0; } @Override public int sremString(String key, String value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.csetValue == null) return 0; + if (entry == null || entry.csetValue == null) { + return 0; + } return entry.csetValue.remove(value) ? 1 : 0; } @Override public int sremLong(String key, long value) { - if (key == null) return 0; + if (key == null) { + return 0; + } CacheEntry entry = container.get(key); - if (entry == null || entry.csetValue == null) return 0; + if (entry == null || entry.csetValue == null) { + return 0; + } return entry.csetValue.remove(value) ? 1 : 0; } @@ -1545,9 +1701,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public byte[] getBytes(final String key) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; + if (entry == null || entry.isExpired()) { + return null; + } return (byte[]) entry.objectValue; } @@ -1570,9 +1730,13 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public byte[] getexBytes(String key, final int expireSeconds) { - if (key == null) return null; + if (key == null) { + return null; + } CacheEntry entry = container.get(key); - if (entry == null || entry.isExpired()) return null; + if (entry == null || entry.isExpired()) { + return null; + } entry.lastAccessed = (int) (System.currentTimeMillis() / 1000); entry.expireSeconds = expireSeconds; return (byte[]) entry.objectValue; @@ -1632,7 +1796,9 @@ public final class CacheMemorySource extends AbstractCacheSource { @Override public List keysStartsWith(String startsWith) { - if (startsWith == null) return keys(); + if (startsWith == null) { + return keys(); + } List rs = new ArrayList<>(); container.keySet().stream().filter(x -> x.startsWith(startsWith)).forEach(x -> rs.add(x)); return rs; diff --git a/src/main/java/org/redkale/source/ColumnFuncNode.java b/src/main/java/org/redkale/source/ColumnFuncNode.java index c0ba981ec..41a1383f2 100644 --- a/src/main/java/org/redkale/source/ColumnFuncNode.java +++ b/src/main/java/org/redkale/source/ColumnFuncNode.java @@ -27,7 +27,9 @@ public class ColumnFuncNode implements ColumnNode { } public ColumnFuncNode(FilterFunc func, Serializable node) { - if (!(node instanceof String) && !(node instanceof ColumnNodeValue)) throw new IllegalArgumentException("value must be String or ColumnNodeValue"); + if (!(node instanceof String) && !(node instanceof ColumnNodeValue)) { + throw new IllegalArgumentException("value must be String or ColumnNodeValue"); + } this.func = func; this.value = node; } diff --git a/src/main/java/org/redkale/source/ColumnNodeValue.java b/src/main/java/org/redkale/source/ColumnNodeValue.java index 5fe87f8e2..4fc27df9c 100644 --- a/src/main/java/org/redkale/source/ColumnNodeValue.java +++ b/src/main/java/org/redkale/source/ColumnNodeValue.java @@ -39,7 +39,9 @@ public class ColumnNodeValue implements ColumnNode { throw new IllegalArgumentException("express cannot be null"); } if (express == MOV) { - if (!(left instanceof String) || right != null) throw new IllegalArgumentException("left value must be String, right value must be null on ColumnExpress.MOV"); + if (!(left instanceof String) || right != null) { + throw new IllegalArgumentException("left value must be String, right value must be null on ColumnExpress.MOV"); + } } else { if (!(left instanceof String) && !(left instanceof Number) && !(left instanceof ColumnNodeValue) && !(left instanceof ColumnFuncNode)) { throw new IllegalArgumentException("left value must be String, Number, ColumnFuncNode or ColumnNodeValue"); diff --git a/src/main/java/org/redkale/source/DataJdbcSource.java b/src/main/java/org/redkale/source/DataJdbcSource.java index 2ab623f34..63379dc20 100644 --- a/src/main/java/org/redkale/source/DataJdbcSource.java +++ b/src/main/java/org/redkale/source/DataJdbcSource.java @@ -68,16 +68,24 @@ public class DataJdbcSource extends DataSqlSource { @Override public void destroy(AnyValue config) { - if (readPool != null) readPool.close(); - if (writePool != null && writePool != readPool) writePool.close(); + if (readPool != null) { + readPool.close(); + } + if (writePool != null && writePool != readPool) { + writePool.close(); + } } @Local @Override public void close() throws Exception { super.close(); - if (readPool != null) readPool.close(); - if (writePool != null && writePool != readPool) writePool.close(); + if (readPool != null) { + readPool.close(); + } + if (writePool != null && writePool != readPool) { + writePool.close(); + } } public static boolean acceptsConf(AnyValue conf) { @@ -276,7 +284,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -318,7 +328,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -366,7 +378,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -428,10 +442,14 @@ public class DataJdbcSource extends DataSqlSource { conn.commit(); } catch (SQLException se) { conn.rollback(); - if (!isTableNotExist(info, se.getSQLState())) throw se; + if (!isTableNotExist(info, se.getSQLState())) { + throw se; + } if (info.getTableStrategy() == null) { //单表 String[] tableSqls = createTableSqls(info); - if (tableSqls == null) throw se; + if (tableSqls == null) { + throw se; + } //创建单表结构 Statement st = conn.createStatement(); if (tableSqls.length == 1) { @@ -587,7 +605,9 @@ public class DataJdbcSource extends DataSqlSource { } } String debugsql = sb.toString(); - if (info.isLoggable(logger, Level.FINEST, debugsql)) logger.finest(info.getType().getSimpleName() + " insert sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + if (info.isLoggable(logger, Level.FINEST, debugsql)) { + logger.finest(info.getType().getSimpleName() + " insert sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + } } } else { prepareInfos.forEach((t, p) -> { @@ -609,7 +629,9 @@ public class DataJdbcSource extends DataSqlSource { } } String debugsql = sb.toString(); - if (info.isLoggable(logger, Level.FINEST, debugsql)) logger.finest(info.getType().getSimpleName() + " insert sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + if (info.isLoggable(logger, Level.FINEST, debugsql)) { + logger.finest(info.getType().getSimpleName() + " insert sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + } } }); } @@ -633,7 +655,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -659,7 +683,9 @@ public class DataJdbcSource extends DataSqlSource { int c1 = 0; int[] pc = prestmt.executeBatch(); for (int p : pc) { - if (p >= 0) c1 += p; + if (p >= 0) { + c1 += p; + } } c = c1; prestmt.close(); @@ -764,7 +790,9 @@ public class DataJdbcSource extends DataSqlSource { } } String debugsql = sb.toString(); - if (info.isLoggable(logger, Level.FINEST, debugsql)) logger.finest(info.getType().getSimpleName() + " update sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + if (info.isLoggable(logger, Level.FINEST, debugsql)) { + logger.finest(info.getType().getSimpleName() + " update sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + } } } else { prepareInfos.forEach((t, p) -> { @@ -786,7 +814,9 @@ public class DataJdbcSource extends DataSqlSource { } } String debugsql = sb.toString(); - if (info.isLoggable(logger, Level.FINEST, debugsql)) logger.finest(info.getType().getSimpleName() + " update sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + if (info.isLoggable(logger, Level.FINEST, debugsql)) { + logger.finest(info.getType().getSimpleName() + " update sql=" + debugsql.replaceAll("(\r|\n)", "\\n")); + } } }); } @@ -810,7 +840,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -856,7 +888,9 @@ public class DataJdbcSource extends DataSqlSource { slowLog(s, sql.sql); return CompletableFuture.completedFuture(c); } else { - if (info.isLoggable(logger, Level.FINEST, sql.sql)) logger.finest(info.getType().getSimpleName() + " update sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql.sql)) { + logger.finest(info.getType().getSimpleName() + " update sql=" + sql); + } final Statement stmt = conn.createStatement(); int c = stmt.executeUpdate(sql.sql); stmt.close(); @@ -896,7 +930,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -916,7 +952,9 @@ public class DataJdbcSource extends DataSqlSource { for (String col : ffc.cols()) { Object o = set.getObject(++index); Number rs = ffc.getDefvalue(); - if (o != null) rs = (Number) o; + if (o != null) { + rs = (Number) o; + } map.put(ffc.col(col), rs); } } @@ -949,7 +987,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -965,7 +1005,9 @@ public class DataJdbcSource extends DataSqlSource { ResultSet set = stmt.executeQuery(sql); if (set.next()) { Object o = set.getObject(1); - if (o != null) rs = (Number) o; + if (o != null) { + rs = (Number) o; + } } set.close(); stmt.close(); @@ -995,7 +1037,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1042,7 +1086,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1104,7 +1150,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1147,7 +1195,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1194,7 +1244,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1210,7 +1262,9 @@ public class DataJdbcSource extends DataSqlSource { boolean rs = set.next() ? (set.getInt(1) > 0) : false; set.close(); ps.close(); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " exists (" + rs + ") sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " exists (" + rs + ") sql=" + sql); + } slowLog(s, sql); return CompletableFuture.completedFuture(rs); } catch (SQLException e) { @@ -1237,7 +1291,9 @@ public class DataJdbcSource extends DataSqlSource { } return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1317,7 +1373,9 @@ public class DataJdbcSource extends DataSqlSource { } catch (Exception e) { return CompletableFuture.failedFuture(e); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1337,7 +1395,9 @@ public class DataJdbcSource extends DataSqlSource { if (needTotal) { ps = conn.prepareStatement(countSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); set = ps.executeQuery(); - if (set.next()) total = set.getLong(1); + if (set.next()) { + total = set.getLong(1); + } set.close(); ps.close(); } @@ -1346,9 +1406,13 @@ public class DataJdbcSource extends DataSqlSource { } else { //conn.setReadOnly(true); PreparedStatement ps = conn.prepareStatement(listSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - if (flipper != null && flipper.getLimit() > 0) ps.setFetchSize(flipper.getLimit()); + if (flipper != null && flipper.getLimit() > 0) { + ps.setFetchSize(flipper.getLimit()); + } ResultSet set = ps.executeQuery(); - if (flipper != null && flipper.getOffset() > 0) set.absolute(flipper.getOffset()); + if (flipper != null && flipper.getOffset() > 0) { + set.absolute(flipper.getOffset()); + } final int limit = flipper == null || flipper.getLimit() < 1 ? Integer.MAX_VALUE : flipper.getLimit(); int i = 0; final DataResultSet rr = createDataResultSet(info, set); @@ -1356,13 +1420,17 @@ public class DataJdbcSource extends DataSqlSource { while (set.next()) { i++; list.add(info.getFullEntityValue(rr)); - if (limit <= i) break; + if (limit <= i) { + break; + } } } else { while (set.next()) { i++; list.add(info.getEntityValue(sels, rr)); - if (limit <= i) break; + if (limit <= i) { + break; + } } } long total = list.size(); @@ -1389,7 +1457,9 @@ public class DataJdbcSource extends DataSqlSource { } else { int b = 0; for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } union.append("SELECT ").append(info.getFullQueryColumns("a", selects)).append(" FROM ").append(table).append(" a").append(joinAndWhere); } listSubSql = "SELECT " + (distinct ? "DISTINCT " : "") + info.getFullQueryColumns("a", selects) + " FROM (" + (union) + ") a"; @@ -1481,7 +1551,9 @@ public class DataJdbcSource extends DataSqlSource { @Local @Override public int[] directExecute(String... sqls) { - if (sqls.length == 0) return new int[0]; + if (sqls.length == 0) { + return new int[0]; + } final long s = System.currentTimeMillis(); Connection conn = writePool.pollConnection(); try { @@ -1504,7 +1576,9 @@ public class DataJdbcSource extends DataSqlSource { } throw new SourceException(e); } finally { - if (conn != null) writePool.offerConnection(conn); + if (conn != null) { + writePool.offerConnection(conn); + } } } @@ -1524,7 +1598,9 @@ public class DataJdbcSource extends DataSqlSource { final long s = System.currentTimeMillis(); final Connection conn = readPool.pollConnection(); try { - if (logger.isLoggable(Level.FINEST)) logger.finest("direct query sql=" + sql); + if (logger.isLoggable(Level.FINEST)) { + logger.finest("direct query sql=" + sql); + } //conn.setReadOnly(true); final Statement statement = conn.createStatement(); //final PreparedStatement statement = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); @@ -1537,7 +1613,9 @@ public class DataJdbcSource extends DataSqlSource { } catch (Exception ex) { throw new SourceException(ex); } finally { - if (conn != null) readPool.offerConnection(conn); + if (conn != null) { + readPool.offerConnection(conn); + } } } @@ -1555,26 +1633,34 @@ public class DataJdbcSource extends DataSqlSource { Object val = index > 0 ? getObject(index) : getObject(column); if (val - == null) return null; + == null) { + return null; + } return new java.util.Date( ((java.sql.Date) val).getTime()); } else if (t == java.time.LocalDate.class) { Object val = index > 0 ? getObject(index) : getObject(column); if (val - == null) return null; + == null) { + return null; + } return ((java.sql.Date) val).toLocalDate(); } else if (t == java.time.LocalTime.class) { Object val = index > 0 ? getObject(index) : getObject(column); if (val - == null) return null; + == null) { + return null; + } return ((java.sql.Time) val).toLocalTime(); } else if (t == java.time.LocalDateTime.class) { Object val = index > 0 ? getObject(index) : getObject(column); if (val - == null) return null; + == null) { + return null; + } return ((java.sql.Timestamp) val).toLocalDateTime(); } else if (t.getName().startsWith("java.sql.")) { return index > 0 ? (Serializable) getObject(index) : (Serializable) getObject(column); @@ -1687,8 +1773,12 @@ public class DataJdbcSource extends DataSqlSource { String username = prop.getProperty(DATA_SOURCE_USER, ""); String password = prop.getProperty(DATA_SOURCE_PASSWORD, ""); this.connectAttrs = new Properties(); - if (username != null) this.connectAttrs.put("user", username); - if (password != null) this.connectAttrs.put("password", password); + if (username != null) { + this.connectAttrs.put("user", username); + } + if (password != null) { + this.connectAttrs.put("password", password); + } try { this.driver = DriverManager.getDriver(this.url); } catch (SQLException e) { @@ -1749,7 +1839,9 @@ public class DataJdbcSource extends DataSqlSource { } catch (InterruptedException t) { logger.log(Level.WARNING, "take pooled connection error", t); } - if (conn == null) throw new SourceException("create pooled connection timeout"); + if (conn == null) { + throw new SourceException("create pooled connection timeout"); + } } } if (conn != null) { @@ -1776,7 +1868,9 @@ public class DataJdbcSource extends DataSqlSource { public void offerConnection(final C connection) { Connection conn = (Connection) connection; - if (conn == null) return; + if (conn == null) { + return; + } try { if (checkValid(conn) && queue.offer(conn)) { usingCounter.decrement(); @@ -1794,9 +1888,13 @@ public class DataJdbcSource extends DataSqlSource { protected boolean checkValid(Connection conn) { try { boolean rs = !conn.isClosed() && conn.isValid(1); - if (!rs) return rs; + if (!rs) { + return rs; + } Properties prop = conn.getClientInfo(); - if (prop == null) return false; + if (prop == null) { + return false; + } return prop == clientInfo || Objects.equals(prop.getProperty("version"), clientInfo.getProperty("version")); } catch (SQLException ex) { if (!"08S01".equals(ex.getSQLState())) {//MySQL特性, 长时间连接没使用会抛出com.mysql.jdbc.exceptions.jdbc4.CommunicationsException diff --git a/src/main/java/org/redkale/source/DataMemorySource.java b/src/main/java/org/redkale/source/DataMemorySource.java index 3f0bb314e..6962f4c84 100644 --- a/src/main/java/org/redkale/source/DataMemorySource.java +++ b/src/main/java/org/redkale/source/DataMemorySource.java @@ -68,7 +68,9 @@ public class DataMemorySource extends DataSqlSource implements SearchSource { @Override public void compile(Class clazz) { EntityInfo entityInfo = EntityInfo.compile(clazz, this); - if (entityInfo.getCache() == null) new EntityCache<>(entityInfo, null).clear(); + if (entityInfo.getCache() == null) { + new EntityCache<>(entityInfo, null).clear(); + } } @Override diff --git a/src/main/java/org/redkale/source/DataSource.java b/src/main/java/org/redkale/source/DataSource.java index a16e7ced1..254709a3a 100644 --- a/src/main/java/org/redkale/source/DataSource.java +++ b/src/main/java/org/redkale/source/DataSource.java @@ -342,7 +342,7 @@ public interface DataSource extends Resourcable { * * @param Entity泛型 * @param clazz Entity类 - * @param node 过滤条件 + * @param node 分库分表的过滤条件 * * @return 影响的记录条数 -1表示表不存在 */ @@ -354,7 +354,7 @@ public interface DataSource extends Resourcable { * * @param Entity泛型 * @param clazz Entity类 - * @param node 过滤条件 + * @param node 分库分表的过滤条件 * * @return 影响的记录条数CompletableFuture -1表示表不存在 */ @@ -405,7 +405,7 @@ public interface DataSource extends Resourcable { * * @param Entity泛型 * @param clazz Entity类 - * @param node 过滤条件 + * @param node 分库分表的过滤条件 * * @return 影响的记录条数CompletableFuture -1表示表不存在 */ diff --git a/src/main/java/org/redkale/source/DataSources.java b/src/main/java/org/redkale/source/DataSources.java index abd5c1ef8..ae72ea863 100644 --- a/src/main/java/org/redkale/source/DataSources.java +++ b/src/main/java/org/redkale/source/DataSources.java @@ -89,7 +89,9 @@ public final class DataSources { for (AnyValue itemConf : confs) { String name = itemConf.getValue("name"); String value = itemConf.getValue("value"); - if (name != null && value != null) prop.put(name, value); + if (name != null && value != null) { + prop.put(name, value); + } } } return createDataSource(unitName, prop, prop); @@ -189,9 +191,13 @@ public final class DataSources { @Deprecated //@deprecated @since 2.7.0 public static DataSource createDataSource(final String unitName, URL persistxml) throws IOException { - if (persistxml == null) persistxml = DataSources.class.getResource("/persistence.xml"); + if (persistxml == null) { + persistxml = DataSources.class.getResource("/persistence.xml"); + } InputStream in = persistxml == null ? null : persistxml.openStream(); - if (in == null) return null; + if (in == null) { + return null; + } Map map = loadPersistenceXml(in); Properties readprop = null; Properties writeprop = null; @@ -219,9 +225,15 @@ public final class DataSources { } } } - if (readprop == null) throw new IOException("Cannot find (resource.name = '" + unitName + "') DataSource"); - if (writeprop == null) writeprop = readprop; - if (readprop.getProperty(JDBC_URL, "").startsWith("memory:source")) return new DataMemorySource(unitName); + if (readprop == null) { + throw new IOException("Cannot find (resource.name = '" + unitName + "') DataSource"); + } + if (writeprop == null) { + writeprop = readprop; + } + if (readprop.getProperty(JDBC_URL, "").startsWith("memory:source")) { + return new DataMemorySource(unitName); + } return createDataSource(unitName, readprop, writeprop); } @@ -232,7 +244,9 @@ public final class DataSources { Map map = loadPersistenceXml(in); final Properties sourceProperties = new Properties(); map.forEach((unitName, prop) -> { - if (unitName.endsWith(".write")) return; + if (unitName.endsWith(".write")) { + return; + } if (unitName.endsWith(".read")) { String name = unitName.replace(".read", ""); prop.forEach((k, v) -> { diff --git a/src/main/java/org/redkale/source/DataSqlSource.java b/src/main/java/org/redkale/source/DataSqlSource.java index 867672807..7a6af58cd 100644 --- a/src/main/java/org/redkale/source/DataSqlSource.java +++ b/src/main/java/org/redkale/source/DataSqlSource.java @@ -141,7 +141,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override @ResourceListener public void onResourceChange(ResourceEvent[] events) { - if (events == null || events.length < 1) return; + if (events == null || events.length < 1) { + return; + } //不支持读写分离模式的动态切换 if (readConfProps == writeConfProps && (events[0].name().startsWith("read.") || events[0].name().startsWith("write."))) { @@ -284,26 +286,36 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public String toString() { - if (readConfProps == null) return getClass().getSimpleName() + "{}"; //compileMode模式下会为null + if (readConfProps == null) { //compileMode模式下会为null + return getClass().getSimpleName() + "{}"; + } if (readConfProps == writeConfProps) { String url = readConfProps.getProperty(DATA_SOURCE_URL); int pos = url.indexOf('?'); - if (pos > 0) url = url.substring(0, pos) + "..."; + if (pos > 0) { + url = url.substring(0, pos) + "..."; + } return getClass().getSimpleName() + "{url=" + url + "}"; } else { String readUrl = readConfProps.getProperty(DATA_SOURCE_URL); int pos = readUrl.indexOf('?'); - if (pos > 0) readUrl = readUrl.substring(0, pos) + "..."; + if (pos > 0) { + readUrl = readUrl.substring(0, pos) + "..."; + } String writeUrl = writeConfProps.getProperty(DATA_SOURCE_URL); pos = writeUrl.indexOf('?'); - if (pos > 0) writeUrl = writeUrl.substring(0, pos) + "..."; + if (pos > 0) { + writeUrl = writeUrl.substring(0, pos) + "..."; + } return getClass().getSimpleName() + "{readurl=" + readUrl + ",writeurl=" + writeUrl + "}"; } } //生成创建表的SQL protected String[] createTableSqls(EntityInfo info) { - if (info == null || !autoDDL) return null; + if (info == null || !autoDDL) { + return null; + } Table table = info.getType().getAnnotation(Table.class); if ("mysql".equals(dbtype())) { //mysql StringBuilder sb = new StringBuilder(); @@ -311,7 +323,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi EntityColumn primary = null; T one = info.constructorAttributes == null ? info.getCreator().create() : null; for (EntityColumn column : info.getDDLColumns()) { - if (column.primary) primary = column; + if (column.primary) { + primary = column; + } String sqltype = "VARCHAR(" + column.length + ")"; String sqlnull = column.primary ? "NOT NULL" : "NULL"; if (column.type == boolean.class || column.type == Boolean.class) { @@ -340,12 +354,16 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == float.class || column.type == Float.class) { sqltype = "FLOAT"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == double.class || column.type == Double.class) { sqltype = "DOUBLE"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == BigInteger.class) { @@ -359,7 +377,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == BigDecimal.class) { sqltype = "DECIMAL"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == String.class) { @@ -372,24 +392,36 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } } else if (column.length == 65535) { sqltype = "TEXT"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } else if (column.length <= 16777215) { sqltype = "MEDIUMTEXT"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } else { sqltype = "LONGTEXT"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } } else if (column.type == byte[].class) { if (column.length <= 65535) { sqltype = "BLOB"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } else if (column.length <= 16777215) { sqltype = "MEDIUMBLOB"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } else { sqltype = "LONGBLOB"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } } else if (column.type == java.time.LocalDate.class || column.type == java.util.Date.class || "java.sql.Date".equals(column.type.getName())) { sqltype = "DATE"; @@ -423,7 +455,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi comments.add("COMMENT ON TABLE " + info.getOriginTable() + " IS '" + table.comment().replace('\'', '"') + "'"); } for (EntityColumn column : info.getDDLColumns()) { - if (column.primary) primary = column; + if (column.primary) { + primary = column; + } String sqltype = "VARCHAR(" + column.length + ")"; String sqlnull = column.primary ? "NOT NULL" : "NULL"; if (column.type == boolean.class || column.type == Boolean.class) { @@ -452,12 +486,16 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == float.class || column.type == Float.class) { sqltype = "FLOAT4"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == double.class || column.type == Double.class) { sqltype = "FLOAT8"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == BigInteger.class) { @@ -471,7 +509,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == BigDecimal.class) { sqltype = "NUMERIC"; - if (column.precision > 0) sqltype += "(" + column.precision + "," + column.scale + ")"; + if (column.precision > 0) { + sqltype += "(" + column.precision + "," + column.scale + ")"; + } Number val = one == null ? null : (Number) info.getAttribute(column.field).get(one); sqlnull = "NOT NULL DEFAULT " + (val == null ? 0 : val); } else if (column.type == String.class) { @@ -484,11 +524,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } } else { sqltype = "TEXT"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } } else if (column.type == byte[].class) { sqltype = "BYTEA"; - if (!column.nullable) sqlnull = "NOT NULL"; + if (!column.nullable) { + sqlnull = "NOT NULL"; + } } else if (column.type == java.time.LocalDate.class || column.type == java.util.Date.class || "java.sql.Date".equals(column.type.getName())) { sqltype = "DATE"; } else if (column.type == java.time.LocalTime.class || "java.sql.Time".equals(column.type.getName())) { @@ -515,7 +559,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Local protected boolean isTableNotExist(EntityInfo info, String sqlCode) { - if (sqlCode == null || sqlCode.isEmpty()) return false; + if (sqlCode == null || sqlCode.isEmpty()) { + return false; + } return tableNotExistSqlstates.contains(';' + sqlCode + ';'); } @@ -594,7 +640,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Local public final String dbtype() { - if (dbtype == null) throw new NullPointerException("dbtype is null"); + if (dbtype == null) { + throw new NullPointerException("dbtype is null"); + } return dbtype; } @@ -708,13 +756,17 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public void refreshCache(Class clazz) { EntityInfo info = loadEntityInfo(clazz); EntityCache cache = info.getCache(); - if (cache == null) return; + if (cache == null) { + return; + } cache.fullLoadAsync(); } protected CharSequence formatValueToString(final EntityInfo info, Object value) { if ("mysql".equals(dbtype)) { - if (value == null) return null; + if (value == null) { + return null; + } if (value instanceof CharSequence) { return new StringBuilder().append('\'').append(value.toString().replace("\\", "\\\\").replace("'", "\\'")).append('\'').toString(); } else if (!(value instanceof Number) && !(value instanceof java.util.Date) @@ -725,7 +777,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } else if (value != null && value instanceof CharSequence && "postgresql".equals(dbtype)) { String s = String.valueOf(value); int pos = s.indexOf('\''); - if (pos >= 0) return new StringBuilder().append("E'").append(value.toString().replace("\\", "\\\\").replace("'", "\\'")).append('\'').toString(); + if (pos >= 0) { + return new StringBuilder().append("E'").append(value.toString().replace("\\", "\\\\").replace("'", "\\'")).append('\'').toString(); + } } return info.formatSQLValue(value, null); } @@ -741,10 +795,14 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi */ @Override public int insert(T... entitys) { - if (entitys.length == 0) return 0; + if (entitys.length == 0) { + return 0; + } checkEntity("insert", false, entitys); final EntityInfo info = loadEntityInfo((Class) entitys[0].getClass()); - if (isOnlyCache(info)) return insertCache(info, entitys); + if (isOnlyCache(info)) { + return insertCache(info, entitys); + } return insertDB(info, entitys).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -756,20 +814,26 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture insertAsync(T... entitys) { - if (entitys.length == 0) return CompletableFuture.completedFuture(0); + if (entitys.length == 0) { + return CompletableFuture.completedFuture(0); + } CompletableFuture future = checkEntity("insert", true, entitys); - if (future != null) return future; + if (future != null) { + return future; + } final EntityInfo info = loadEntityInfo((Class) entitys[0].getClass()); if (isOnlyCache(info)) { return CompletableFuture.completedFuture(insertCache(info, entitys)); } - if (isAsync()) return insertDB(info, entitys).whenComplete((rs, t) -> { + if (isAsync()) { + return insertDB(info, entitys).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { insertCache(info, entitys); } }); + } return CompletableFuture.supplyAsync(() -> insertDB(info, entitys).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -781,7 +845,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int insertCache(final EntityInfo info, T... entitys) { final EntityCache cache = info.getCache(); - if (cache == null) return 0; + if (cache == null) { + return 0; + } int c = 0; for (final T value : entitys) { c += cache.insert(value); @@ -800,7 +866,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi */ @Override public int delete(T... entitys) { - if (entitys.length == 0) return -1; + if (entitys.length == 0) { + return -1; + } checkEntity("delete", false, entitys); final Class clazz = (Class) entitys[0].getClass(); final EntityInfo info = loadEntityInfo(clazz); @@ -815,9 +883,13 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture deleteAsync(final T... entitys) { - if (entitys.length == 0) return CompletableFuture.completedFuture(-1); + if (entitys.length == 0) { + return CompletableFuture.completedFuture(-1); + } CompletableFuture future = checkEntity("delete", true, entitys); - if (future != null) return future; + if (future != null) { + return future; + } final Class clazz = (Class) entitys[0].getClass(); final EntityInfo info = loadEntityInfo(clazz); final Attribute primary = info.getPrimary(); @@ -831,9 +903,13 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int delete(Class clazz, Serializable... pks) { - if (pks.length == 0) return -1; + if (pks.length == 0) { + return -1; + } final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return deleteCache(info, -1, pks); + if (isOnlyCache(info)) { + return deleteCache(info, -1, pks); + } return deleteCompose(info, pks).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -845,18 +921,22 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture deleteAsync(final Class clazz, final Serializable... pks) { - if (pks.length == 0) return CompletableFuture.completedFuture(-1); + if (pks.length == 0) { + return CompletableFuture.completedFuture(-1); + } final EntityInfo info = loadEntityInfo(clazz); if (isOnlyCache(info)) { return CompletableFuture.completedFuture(deleteCache(info, -1, pks)); } - if (isAsync()) return deleteCompose(info, pks).whenComplete((rs, t) -> { + if (isAsync()) { + return deleteCompose(info, pks).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { deleteCache(info, rs, pks); } }); + } return CompletableFuture.supplyAsync(() -> deleteCompose(info, pks).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -879,7 +959,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int delete(Class clazz, final Flipper flipper, FilterNode node) { final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return deleteCache(info, -1, flipper, node); + if (isOnlyCache(info)) { + return deleteCache(info, -1, flipper, node); + } return this.deleteCompose(info, flipper, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -895,13 +977,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(deleteCache(info, -1, flipper, node)); } - if (isAsync()) return this.deleteCompose(info, flipper, node).whenComplete((rs, t) -> { + if (isAsync()) { + return this.deleteCompose(info, flipper, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { deleteCache(info, rs, flipper, node); } }); + } return CompletableFuture.supplyAsync(() -> this.deleteCompose(info, flipper, node).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -913,7 +997,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected CompletableFuture deleteCompose(final EntityInfo info, final Serializable... pks) { String sql = deleteSql(info, pks); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " delete sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " delete sql=" + sql); + } return deleteDB(info, null, sql); } @@ -927,7 +1013,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } String sql = "DELETE FROM " + info.getTable(pks[0]) + " WHERE " + info.getPrimarySQLColumn() + " IN ("; for (int i = 0; i < pks.length; i++) { - if (i > 0) sql += ','; + if (i > 0) { + sql += ','; + } sql += info.formatSQLValue(info.getPrimarySQLColumn(), pks[i], sqlFormatter); } sql += ")"; @@ -987,7 +1075,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int clearTable(Class clazz, FilterNode node) { final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return clearTableCache(info, node); + if (isOnlyCache(info)) { + return clearTableCache(info, node); + } return this.clearTableCompose(info, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1003,13 +1093,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(clearTableCache(info, node)); } - if (isAsync()) return this.clearTableCompose(info, node).whenComplete((rs, t) -> { + if (isAsync()) { + return this.clearTableCompose(info, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { clearTableCache(info, node); } }); + } return CompletableFuture.supplyAsync(() -> this.clearTableCompose(info, node).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1043,7 +1135,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int dropTable(Class clazz, FilterNode node) { final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return dropTableCache(info, node); + if (isOnlyCache(info)) { + return dropTableCache(info, node); + } return this.dropTableCompose(info, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1059,13 +1153,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(dropTableCache(info, node)); } - if (isAsync()) return this.dropTableCompose(info, node).whenComplete((rs, t) -> { + if (isAsync()) { + return this.dropTableCompose(info, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { dropTableCache(info, node); } }); + } return CompletableFuture.supplyAsync(() -> this.dropTableCompose(info, node).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1098,26 +1194,34 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int clearTableCache(final EntityInfo info, FilterNode node) { final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } return cache.clear(); } protected int dropTableCache(final EntityInfo info, FilterNode node) { final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } return cache.drop(); } protected int deleteCache(final EntityInfo info, int count, Flipper flipper, FilterNode node) { final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } Serializable[] ids = cache.delete(flipper, node); return count >= 0 ? count : (ids == null ? 0 : ids.length); } protected int deleteCache(final EntityInfo info, int count, Serializable... pks) { final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } int c = 0; for (Serializable key : pks) { c += cache.delete(key); @@ -1126,12 +1230,20 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } protected static StringBuilder multisplit(char ch1, char ch2, String split, StringBuilder sb, String str, int from) { - if (str == null) return sb; + if (str == null) { + return sb; + } int pos1 = str.indexOf(ch1, from); - if (pos1 < 0) return sb; + if (pos1 < 0) { + return sb; + } int pos2 = str.indexOf(ch2, from); - if (pos2 < 0) return sb; - if (sb.length() > 0) sb.append(split); + if (pos2 < 0) { + return sb; + } + if (sb.length() > 0) { + sb.append(split); + } sb.append(str.substring(pos1 + 1, pos2)); return multisplit(ch1, ch2, split, sb, str, pos2 + 1); } @@ -1147,7 +1259,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi */ @Override public int update(T... entitys) { - if (entitys.length == 0) return -1; + if (entitys.length == 0) { + return -1; + } checkEntity("update", false, entitys); final Class clazz = (Class) entitys[0].getClass(); final EntityInfo info = loadEntityInfo(clazz); @@ -1165,21 +1279,27 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture updateAsync(final T... entitys) { - if (entitys.length == 0) return CompletableFuture.completedFuture(-1); + if (entitys.length == 0) { + return CompletableFuture.completedFuture(-1); + } CompletableFuture future = checkEntity("update", true, entitys); - if (future != null) return future; + if (future != null) { + return future; + } final Class clazz = (Class) entitys[0].getClass(); final EntityInfo info = loadEntityInfo(clazz); if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, entitys)); } - if (isAsync()) return updateEntityDB(info, entitys).whenComplete((rs, t) -> { + if (isAsync()) { + return updateEntityDB(info, entitys).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, entitys); } }); + } return CompletableFuture.supplyAsync(() -> updateEntityDB(info, entitys).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1203,7 +1323,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int updateColumn(Class clazz, Serializable pk, String column, Serializable colval) { final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return updateCache(info, -1, pk, column, colval); + if (isOnlyCache(info)) { + return updateCache(info, -1, pk, column, colval); + } return updateColumnCompose(info, pk, column, colval).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1219,13 +1341,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, pk, column, colval)); } - if (isAsync()) return updateColumnCompose(info, pk, column, colval).whenComplete((rs, t) -> { + if (isAsync()) { + return updateColumnCompose(info, pk, column, colval).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, pk, column, colval); } }); + } return CompletableFuture.supplyAsync(() -> updateColumnCompose(info, pk, column, colval).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1266,7 +1390,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int updateColumn(Class clazz, String column, Serializable colval, FilterNode node) { final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return updateCache(info, -1, column, colval, node); + if (isOnlyCache(info)) { + return updateCache(info, -1, column, colval, node); + } return this.updateColumnCompose(info, column, colval, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1282,13 +1408,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, column, colval, node)); } - if (isAsync()) return this.updateColumnCompose(info, column, colval, node).whenComplete((rs, t) -> { + if (isAsync()) { + return this.updateColumnCompose(info, column, colval, node).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, column, colval, node); } }); + } return CompletableFuture.supplyAsync(() -> this.updateColumnCompose(info, column, colval, node).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1362,9 +1490,13 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi */ @Override public int updateColumn(final Class clazz, final Serializable pk, final ColumnValue... values) { - if (values == null || values.length < 1) return -1; + if (values == null || values.length < 1) { + return -1; + } final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return updateCache(info, -1, pk, values); + if (isOnlyCache(info)) { + return updateCache(info, -1, pk, values); + } return this.updateColumnCompose(info, pk, values).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1376,18 +1508,22 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture updateColumnAsync(final Class clazz, final Serializable pk, final ColumnValue... values) { - if (values == null || values.length < 1) return CompletableFuture.completedFuture(-1); + if (values == null || values.length < 1) { + return CompletableFuture.completedFuture(-1); + } final EntityInfo info = loadEntityInfo(clazz); if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, pk, values)); } - if (isAsync()) return this.updateColumnCompose(info, pk, values).whenComplete((rs, t) -> { + if (isAsync()) { + return this.updateColumnCompose(info, pk, values).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, pk, values); } }); + } return CompletableFuture.supplyAsync(() -> this.updateColumnCompose(info, pk, values).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1407,29 +1543,43 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi List blobs = null; int index = 0; for (ColumnValue col : values) { - if (col == null) continue; + if (col == null) { + continue; + } Attribute attr = info.getUpdateAttribute(col.getColumn()); - if (attr == null) throw new SourceException(info.getType() + " cannot found column " + col.getColumn()); - if (setsql.length() > 0) setsql.append(", "); + if (attr == null) { + throw new SourceException(info.getType() + " cannot found column " + col.getColumn()); + } + if (setsql.length() > 0) { + setsql.append(", "); + } String sqlColumn = info.getSQLColumn(null, col.getColumn()); if (col.getValue() instanceof byte[]) { - if (blobs == null) blobs = new ArrayList<>(); + if (blobs == null) { + blobs = new ArrayList<>(); + } blobs.add((byte[]) col.getValue()); setsql.append(sqlColumn).append("=").append(prepareParamSign(++index)); } else { setsql.append(sqlColumn).append("=").append(info.formatSQLValue(sqlColumn, attr, col, sqlFormatter)); } } - if (setsql.length() < 1) throw new SourceException("update non column-value array"); + if (setsql.length() < 1) { + throw new SourceException("update non column-value array"); + } String sql = "UPDATE " + info.getTable(pk) + " SET " + setsql + " WHERE " + info.getPrimarySQLColumn() + "=" + info.formatSQLValue(info.getPrimarySQLColumn(), pk, sqlFormatter); return new SqlInfo(sql, blobs); } @Override public int updateColumn(final Class clazz, final FilterNode node, final Flipper flipper, final ColumnValue... values) { - if (values == null || values.length < 1) return -1; + if (values == null || values.length < 1) { + return -1; + } final EntityInfo info = loadEntityInfo(clazz); - if (isOnlyCache(info)) return updateCache(info, -1, node, flipper, values); + if (isOnlyCache(info)) { + return updateCache(info, -1, node, flipper, values); + } return this.updateColumnCompose(info, node, flipper, values).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1441,18 +1591,22 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture updateColumnAsync(final Class clazz, final FilterNode node, final Flipper flipper, final ColumnValue... values) { - if (values == null || values.length < 1) return CompletableFuture.completedFuture(-1); + if (values == null || values.length < 1) { + return CompletableFuture.completedFuture(-1); + } final EntityInfo info = loadEntityInfo(clazz); if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, node, flipper, values)); } - if (isAsync()) return this.updateColumnCompose(info, node, flipper, values).whenComplete((rs, t) -> { + if (isAsync()) { + return this.updateColumnCompose(info, node, flipper, values).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, node, flipper, values); } }); + } return CompletableFuture.supplyAsync(() -> this.updateColumnCompose(info, node, flipper, values).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1474,20 +1628,30 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi boolean pgsql = "postgresql".equals(dbtype()); String alias = pgsql ? null : "a"; //postgresql的BUG, UPDATE的SET中不能含别名 for (ColumnValue col : values) { - if (col == null) continue; + if (col == null) { + continue; + } Attribute attr = info.getUpdateAttribute(col.getColumn()); - if (attr == null) continue; - if (setsql.length() > 0) setsql.append(", "); + if (attr == null) { + continue; + } + if (setsql.length() > 0) { + setsql.append(", "); + } String sqlColumn = info.getSQLColumn(alias, col.getColumn()); if (col.getValue() instanceof byte[]) { - if (blobs == null) blobs = new ArrayList<>(); + if (blobs == null) { + blobs = new ArrayList<>(); + } blobs.add((byte[]) col.getValue()); setsql.append(sqlColumn).append("=").append(prepareParamSign(++index)); } else { setsql.append(sqlColumn).append("=").append(info.formatSQLValue(sqlColumn, attr, col, sqlFormatter)); } } - if (setsql.length() < 1) throw new SourceException("update non column-value array"); + if (setsql.length() < 1) { + throw new SourceException("update non column-value array"); + } Map joinTabalis = node == null ? null : node.getJoinTabalis(); CharSequence join = node == null ? null : node.createSQLJoin(this, true, joinTabalis, new HashSet<>(), info); CharSequence where = node == null ? null : node.createSQLExpress(this, info, joinTabalis); @@ -1534,25 +1698,35 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi //返回不存在的字段名,null表示字段都合法; protected String checkIllegalColumn(final EntityInfo info, SelectColumn selects) { - if (selects == null) return null; + if (selects == null) { + return null; + } String[] columns = selects.getColumns(); - if (columns == null) return null; + if (columns == null) { + return null; + } for (String col : columns) { - if (info.getAttribute(col) == null) return col; + if (info.getAttribute(col) == null) { + return col; + } } return null; } @Override public int updateColumn(final T entity, final SelectColumn selects) { - if (entity == null || selects == null) return -1; + if (entity == null || selects == null) { + return -1; + } Class clazz = (Class) entity.getClass(); final EntityInfo info = loadEntityInfo(clazz); String illegalColumn = checkIllegalColumn(info, selects); if (illegalColumn != null) { throw new SourceException(info.getType() + " cannot found column " + illegalColumn); } - if (isOnlyCache(info)) return updateCache(info, -1, false, entity, null, selects); + if (isOnlyCache(info)) { + return updateCache(info, -1, false, entity, null, selects); + } return this.updateColumnCompose(info, false, entity, null, selects).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1564,7 +1738,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture updateColumnAsync(final T entity, final SelectColumn selects) { - if (entity == null || selects == null) return CompletableFuture.completedFuture(-1); + if (entity == null || selects == null) { + return CompletableFuture.completedFuture(-1); + } Class clazz = (Class) entity.getClass(); final EntityInfo info = loadEntityInfo(clazz); String illegalColumn = checkIllegalColumn(info, selects); @@ -1574,13 +1750,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, false, entity, null, selects)); } - if (isAsync()) return this.updateColumnCompose(info, false, entity, null, selects).whenComplete((rs, t) -> { + if (isAsync()) { + return this.updateColumnCompose(info, false, entity, null, selects).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, false, entity, null, selects); } }); + } return CompletableFuture.supplyAsync(() -> this.updateColumnCompose(info, false, entity, null, selects).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1592,14 +1770,18 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public int updateColumn(final T entity, final FilterNode node, final SelectColumn selects) { - if (entity == null || node == null || selects == null) return -1; + if (entity == null || node == null || selects == null) { + return -1; + } Class clazz = (Class) entity.getClass(); final EntityInfo info = loadEntityInfo(clazz); String illegalColumn = checkIllegalColumn(info, selects); if (illegalColumn != null) { throw new SourceException(info.getType() + " cannot found column " + illegalColumn); } - if (isOnlyCache(info)) return updateCache(info, -1, true, entity, node, selects); + if (isOnlyCache(info)) { + return updateCache(info, -1, true, entity, node, selects); + } return this.updateColumnCompose(info, true, entity, node, selects).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1611,7 +1793,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture updateColumnAsync(final T entity, final FilterNode node, final SelectColumn selects) { - if (entity == null || node == null || selects == null) return CompletableFuture.completedFuture(-1); + if (entity == null || node == null || selects == null) { + return CompletableFuture.completedFuture(-1); + } Class clazz = (Class) entity.getClass(); final EntityInfo info = loadEntityInfo(clazz); String illegalColumn = checkIllegalColumn(info, selects); @@ -1621,13 +1805,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (isOnlyCache(info)) { return CompletableFuture.completedFuture(updateCache(info, -1, true, entity, node, selects)); } - if (isAsync()) return this.updateColumnCompose(info, true, entity, node, selects).whenComplete((rs, t) -> { + if (isAsync()) { + return this.updateColumnCompose(info, true, entity, node, selects).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); } else { updateCache(info, rs, true, entity, node, selects); } }); + } return CompletableFuture.supplyAsync(() -> this.updateColumnCompose(info, true, entity, node, selects).join(), getExecutor()).whenComplete((rs, t) -> { if (t != null) { errorCompleteConsumer.accept(rs, t); @@ -1648,17 +1834,25 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi int index = 0; String alias = "postgresql".equals(dbtype()) ? null : "a"; //postgresql的BUG, UPDATE的SET中不能含别名 for (Attribute attr : info.updateAttributes) { - if (!selects.test(attr.field())) continue; - if (setsql.length() > 0) setsql.append(", "); + if (!selects.test(attr.field())) { + continue; + } + if (setsql.length() > 0) { + setsql.append(", "); + } setsql.append(info.getSQLColumn(alias, attr.field())); Serializable val = info.getFieldValue(attr, entity); if (val instanceof byte[]) { - if (blobs == null) blobs = new ArrayList<>(); + if (blobs == null) { + blobs = new ArrayList<>(); + } blobs.add((byte[]) val); setsql.append("=").append(prepareParamSign(++index)); } else { CharSequence sqlval = info.formatSQLValue(val, sqlFormatter); - if (sqlval == null && info.isNotNullJson(attr)) sqlval = "''"; + if (sqlval == null && info.isNotNullJson(attr)) { + sqlval = "''"; + } setsql.append("=").append(sqlval); } } @@ -1696,10 +1890,14 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int updateCache(final EntityInfo info, int count, final boolean needNode, final T entity, final FilterNode node, final SelectColumn selects) { final EntityCache cache = info.getCache(); - if (cache == null) return count; + if (cache == null) { + return count; + } final List> attrs = new ArrayList<>(); for (Attribute attr : info.updateAttributes) { - if (!selects.test(attr.field())) continue; + if (!selects.test(attr.field())) { + continue; + } attrs.add(attr); } if (needNode) { @@ -1713,13 +1911,19 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int updateCache(final EntityInfo info, int count, final FilterNode node, final Flipper flipper, final ColumnValue... values) { final EntityCache cache = info.getCache(); - if (cache == null) return count; + if (cache == null) { + return count; + } final List> attrs = new ArrayList<>(); final List cols = new ArrayList<>(); for (ColumnValue col : values) { - if (col == null) continue; + if (col == null) { + continue; + } Attribute attr = info.getUpdateAttribute(col.getColumn()); - if (attr == null) continue; + if (attr == null) { + continue; + } attrs.add(attr); cols.add(col); } @@ -1729,13 +1933,19 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int updateCache(final EntityInfo info, int count, final Serializable pk, final ColumnValue... values) { final EntityCache cache = info.getCache(); - if (cache == null) return count; + if (cache == null) { + return count; + } final List> attrs = new ArrayList<>(); final List cols = new ArrayList<>(); for (ColumnValue col : values) { - if (col == null) continue; + if (col == null) { + continue; + } Attribute attr = info.getUpdateAttribute(col.getColumn()); - if (attr == null) continue; + if (attr == null) { + continue; + } attrs.add(attr); cols.add(col); } @@ -1745,21 +1955,27 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi protected int updateCache(final EntityInfo info, int count, String column, final Serializable colval, FilterNode node) { final EntityCache cache = info.getCache(); - if (cache == null) return count; + if (cache == null) { + return count; + } T[] rs = cache.update(info.getAttribute(column), colval, node); return count >= 0 ? count : (rs == null ? 0 : 1); } protected int updateCache(final EntityInfo info, int count, final Serializable pk, final String column, final Serializable colval) { final EntityCache cache = info.getCache(); - if (cache == null) return count; + if (cache == null) { + return count; + } T rs = cache.update(pk, info.getAttribute(column), colval); return count >= 0 ? count : (rs == null ? 0 : 1); } protected int updateCache(final EntityInfo info, int count, T... entitys) { final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } int c2 = 0; for (final T value : entitys) { c2 += cache.update(value); @@ -1770,13 +1986,17 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public int reloadCache(Class clazz, Serializable... pks) { final EntityInfo info = loadEntityInfo(clazz); final EntityCache cache = info.getCache(); - if (cache == null) return -1; + if (cache == null) { + return -1; + } String column = info.getPrimary().field(); int c = 0; for (Serializable id : pks) { Sheet sheet = querySheetCompose(false, true, false, clazz, null, FLIPPER_ONE, FilterNode.create(column, id)).join(); T value = sheet.isEmpty() ? null : sheet.list().get(0); - if (value != null) c += cache.update(value); + if (value != null) { + c += cache.update(value); + } } return c; } @@ -1815,7 +2035,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi return CompletableFuture.completedFuture(map); } } - if (isAsync()) return getNumberMapCompose(info, node, columns); + if (isAsync()) { + return getNumberMapCompose(info, node, columns); + } return CompletableFuture.supplyAsync(() -> (Map) getNumberMapCompose(info, node, columns).join(), getExecutor()); } @@ -1827,13 +2049,17 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi StringBuilder sb = new StringBuilder(); for (FilterFuncColumn ffc : columns) { for (String col : ffc.cols()) { - if (sb.length() > 0) sb.append(", "); + if (sb.length() > 0) { + sb.append(", "); + } sb.append(ffc.func.getColumn((col == null || col.isEmpty() ? "*" : info.getSQLColumn("a", col)))); } } final String sql = "SELECT " + sb + " FROM " + info.getTable(node) + " a" + (join == null ? "" : join) + ((where == null || where.length() == 0) ? "" : (" WHERE " + where)); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " getnumbermap sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " getnumbermap sql=" + sql); + } return getNumberMapDB(info, sql, columns); } @@ -1847,7 +2073,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi for (String col : ffc.cols()) { Object o = dataset.getObject(++index); Number rs = ffc.getDefvalue(); - if (o != null) rs = (Number) o; + if (o != null) { + rs = (Number) o; + } map.put(ffc.col(col), rs); } } @@ -1879,7 +2107,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi return CompletableFuture.completedFuture(cache.getNumberResult(func, defVal, column, node)); } } - if (isAsync()) return getNumberResultCompose(info, entityClass, func, defVal, column, node); + if (isAsync()) { + return getNumberResultCompose(info, entityClass, func, defVal, column, node); + } return CompletableFuture.supplyAsync(() -> getNumberResultCompose(info, entityClass, func, defVal, column, node).join(), getExecutor()); } @@ -1890,7 +2120,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final CharSequence where = node == null ? null : node.createSQLExpress(this, info, joinTabalis); final String sql = "SELECT " + func.getColumn((column == null || column.isEmpty() ? "*" : info.getSQLColumn("a", column))) + " FROM " + info.getTable(node) + " a" + (join == null ? "" : join) + ((where == null || where.length() == 0) ? "" : (" WHERE " + where)); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(entityClass.getSimpleName() + " getNumberResult sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(entityClass.getSimpleName() + " getNumberResult sql=" + sql); + } return getNumberResultDB(info, sql, defVal, column); } @@ -1900,7 +2132,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi Number rs = defVal; if (dataset.next()) { Object o = dataset.getObject(1); - if (o != null) rs = (Number) o; + if (o != null) { + rs = (Number) o; + } } dataset.close(); return rs; @@ -1929,7 +2163,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi return CompletableFuture.completedFuture(cache.queryColumnMap(keyColumn, func, funcColumn, node)); } } - if (isAsync()) return queryColumnMapCompose(info, keyColumn, func, funcColumn, node); + if (isAsync()) { + return queryColumnMapCompose(info, keyColumn, func, funcColumn, node); + } return CompletableFuture.supplyAsync(() -> (Map) queryColumnMapCompose(info, keyColumn, func, funcColumn, node).join(), getExecutor()); } @@ -1950,13 +2186,17 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi int b = 0; StringBuilder union = new StringBuilder(); for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } union.append("SELECT a.").append(keySqlColumn).append(", ").append(funcSqlColumn) .append(" FROM ").append(table).append(" a").append(joinAndWhere); } sql = "SELECT a." + keySqlColumn + ", " + funcSqlColumn + " FROM (" + (union) + ") a"; } - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " querycolumnmap sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " querycolumnmap sql=" + sql); + } return queryColumnMapDB(info, sql, keyColumn); } @@ -2011,7 +2251,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi return CompletableFuture.completedFuture(cache.queryColumnMap(funcNodes, groupByColumns, node)); } } - if (isAsync()) return queryColumnMapCompose(info, funcNodes, groupByColumns, node); + if (isAsync()) { + return queryColumnMapCompose(info, funcNodes, groupByColumns, node); + } return CompletableFuture.supplyAsync(() -> (Map) queryColumnMapCompose(info, funcNodes, groupByColumns, node).join(), getExecutor()); } @@ -2019,13 +2261,17 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final StringBuilder groupBySqlColumns = new StringBuilder(); if (groupByColumns != null && groupByColumns.length > 0) { for (int i = 0; i < groupByColumns.length; i++) { - if (groupBySqlColumns.length() > 0) groupBySqlColumns.append(", "); + if (groupBySqlColumns.length() > 0) { + groupBySqlColumns.append(", "); + } groupBySqlColumns.append(info.getSQLColumn("a", groupByColumns[i])); } } final StringBuilder funcSqlColumns = new StringBuilder(); for (int i = 0; i < funcNodes.length; i++) { - if (funcSqlColumns.length() > 0) funcSqlColumns.append(", "); + if (funcSqlColumns.length() > 0) { + funcSqlColumns.append(", "); + } if (funcNodes[i] instanceof ColumnFuncNode) { funcSqlColumns.append(info.formatSQLValue((Attribute) null, "a", (ColumnFuncNode) funcNodes[i], sqlFormatter)); } else { @@ -2042,23 +2288,35 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi String sql; if (tables.length == 1) { sql = "SELECT "; - if (groupBySqlColumns.length() > 0) sql += groupBySqlColumns + ", "; + if (groupBySqlColumns.length() > 0) { + sql += groupBySqlColumns + ", "; + } sql += funcSqlColumns + " FROM " + tables[0] + " a" + joinAndWhere; } else { StringBuilder union = new StringBuilder(); for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } String subsql = "SELECT "; - if (groupBySqlColumns.length() > 0) subsql += groupBySqlColumns.toString() + ", "; + if (groupBySqlColumns.length() > 0) { + subsql += groupBySqlColumns.toString() + ", "; + } subsql += funcSqlColumns.toString() + " FROM " + table + " a" + joinAndWhere; union.append(subsql); } sql = "SELECT "; - if (groupBySqlColumns.length() > 0) sql += groupBySqlColumns + ", "; + if (groupBySqlColumns.length() > 0) { + sql += groupBySqlColumns + ", "; + } sql += funcSqlColumns + " FROM (" + (union) + ") a"; } - if (groupBySqlColumns.length() > 0) sql += " GROUP BY " + groupBySqlColumns; - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " querycolumnmap sql=" + sql); + if (groupBySqlColumns.length() > 0) { + sql += " GROUP BY " + groupBySqlColumns; + } + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " querycolumnmap sql=" + sql); + } return queryColumnMapDB(info, sql, funcNodes, groupByColumns); } @@ -2092,11 +2350,15 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture findsAsync(Class clazz, final SelectColumn selects, Serializable... pks) { final EntityInfo info = loadEntityInfo(clazz); - if (pks == null || pks.length == 0) return CompletableFuture.completedFuture(info.getArrayer().apply(0)); + if (pks == null || pks.length == 0) { + return CompletableFuture.completedFuture(info.getArrayer().apply(0)); + } final EntityCache cache = info.getCache(); if (cache != null) { T[] rs = selects == null ? cache.finds(pks) : cache.finds(selects, pks); - if (cache.isFullLoaded() || rs != null) return CompletableFuture.completedFuture(rs); + if (cache.isFullLoaded() || rs != null) { + return CompletableFuture.completedFuture(rs); + } } return findsComposeAsync(info, selects, pks); } @@ -2138,7 +2400,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { T rs = selects == null ? cache.find(pk) : cache.find(selects, pk); - if (cache.isFullLoaded() || rs != null) return rs; + if (cache.isFullLoaded() || rs != null) { + return rs; + } } return findCompose(info, selects, pk).join(); } @@ -2149,16 +2413,22 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { T rs = selects == null ? cache.find(pk) : cache.find(selects, pk); - if (cache.isFullLoaded() || rs != null) return CompletableFuture.completedFuture(rs); + if (cache.isFullLoaded() || rs != null) { + return CompletableFuture.completedFuture(rs); + } + } + if (isAsync()) { + return findCompose(info, selects, pk); } - if (isAsync()) return findCompose(info, selects, pk); return CompletableFuture.supplyAsync(() -> findCompose(info, selects, pk).join(), getExecutor()); } protected CompletableFuture findCompose(final EntityInfo info, final SelectColumn selects, Serializable pk) { String column = info.getPrimarySQLColumn(); final String sql = "SELECT " + info.getQueryColumns(null, selects) + " FROM " + info.getTable(pk) + " WHERE " + column + "=" + info.formatSQLValue(column, pk, sqlFormatter); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + } return findDB(info, sql, true, selects); } @@ -2166,7 +2436,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public T find(final Class clazz, final SelectColumn selects, final FilterNode node) { final EntityInfo info = loadEntityInfo(clazz); final EntityCache cache = info.getCache(); - if (cache != null && cache.isFullLoaded() && (node == null || isCacheUseable(node, this))) return cache.find(selects, node); + if (cache != null && cache.isFullLoaded() && (node == null || isCacheUseable(node, this))) { + return cache.find(selects, node); + } return this.findCompose(info, selects, node).join(); } @@ -2177,7 +2449,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi if (cache != null && cache.isFullLoaded() && (node == null || isCacheUseable(node, this))) { return CompletableFuture.completedFuture(cache.find(selects, node)); } - if (isAsync()) return this.findCompose(info, selects, node); + if (isAsync()) { + return this.findCompose(info, selects, node); + } return CompletableFuture.supplyAsync(() -> this.findCompose(info, selects, node).join(), getExecutor()); } @@ -2193,12 +2467,16 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } else { StringBuilder union = new StringBuilder(); for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } union.append("SELECT ").append(info.getQueryColumns("a", selects)).append(" FROM ").append(table).append(" a").append(joinAndWhere); } sql = "SELECT " + info.getQueryColumns("a", selects) + " FROM (" + (union) + ") a"; } - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + } return findDB(info, sql, false, selects); } @@ -2217,7 +2495,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { Serializable val = cache.findColumn(column, defValue, pk); - if (cache.isFullLoaded() || val != null) return val; + if (cache.isFullLoaded() || val != null) { + return val; + } } return findColumnCompose(info, column, defValue, pk).join(); } @@ -2228,15 +2508,21 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { Serializable val = cache.findColumn(column, defValue, pk); - if (cache.isFullLoaded() || val != null) return CompletableFuture.completedFuture(val); + if (cache.isFullLoaded() || val != null) { + return CompletableFuture.completedFuture(val); + } + } + if (isAsync()) { + return findColumnCompose(info, column, defValue, pk); } - if (isAsync()) return findColumnCompose(info, column, defValue, pk); return CompletableFuture.supplyAsync(() -> findColumnCompose(info, column, defValue, pk).join(), getExecutor()); } protected CompletableFuture findColumnCompose(final EntityInfo info, String column, final Serializable defValue, final Serializable pk) { final String sql = "SELECT " + info.getSQLColumn(null, column) + " FROM " + info.getTable(pk) + " WHERE " + info.getPrimarySQLColumn() + "=" + info.formatSQLValue(info.getPrimarySQLColumn(), pk, sqlFormatter); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + } return findColumnDB(info, sql, true, column, defValue); } @@ -2246,7 +2532,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { Serializable val = cache.findColumn(column, defValue, node); - if (cache.isFullLoaded() || val != null) return val; + if (cache.isFullLoaded() || val != null) { + return val; + } } return this.findColumnCompose(info, column, defValue, node).join(); } @@ -2257,9 +2545,13 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { Serializable val = cache.findColumn(column, defValue, node); - if (cache.isFullLoaded() || val != null) return CompletableFuture.completedFuture(val); + if (cache.isFullLoaded() || val != null) { + return CompletableFuture.completedFuture(val); + } + } + if (isAsync()) { + return this.findColumnCompose(info, column, defValue, node); } - if (isAsync()) return this.findColumnCompose(info, column, defValue, node); return CompletableFuture.supplyAsync(() -> this.findColumnCompose(info, column, defValue, node).join(), getExecutor()); } @@ -2275,12 +2567,16 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } else { StringBuilder union = new StringBuilder(); for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } union.append("SELECT ").append(info.getSQLColumn("a", column)).append(" FROM ").append(table).append(" a").append(joinAndWhere); } sql = "SELECT " + info.getSQLColumn("a", column) + " FROM (" + (union) + ") a"; } - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " find sql=" + sql); + } return findColumnDB(info, sql, false, column, defValue); } @@ -2304,7 +2600,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { boolean rs = cache.exists(pk); - if (rs || cache.isFullLoaded()) return rs; + if (rs || cache.isFullLoaded()) { + return rs; + } } return existsCompose(info, pk).join(); } @@ -2315,15 +2613,21 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { boolean rs = cache.exists(pk); - if (rs || cache.isFullLoaded()) return CompletableFuture.completedFuture(rs); + if (rs || cache.isFullLoaded()) { + return CompletableFuture.completedFuture(rs); + } + } + if (isAsync()) { + return existsCompose(info, pk); } - if (isAsync()) return existsCompose(info, pk); return CompletableFuture.supplyAsync(() -> existsCompose(info, pk).join(), getExecutor()); } protected CompletableFuture existsCompose(final EntityInfo info, Serializable pk) { final String sql = "SELECT COUNT(*) FROM " + info.getTable(pk) + " WHERE " + info.getPrimarySQLColumn() + "=" + info.formatSQLValue(info.getPrimarySQLColumn(), pk, sqlFormatter); - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " exists sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " exists sql=" + sql); + } return existsDB(info, sql, true); } @@ -2333,7 +2637,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { boolean rs = cache.exists(node); - if (rs || cache.isFullLoaded()) return rs; + if (rs || cache.isFullLoaded()) { + return rs; + } } return this.existsCompose(info, node).join(); } @@ -2344,9 +2650,13 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (cache != null) { boolean rs = cache.exists(node); - if (rs || cache.isFullLoaded()) return CompletableFuture.completedFuture(rs); + if (rs || cache.isFullLoaded()) { + return CompletableFuture.completedFuture(rs); + } + } + if (isAsync()) { + return this.existsCompose(info, node); } - if (isAsync()) return this.existsCompose(info, node); return CompletableFuture.supplyAsync(() -> this.existsCompose(info, node).join(), getExecutor()); } @@ -2362,12 +2672,16 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi } else { StringBuilder union = new StringBuilder(); for (String table : tables) { - if (!union.isEmpty()) union.append(" UNION ALL "); + if (!union.isEmpty()) { + union.append(" UNION ALL "); + } union.append("SELECT ").append(info.getPrimarySQLColumn("a")).append(" FROM ").append(table).append(" a").append(joinAndWhere); } sql = "SELECT COUNT(" + info.getPrimarySQLColumn("a") + ") FROM (" + (union) + ") a"; } - if (info.isLoggable(logger, Level.FINEST, sql)) logger.finest(info.getType().getSimpleName() + " exists sql=" + sql); + if (info.isLoggable(logger, Level.FINEST, sql)) { + logger.finest(info.getType().getSimpleName() + " exists sql=" + sql); + } return existsDB(info, sql, false); } @@ -2385,7 +2699,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public Set queryColumnSet(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { final Set list = querySet(clazz, SelectColumn.includes(selectedColumn), flipper, node); final Set rs = new LinkedHashSet<>(); - if (list.isEmpty()) return rs; + if (list.isEmpty()) { + return rs; + } final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); for (T t : list) { @@ -2398,7 +2714,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public CompletableFuture> queryColumnSetAsync(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { return querySetAsync(clazz, SelectColumn.includes(selectedColumn), flipper, node).thenApply((Set list) -> { final Set rs = new LinkedHashSet<>(); - if (list.isEmpty()) return rs; + if (list.isEmpty()) { + return rs; + } final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); for (T t : list) { @@ -2412,7 +2730,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public List queryColumnList(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { final List list = queryList(clazz, SelectColumn.includes(selectedColumn), flipper, node); final List rs = new ArrayList<>(); - if (list.isEmpty()) return rs; + if (list.isEmpty()) { + return rs; + } final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); for (T t : list) { @@ -2425,7 +2745,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public CompletableFuture> queryColumnListAsync(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { return queryListAsync(clazz, SelectColumn.includes(selectedColumn), flipper, node).thenApply((List list) -> { final List rs = new ArrayList<>(); - if (list.isEmpty()) return rs; + if (list.isEmpty()) { + return rs; + } final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); for (T t : list) { @@ -2439,7 +2761,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public Sheet queryColumnSheet(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { Sheet sheet = querySheet(clazz, SelectColumn.includes(selectedColumn), flipper, node); final Sheet rs = new Sheet<>(); - if (sheet.isEmpty()) return rs; + if (sheet.isEmpty()) { + return rs; + } rs.setTotal(sheet.getTotal()); final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); @@ -2455,7 +2779,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi public CompletableFuture> queryColumnSheetAsync(final String selectedColumn, final Class clazz, final Flipper flipper, final FilterNode node) { return querySheetAsync(clazz, SelectColumn.includes(selectedColumn), flipper, node).thenApply((Sheet sheet) -> { final Sheet rs = new Sheet<>(); - if (sheet.isEmpty()) return rs; + if (sheet.isEmpty()) { + return rs; + } rs.setTotal(sheet.getTotal()); final EntityInfo info = loadEntityInfo(clazz); final Attribute selected = (Attribute) info.getAttribute(selectedColumn); @@ -2482,14 +2808,18 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi */ @Override public Map queryMap(final Class clazz, final SelectColumn selects, final Stream keyStream) { - if (keyStream == null) return new LinkedHashMap<>(); + if (keyStream == null) { + return new LinkedHashMap<>(); + } final EntityInfo info = loadEntityInfo(clazz); final ArrayList ids = new ArrayList<>(); keyStream.forEach(k -> ids.add(k)); final Attribute primary = info.getPrimary(); List rs = queryList(clazz, FilterNode.create(primary.field(), ids)); Map map = new LinkedHashMap<>(); - if (rs.isEmpty()) return new LinkedHashMap<>(); + if (rs.isEmpty()) { + return new LinkedHashMap<>(); + } for (T item : rs) { map.put((K) primary.get(item), item); } @@ -2498,14 +2828,18 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture> queryMapAsync(final Class clazz, final SelectColumn selects, final Stream keyStream) { - if (keyStream == null) return CompletableFuture.completedFuture(new LinkedHashMap<>()); + if (keyStream == null) { + return CompletableFuture.completedFuture(new LinkedHashMap<>()); + } final EntityInfo info = loadEntityInfo(clazz); final ArrayList pks = new ArrayList<>(); keyStream.forEach(k -> pks.add(k)); final Attribute primary = info.getPrimary(); return queryListAsync(clazz, FilterNode.create(primary.field(), pks)).thenApply((List rs) -> { Map map = new LinkedHashMap<>(); - if (rs.isEmpty()) return new LinkedHashMap<>(); + if (rs.isEmpty()) { + return new LinkedHashMap<>(); + } for (T item : rs) { map.put((K) primary.get(item), item); } @@ -2531,7 +2865,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityInfo info = loadEntityInfo(clazz); final Attribute primary = info.getPrimary(); Map map = new LinkedHashMap<>(); - if (rs.isEmpty()) return new LinkedHashMap<>(); + if (rs.isEmpty()) { + return new LinkedHashMap<>(); + } for (T item : rs) { map.put((K) primary.get(item), item); } @@ -2544,7 +2880,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityInfo info = loadEntityInfo(clazz); final Attribute primary = info.getPrimary(); Map map = new LinkedHashMap<>(); - if (rs.isEmpty()) return new LinkedHashMap<>(); + if (rs.isEmpty()) { + return new LinkedHashMap<>(); + } for (T item : rs) { map.put((K) primary.get(item), item); } @@ -2579,7 +2917,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi @Override public CompletableFuture> querySheetAsync(final Class clazz, final SelectColumn selects, final Flipper flipper, final FilterNode node) { - if (isAsync()) return querySheetCompose(true, true, false, clazz, selects, flipper, node); + if (isAsync()) { + return querySheetCompose(true, true, false, clazz, selects, flipper, node); + } return CompletableFuture.supplyAsync(() -> querySheetCompose(true, true, false, clazz, selects, flipper, node).join(), getExecutor()); } @@ -2588,7 +2928,9 @@ public abstract class DataSqlSource extends AbstractDataSource implements Functi final EntityCache cache = info.getCache(); if (readcache && cache != null && cache.isFullLoaded()) { if (node == null || isCacheUseable(node, this)) { - if (info.isLoggable(logger, Level.FINEST, " cache query predicate = ")) logger.finest(clazz.getSimpleName() + " cache query predicate = " + (node == null ? null : createPredicate(node, cache))); + if (info.isLoggable(logger, Level.FINEST, " cache query predicate = ")) { + logger.finest(clazz.getSimpleName() + " cache query predicate = " + (node == null ? null : createPredicate(node, cache))); + } return CompletableFuture.completedFuture(cache.querySheet(needtotal, distinct, selects, flipper, node)); } } diff --git a/src/main/java/org/redkale/source/EntityCache.java b/src/main/java/org/redkale/source/EntityCache.java index 9c537cb04..e8f6379dc 100644 --- a/src/main/java/org/redkale/source/EntityCache.java +++ b/src/main/java/org/redkale/source/EntityCache.java @@ -91,10 +91,14 @@ public final class EntityCache { this.primary = info.primary; org.redkale.persistence.VirtualEntity ve = info.getType().getAnnotation(org.redkale.persistence.VirtualEntity.class); boolean direct = cacheDirect; - if (!direct) direct = ve != null && ve.direct(); + if (!direct) { + direct = ve != null && ve.direct(); + } { //兼容废弃类 org.redkale.source.VirtualEntity ve2 = info.getType().getAnnotation(org.redkale.source.VirtualEntity.class); - if (!direct && ve2 != null) direct = ve2.direct(); + if (!direct && ve2 != null) { + direct = ve2.direct(); + } } this.needcopy = !direct; this.newReproduce = Reproduce.create(type, type, (m) -> { @@ -108,8 +112,12 @@ public final class EntityCache { this.chgReproduce = Reproduce.create(type, type, (m) -> { try { java.lang.reflect.Field field = type.getDeclaredField(m); - if (field.getAnnotation(Transient.class) != null) return false; - if (field.getAnnotation(javax.persistence.Transient.class) != null) return false; + if (field.getAnnotation(Transient.class) != null) { + return false; + } + if (field.getAnnotation(javax.persistence.Transient.class) != null) { + return false; + } Column column = field.getAnnotation(Column.class); return (column == null || column.updatable()); } catch (Exception e) { @@ -119,8 +127,12 @@ public final class EntityCache { } public CompletableFuture> fullLoadAsync() { - if (this.fullloaded) return this.loadFuture; - if (loading.getAndSet(true)) return this.loadFuture; + if (this.fullloaded) { + return this.loadFuture; + } + if (loading.getAndSet(true)) { + return this.loadFuture; + } if (info.fullloader == null) { this.list = new ConcurrentLinkedQueue(); this.map = new ConcurrentHashMap(); @@ -200,13 +212,17 @@ public final class EntityCache { } public T find(Serializable pk) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = map.get(pk); return rs == null ? null : (needcopy ? newReproduce.apply(this.creator.create(), rs) : rs); } public T[] finds(Serializable... pks) { - if (pks == null || pks.length == 0) return arrayer.apply(0); + if (pks == null || pks.length == 0) { + return arrayer.apply(0); + } if (pks.length == 1) { Class t = pks[0].getClass(); if (t == int[].class) { @@ -236,19 +252,29 @@ public final class EntityCache { } public T find(final SelectColumn selects, final Serializable pk) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = map.get(pk); - if (rs == null) return null; - if (selects == null) return (needcopy ? newReproduce.apply(this.creator.create(), rs) : rs); + if (rs == null) { + return null; + } + if (selects == null) { + return (needcopy ? newReproduce.apply(this.creator.create(), rs) : rs); + } T t = this.creator.create(); for (Attribute attr : this.info.attributes) { - if (selects.test(attr.field())) attr.set(t, attr.get(rs)); + if (selects.test(attr.field())) { + attr.set(t, attr.get(rs)); + } } return t; } public T[] finds(final SelectColumn selects, Serializable... pks) { - if (pks == null || pks.length == 0) return arrayer.apply(0); + if (pks == null || pks.length == 0) { + return arrayer.apply(0); + } final Creator ctr = this.creator; final Attribute[] attrs = this.info.attributes; int size = pks.length; @@ -265,13 +291,19 @@ public final class EntityCache { for (int i = 0; i < array.length; i++) { Serializable id = ids1 == null ? (ids2 == null ? pks[i] : ids2[i]) : ids1[i]; T rs = map.get(id); - if (rs == null) continue; + if (rs == null) { + continue; + } if (selects == null) { - if (needcopy) rs = newReproduce.apply(ctr.create(), rs); + if (needcopy) { + rs = newReproduce.apply(ctr.create(), rs); + } } else { T t = ctr.create(); for (Attribute attr : attrs) { - if (selects.test(attr.field())) attr.set(t, attr.get(rs)); + if (selects.test(attr.field())) { + attr.set(t, attr.get(rs)); + } } rs = t; } @@ -283,22 +315,34 @@ public final class EntityCache { public T find(final SelectColumn selects, FilterNode node) { final Predicate filter = node == null ? null : node.createPredicate(this); Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } Optional opt = stream.findFirst(); - if (!opt.isPresent()) return null; - if (selects == null) return (needcopy ? newReproduce.apply(this.creator.create(), opt.get()) : opt.get()); + if (!opt.isPresent()) { + return null; + } + if (selects == null) { + return (needcopy ? newReproduce.apply(this.creator.create(), opt.get()) : opt.get()); + } T rs = opt.get(); T t = this.creator.create(); for (Attribute attr : this.info.attributes) { - if (selects.test(attr.field())) attr.set(t, attr.get(rs)); + if (selects.test(attr.field())) { + attr.set(t, attr.get(rs)); + } } return t; } public Serializable findColumn(final String column, final Serializable defValue, final Serializable pk) { - if (pk == null) return defValue; + if (pk == null) { + return defValue; + } T rs = map.get(pk); - if (rs == null) return defValue; + if (rs == null) { + return defValue; + } for (Attribute attr : this.info.attributes) { if (column.equals(attr.field())) { Serializable val = (Serializable) attr.get(rs); @@ -311,9 +355,13 @@ public final class EntityCache { public Serializable findColumn(final String column, final Serializable defValue, FilterNode node) { final Predicate filter = node == null ? null : node.createPredicate(this); Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } Optional opt = stream.findFirst(); - if (!opt.isPresent()) return defValue; + if (!opt.isPresent()) { + return defValue; + } T rs = opt.get(); for (Attribute attr : this.info.attributes) { if (column.equals(attr.field())) { @@ -325,7 +373,9 @@ public final class EntityCache { } public boolean exists(Serializable pk) { - if (pk == null) return false; + if (pk == null) { + return false; + } final Class atype = this.primary.type(); if (pk.getClass() != atype && pk instanceof Number) { if (atype == int.class || atype == Integer.class) { @@ -356,7 +406,9 @@ public final class EntityCache { public boolean exists(FilterNode node) { final Predicate filter = node == null ? null : node.createPredicate(this); Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } return stream.findFirst().isPresent(); } @@ -369,7 +421,9 @@ public final class EntityCache { final Predicate filter = node == null ? null : node.createPredicate(this); final Attribute funcAttr = funcColumn == null ? null : info.getAttribute(funcColumn); Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } Collector collector = null; final Class valtype = funcAttr == null ? null : funcAttr.type(); if (func != null) { @@ -406,7 +460,9 @@ public final class EntityCache { if (func == MAX || func == MIN) { Map rs2 = new LinkedHashMap(); rs.forEach((x, y) -> { - if (((Optional) y).isPresent()) rs2.put(x, funcAttr.get((T) ((Optional) y).get())); + if (((Optional) y).isPresent()) { + rs2.put(x, funcAttr.get((T) ((Optional) y).get())); + } }); rs = rs2; } else if (func == DISTINCTCOUNT) { @@ -420,7 +476,9 @@ public final class EntityCache { public Map queryColumnMap(final ColumnNode[] funcNodes, final String[] groupByColumns, FilterNode node) { final Predicate filter = node == null ? null : node.createPredicate(this); Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } final Attribute[] attrs = new Attribute[groupByColumns.length]; for (int i = 0; i < groupByColumns.length; i++) { attrs[i] = info.getAttribute(groupByColumns[i]); @@ -434,7 +492,9 @@ public final class EntityCache { sb.append((char) 20).append(vals[i]); } final String key = sb.toString(); - if (!valmap.containsKey(key)) valmap.put(key, vals); + if (!valmap.containsKey(key)) { + valmap.put(key, vals); + } return valmap.get(key); }; Map> listmap = stream.collect(Collectors.groupingBy(func)); @@ -444,7 +504,9 @@ public final class EntityCache { } private Number[] queryColumnNumbers(final List list, final ColumnNode[] funcNodes) { - if (true) throw new UnsupportedOperationException("Not supported yet."); + if (true) { + throw new UnsupportedOperationException("Not supported yet."); + } Number[] rs = new Number[funcNodes.length]; for (int i = 0; i < rs.length; i++) { rs[i] = queryColumnNumber(list, funcNodes[i]); @@ -484,7 +546,9 @@ public final class EntityCache { private Number getNumberResult(final Collection entityList, final FilterFunc func, final Number defResult, final Class attrType, final Function attrFunc, final FilterNode node) { final Predicate filter = node == null ? null : node.createPredicate(this); Stream stream = entityList.stream(); - if (filter != null) stream = stream.filter(filter); + if (filter != null) { + stream = stream.filter(filter); + } switch (func) { case AVG: if (attrType == int.class || attrType == Integer.class || attrType == AtomicInteger.class) { @@ -575,7 +639,9 @@ public final class EntityCache { } protected Stream distinctStream(Stream stream, final List> keyattrs) { - if (keyattrs == null) return stream; + if (keyattrs == null) { + return stream; + } final Set keys = new HashSet<>(); Predicate filter = t -> { StringBuilder sb = new StringBuilder(); @@ -583,7 +649,9 @@ public final class EntityCache { sb.append(attr.get(t)); } String key = sb.toString(); - if (keys.contains(key)) return false; + if (keys.contains(key)) { + return false; + } keys.add(key); return true; }; @@ -598,23 +666,41 @@ public final class EntityCache { if (distinct) { final List> attrs = new ArrayList<>(); info.forEachAttribute((k, v) -> { - if (selects == null || selects.test(k)) attrs.add(v); + if (selects == null || selects.test(k)) { + attrs.add(v); + } }); keyattrs = attrs; } if (needtotal) { Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); - if (distinct) stream = distinctStream(stream, keyattrs); + if (filter != null) { + stream = stream.filter(filter); + } + if (distinct) { + stream = distinctStream(stream, keyattrs); + } total = stream.count(); } - if (needtotal && total == 0) return new Sheet<>(0, new ArrayList()); + if (needtotal && total == 0) { + return new Sheet<>(0, new ArrayList()); + } Stream stream = this.list.stream(); - if (filter != null) stream = stream.filter(filter); - if (distinct) stream = distinctStream(stream, keyattrs); - if (comparator != null) stream = stream.sorted(comparator); - if (flipper != null && flipper.getOffset() > 0) stream = stream.skip(flipper.getOffset()); - if (flipper != null && flipper.getLimit() > 0) stream = stream.limit(flipper.getLimit()); + if (filter != null) { + stream = stream.filter(filter); + } + if (distinct) { + stream = distinctStream(stream, keyattrs); + } + if (comparator != null) { + stream = stream.sorted(comparator); + } + if (flipper != null && flipper.getOffset() > 0) { + stream = stream.skip(flipper.getOffset()); + } + if (flipper != null && flipper.getLimit() > 0) { + stream = stream.limit(flipper.getLimit()); + } final List rs = new ArrayList<>(); if (selects == null) { Consumer action = x -> rs.add(needcopy ? newReproduce.apply(creator.create(), x) : x); @@ -626,7 +712,9 @@ public final class EntityCache { } else { final List> attrs = new ArrayList<>(); info.forEachAttribute((k, v) -> { - if (selects.test(k)) attrs.add(v); + if (selects.test(k)) { + attrs.add(v); + } }); Consumer action = x -> { final T item = creator.create(); @@ -641,12 +729,16 @@ public final class EntityCache { stream.forEach(action); } } - if (!needtotal) total = rs.size(); + if (!needtotal) { + total = rs.size(); + } return new Sheet<>(total, rs); } public int insert(T entity) { - if (entity == null) return 0; + if (entity == null) { + return 0; + } final T rs = newReproduce.apply(this.creator.create(), entity); //确保同一主键值的map与list中的对象必须共用。 T old = this.map.putIfAbsent(this.primary.get(rs), rs); if (old == null) { @@ -659,20 +751,32 @@ public final class EntityCache { } public int delete(final Serializable pk) { - if (pk == null) return 0; + if (pk == null) { + return 0; + } final T rs = this.map.remove(pk); - if (rs == null) return 0; + if (rs == null) { + return 0; + } this.list.remove(rs); return 1; } public Serializable[] delete(final Flipper flipper, final FilterNode node) { - if (node == null || this.list.isEmpty()) return new Serializable[0]; + if (node == null || this.list.isEmpty()) { + return new Serializable[0]; + } final Comparator comparator = createComparator(flipper); Stream stream = this.list.stream().filter(node.createPredicate(this)); - if (comparator != null) stream = stream.sorted(comparator); - if (flipper != null && flipper.getOffset() > 0) stream = stream.skip(flipper.getOffset()); - if (flipper != null && flipper.getLimit() > 0) stream = stream.limit(flipper.getLimit()); + if (comparator != null) { + stream = stream.sorted(comparator); + } + if (flipper != null && flipper.getOffset() > 0) { + stream = stream.skip(flipper.getOffset()); + } + if (flipper != null && flipper.getLimit() > 0) { + stream = stream.limit(flipper.getLimit()); + } Object[] rms = stream.toArray(); Serializable[] ids = new Serializable[rms.length]; int i = -1; @@ -690,9 +794,13 @@ public final class EntityCache { } public int update(final T entity) { - if (entity == null) return 0; + if (entity == null) { + return 0; + } T rs = this.map.get(this.primary.get(entity)); - if (rs == null) return 0; + if (rs == null) { + return 0; + } synchronized (rs) { this.chgReproduce.apply(rs, entity); } @@ -700,9 +808,13 @@ public final class EntityCache { } public T update(final T entity, Collection> attrs) { - if (entity == null) return entity; + if (entity == null) { + return entity; + } T rs = this.map.get(this.primary.get(entity)); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { for (Attribute attr : attrs) { attr.set(rs, attr.get(entity)); @@ -712,7 +824,9 @@ public final class EntityCache { } public T[] update(final T entity, final Collection> attrs, final FilterNode node) { - if (entity == null || node == null) return (T[]) Array.newInstance(type, 0); + if (entity == null || node == null) { + return (T[]) Array.newInstance(type, 0); + } T[] rms = this.list.stream().filter(node.createPredicate(this)).toArray(len -> (T[]) Array.newInstance(type, len)); for (T rs : rms) { synchronized (rs) { @@ -725,14 +839,20 @@ public final class EntityCache { } public T update(final Serializable pk, Attribute attr, final V fieldValue) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = this.map.get(pk); - if (rs != null) attr.set(rs, fieldValue); + if (rs != null) { + attr.set(rs, fieldValue); + } return rs; } public T[] update(Attribute attr, final V fieldValue, final FilterNode node) { - if (attr == null || node == null) return (T[]) Array.newInstance(type, 0); + if (attr == null || node == null) { + return (T[]) Array.newInstance(type, 0); + } T[] rms = this.list.stream().filter(node.createPredicate(this)).toArray(len -> (T[]) Array.newInstance(type, len)); for (T rs : rms) { attr.set(rs, fieldValue); @@ -741,9 +861,13 @@ public final class EntityCache { } public T updateColumn(final Serializable pk, List> attrs, final List values) { - if (pk == null || attrs == null || attrs.isEmpty()) return null; + if (pk == null || attrs == null || attrs.isEmpty()) { + return null; + } T rs = this.map.get(pk); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { for (int i = 0; i < attrs.size(); i++) { ColumnValue cv = values.get(i); @@ -754,11 +878,17 @@ public final class EntityCache { } public T[] updateColumn(final FilterNode node, final Flipper flipper, List> attrs, final List values) { - if (attrs == null || attrs.isEmpty() || node == null) return (T[]) Array.newInstance(type, 0); + if (attrs == null || attrs.isEmpty() || node == null) { + return (T[]) Array.newInstance(type, 0); + } Stream stream = this.list.stream(); final Comparator comparator = createComparator(flipper); - if (comparator != null) stream = stream.sorted(comparator); - if (flipper != null && flipper.getLimit() > 0) stream = stream.limit(flipper.getLimit()); + if (comparator != null) { + stream = stream.sorted(comparator); + } + if (flipper != null && flipper.getLimit() > 0) { + stream = stream.limit(flipper.getLimit()); + } T[] rms = stream.filter(node.createPredicate(this)).toArray(len -> (T[]) Array.newInstance(type, len)); for (T rs : rms) { synchronized (rs) { @@ -772,36 +902,52 @@ public final class EntityCache { } public T updateColumnOr(final Serializable pk, Attribute attr, final long orvalue) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = this.map.get(pk); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { return updateColumn(attr, rs, ColumnExpress.ORR, orvalue); } } public T updateColumnAnd(final Serializable pk, Attribute attr, final long andvalue) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = this.map.get(pk); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { return updateColumn(attr, rs, ColumnExpress.AND, andvalue); } } public T updateColumnIncrement(final Serializable pk, Attribute attr, final long incvalue) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = this.map.get(pk); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { return updateColumn(attr, rs, ColumnExpress.INC, incvalue); } } public T updateColumnDecrement(final Serializable pk, Attribute attr, final long incvalue) { - if (pk == null) return null; + if (pk == null) { + return null; + } T rs = this.map.get(pk); - if (rs == null) return rs; + if (rs == null) { + return rs; + } synchronized (rs) { return updateColumn(attr, rs, ColumnExpress.DEC, incvalue); } @@ -822,9 +968,13 @@ public final class EntityCache { numb = getValue((Number) attr.get(entity), express, val); break; case MOV: - if (val instanceof ColumnNodeValue) val = updateColumnNodeValue(attr, entity, (ColumnNodeValue) val); + if (val instanceof ColumnNodeValue) { + val = updateColumnNodeValue(attr, entity, (ColumnNodeValue) val); + } newval = val; - if (val instanceof Number) numb = (Number) val; + if (val instanceof Number) { + numb = (Number) val; + } break; } if (numb != null) { @@ -868,7 +1018,9 @@ public final class EntityCache { Serializable left = node.getLeft(); if (left instanceof CharSequence) { left = info.getUpdateAttribute(left.toString()).get(entity); - if (node.getExpress() == ColumnExpress.MOV) return left; + if (node.getExpress() == ColumnExpress.MOV) { + return left; + } } else if (left instanceof ColumnNodeValue) { left = updateColumnNodeValue(attr, entity, (ColumnNodeValue) left); } @@ -954,12 +1106,18 @@ public final class EntityCache { //------------------------------------------------------------------------------------------------------------------------------- protected Comparator createComparator(Flipper flipper) { - if (flipper == null || flipper.getSort() == null || flipper.getSort().isEmpty() || flipper.getSort().indexOf(';') >= 0 || flipper.getSort().indexOf('\n') >= 0) return null; + if (flipper == null || flipper.getSort() == null || flipper.getSort().isEmpty() || flipper.getSort().indexOf(';') >= 0 || flipper.getSort().indexOf('\n') >= 0) { + return null; + } final String sort = flipper.getSort(); Comparator comparator = this.sortComparators.get(sort); - if (comparator != null) return comparator; + if (comparator != null) { + return comparator; + } for (String item : sort.split(",")) { - if (item.trim().isEmpty()) continue; + if (item.trim().isEmpty()) { + continue; + } String[] sub = item.trim().split("\\s+"); int pos = sub[0].indexOf('('); Attribute attr; @@ -1024,12 +1182,20 @@ public final class EntityCache { @Override public boolean equals(Object obj) { - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } final UniqueSequence other = (UniqueSequence) obj; - if (value.length != other.value.length) return false; + if (value.length != other.value.length) { + return false; + } for (int i = 0; i < value.length; i++) { - if (!value[i].equals(other.value[i])) return false; + if (!value[i].equals(other.value[i])) { + return false; + } } return true; } @@ -1055,11 +1221,19 @@ public final class EntityCache { @Override public boolean test(FilterNode node) { - if (node == null || node.isOr()) return false; - if (!attribute.field().equals(node.column)) return false; - if (node.nodes == null) return true; + if (node == null || node.isOr()) { + return false; + } + if (!attribute.field().equals(node.column)) { + return false; + } + if (node.nodes == null) { + return true; + } for (FilterNode n : node.nodes) { - if (!test(n)) return false; + if (!test(n)) { + return false; + } } return true; } diff --git a/src/main/java/org/redkale/source/EntityInfo.java b/src/main/java/org/redkale/source/EntityInfo.java index d85c92a71..534d7d39f 100644 --- a/src/main/java/org/redkale/source/EntityInfo.java +++ b/src/main/java/org/redkale/source/EntityInfo.java @@ -187,7 +187,9 @@ public final class EntityInfo { static EntityInfo load(Class clazz, final boolean cacheForbidden, final Properties conf, DataSource source, BiFunction> fullloader) { EntityInfo rs = entityInfos.get(clazz); - if (rs != null && (rs.cache == null || rs.cache.isFullLoaded())) return rs; + if (rs != null && (rs.cache == null || rs.cache.isFullLoaded())) { + return rs; + } synchronized (entityInfos) { rs = entityInfos.get(clazz); if (rs == null) { @@ -195,7 +197,9 @@ public final class EntityInfo { entityInfos.put(clazz, rs); } if (rs.cache != null && !rs.isCacheFullLoaded()) { - if (fullloader == null) throw new IllegalArgumentException(clazz.getName() + " auto loader is illegal"); + if (fullloader == null) { + throw new IllegalArgumentException(clazz.getName() + " auto loader is illegal"); + } rs.cache.fullLoadAsync(); } return rs; @@ -317,7 +321,9 @@ public final class EntityInfo { DistributeTableStrategy dts = null; try { dts = (dt == null) ? null : dt.strategy().getDeclaredConstructor().newInstance(); - if (dts != null) RedkaleClassLoader.putReflectionDeclaredConstructors(dt.strategy(), dt.strategy().getName()); + if (dts != null) { + RedkaleClassLoader.putReflectionDeclaredConstructors(dt.strategy(), dt.strategy().getName()); + } } catch (Exception e) { logger.log(Level.SEVERE, type + " init DistributeTableStrategy error", e); } @@ -359,16 +365,28 @@ public final class EntityInfo { ddlList.add(ddl); RedkaleClassLoader.putReflectionDeclaredFields(cltmp.getName()); for (Field field : cltmp.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) continue; - if (Modifier.isFinal(field.getModifiers())) continue; - if (field.getAnnotation(Transient.class) != null) continue; - if (field.getAnnotation(javax.persistence.Transient.class) != null) continue; - if (fields.contains(field.getName())) continue; + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + if (Modifier.isFinal(field.getModifiers())) { + continue; + } + if (field.getAnnotation(Transient.class) != null) { + continue; + } + if (field.getAnnotation(javax.persistence.Transient.class) != null) { + continue; + } + if (fields.contains(field.getName())) { + continue; + } final String fieldname = field.getName(); final Column col = field.getAnnotation(Column.class); final String sqlfield = col == null || col.name().isEmpty() ? fieldname : col.name(); if (!fieldname.equals(sqlfield)) { - if (aliasmap0 == null) aliasmap0 = new HashMap<>(); + if (aliasmap0 == null) { + aliasmap0 = new HashMap<>(); + } aliasmap0.put(fieldname, sqlfield); } Attribute attr; @@ -405,22 +423,34 @@ public final class EntityInfo { attributeMap.put(fieldname, attr); } } while ((cltmp = cltmp.getSuperclass()) != Object.class); - if (idAttr0 == null) throw new SourceException(type.getName() + " have no primary column by @org.redkale.persistence.Id"); + if (idAttr0 == null) { + throw new SourceException(type.getName() + " have no primary column by @org.redkale.persistence.Id"); + } cltmp = type; JsonConvert convert = DEFAULT_JSON_CONVERT; do { for (Method method : cltmp.getDeclaredMethods()) { - if (method.getAnnotation(SourceConvert.class) == null) continue; - if (!Modifier.isStatic(method.getModifiers())) throw new SourceException("@SourceConvert method(" + method + ") must be static"); - if (method.getReturnType() != JsonConvert.class) throw new SourceException("@SourceConvert method(" + method + ") must be return JsonConvert.class"); - if (method.getParameterCount() > 0) throw new SourceException("@SourceConvert method(" + method + ") must be 0 parameter"); + if (method.getAnnotation(SourceConvert.class) == null) { + continue; + } + if (!Modifier.isStatic(method.getModifiers())) { + throw new SourceException("@SourceConvert method(" + method + ") must be static"); + } + if (method.getReturnType() != JsonConvert.class) { + throw new SourceException("@SourceConvert method(" + method + ") must be return JsonConvert.class"); + } + if (method.getParameterCount() > 0) { + throw new SourceException("@SourceConvert method(" + method + ") must be 0 parameter"); + } try { method.setAccessible(true); convert = (JsonConvert) method.invoke(null); } catch (Exception e) { throw new SourceException(method + " invoke error", e); } - if (convert != null) break; + if (convert != null) { + break; + } } } while ((cltmp = cltmp.getSuperclass()) != Object.class); this.jsonConvert = convert == null ? DEFAULT_JSON_CONVERT : convert; @@ -476,7 +506,9 @@ public final class EntityInfo { StringBuilder querydb = new StringBuilder(); int index = 0; for (String col : querycols) { - if (index > 0) querydb.append(','); + if (index > 0) { + querydb.append(','); + } querydb.append(col); index++; } @@ -486,7 +518,9 @@ public final class EntityInfo { StringBuilder insertsbnames = new StringBuilder(); index = 0; for (String col : insertcols) { - if (index > 0) insertsb.append(','); + if (index > 0) { + insertsb.append(','); + } insertsb.append(col); if (index > 0) { insertsbquestion.append(','); @@ -712,7 +746,9 @@ public final class EntityInfo { * @return String */ public String getFindQuestionPrepareSQL(Serializable pk) { - if (this.tableStrategy == null) return findQuestionPrepareSQL; + if (this.tableStrategy == null) { + return findQuestionPrepareSQL; + } return findQuestionPrepareSQL.replace("${newtable}", getTable(pk)); } @@ -734,7 +770,9 @@ public final class EntityInfo { * @return String */ public String getFindDollarPrepareSQL(Serializable pk) { - if (this.tableStrategy == null) return findDollarPrepareSQL; + if (this.tableStrategy == null) { + return findDollarPrepareSQL; + } return findDollarPrepareSQL.replace("${newtable}", getTable(pk)); } @@ -746,7 +784,9 @@ public final class EntityInfo { * @return String */ public String getFindNamesPrepareSQL(Serializable pk) { - if (this.tableStrategy == null) return findNamesPrepareSQL; + if (this.tableStrategy == null) { + return findNamesPrepareSQL; + } return findNamesPrepareSQL.replace("${newtable}", getTable(pk)); } @@ -758,7 +798,9 @@ public final class EntityInfo { * @return String */ public String getInsertQuestionPrepareSQL(T bean) { - if (this.tableStrategy == null) return insertQuestionPrepareSQL; + if (this.tableStrategy == null) { + return insertQuestionPrepareSQL; + } return insertQuestionPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -770,7 +812,9 @@ public final class EntityInfo { * @return String */ public String getInsertDollarPrepareSQL(T bean) { - if (this.tableStrategy == null) return insertDollarPrepareSQL; + if (this.tableStrategy == null) { + return insertDollarPrepareSQL; + } return insertDollarPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -782,7 +826,9 @@ public final class EntityInfo { * @return String */ public String getInsertNamesPrepareSQL(T bean) { - if (this.tableStrategy == null) return insertNamesPrepareSQL; + if (this.tableStrategy == null) { + return insertNamesPrepareSQL; + } return insertNamesPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -794,7 +840,9 @@ public final class EntityInfo { * @return String */ public String getUpdateQuestionPrepareSQL(T bean) { - if (this.tableStrategy == null) return updateQuestionPrepareSQL; + if (this.tableStrategy == null) { + return updateQuestionPrepareSQL; + } return updateQuestionPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -806,7 +854,9 @@ public final class EntityInfo { * @return String */ public String getUpdateDollarPrepareSQL(T bean) { - if (this.tableStrategy == null) return updateDollarPrepareSQL; + if (this.tableStrategy == null) { + return updateDollarPrepareSQL; + } return updateDollarPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -818,9 +868,15 @@ public final class EntityInfo { * @return String */ public String getUpdateQuestionPrepareCaseSQL(T[] beans) { - if (beans == null || beans.length < 2) return null; - if (this.updateQuestionPrepareCaseSQLs == null) return null; - if (this.updateQuestionPrepareCaseSQLs.length <= beans.length) return null; + if (beans == null || beans.length < 2) { + return null; + } + if (this.updateQuestionPrepareCaseSQLs == null) { + return null; + } + if (this.updateQuestionPrepareCaseSQLs.length <= beans.length) { + return null; + } return this.updateQuestionPrepareCaseSQLs[beans.length]; } @@ -832,9 +888,15 @@ public final class EntityInfo { * @return String */ public String getUpdateDollarPrepareCaseSQL(T[] beans) { - if (beans == null || beans.length < 2) return null; - if (this.updateDollarPrepareCaseSQLs == null) return null; - if (this.updateDollarPrepareCaseSQLs.length <= beans.length) return null; + if (beans == null || beans.length < 2) { + return null; + } + if (this.updateDollarPrepareCaseSQLs == null) { + return null; + } + if (this.updateDollarPrepareCaseSQLs.length <= beans.length) { + return null; + } return this.updateDollarPrepareCaseSQLs[beans.length]; } @@ -846,7 +908,9 @@ public final class EntityInfo { * @return String */ public String getUpdateNamesPrepareSQL(T bean) { - if (this.tableStrategy == null) return updateNamesPrepareSQL; + if (this.tableStrategy == null) { + return updateNamesPrepareSQL; + } return updateNamesPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -858,7 +922,9 @@ public final class EntityInfo { * @return String */ public String getDeleteQuestionPrepareSQL(T bean) { - if (this.tableStrategy == null) return deleteQuestionPrepareSQL; + if (this.tableStrategy == null) { + return deleteQuestionPrepareSQL; + } return deleteQuestionPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -870,7 +936,9 @@ public final class EntityInfo { * @return String */ public String getDeleteDollarPrepareSQL(T bean) { - if (this.tableStrategy == null) return deleteDollarPrepareSQL; + if (this.tableStrategy == null) { + return deleteDollarPrepareSQL; + } return deleteDollarPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -882,7 +950,9 @@ public final class EntityInfo { * @return String */ public String getDeleteNamesPrepareSQL(T bean) { - if (this.tableStrategy == null) return deleteNamesPrepareSQL; + if (this.tableStrategy == null) { + return deleteNamesPrepareSQL; + } return deleteNamesPrepareSQL.replace("${newtable}", getTable(bean)); } @@ -896,17 +966,27 @@ public final class EntityInfo { */ public CharSequence getQueryColumns(String tabalis, SelectColumn selects) { if (selects == null) { - if (tabalis == null) return querySqlColumnSequence; - if ("a".equals(tabalis)) return querySqlColumnSequenceA; + if (tabalis == null) { + return querySqlColumnSequence; + } + if ("a".equals(tabalis)) { + return querySqlColumnSequenceA; + } return tabalis + "." + Utility.joining(querySqlColumns, "," + tabalis + "."); } StringBuilder sb = new StringBuilder(); for (Attribute attr : this.attributes) { - if (!selects.test(attr.field())) continue; - if (sb.length() > 0) sb.append(','); + if (!selects.test(attr.field())) { + continue; + } + if (sb.length() > 0) { + sb.append(','); + } sb.append(getSQLColumn(tabalis, attr.field())); } - if (sb.length() == 0) sb.append('*'); + if (sb.length() == 0) { + sb.append('*'); + } return sb; } @@ -918,7 +998,9 @@ public final class EntityInfo { StringBuilder sb = new StringBuilder(); String s = tabalis + "."; for (String col : querySqlColumns) { - if (sb.length() > 0) sb.append(','); + if (sb.length() > 0) { + sb.append(','); + } sb.append(s).append(col); } return sb; @@ -926,11 +1008,17 @@ public final class EntityInfo { } else { StringBuilder sb = new StringBuilder(); for (Attribute attr : this.attributes) { - if (!selects.test(attr.field())) continue; - if (sb.length() > 0) sb.append(','); + if (!selects.test(attr.field())) { + continue; + } + if (sb.length() > 0) { + sb.append(','); + } sb.append(getSQLColumn(tabalis, attr.field())); } - if (sb.length() == 0) sb.append('*'); + if (sb.length() == 0) { + sb.append('*'); + } return sb; } } @@ -940,7 +1028,9 @@ public final class EntityInfo { } public Map> getTableMap(Serializable... pks) { - if (tableStrategy == null) return Utility.ofMap(table, Utility.ofList(pks)); + if (tableStrategy == null) { + return Utility.ofMap(table, Utility.ofList(pks)); + } Map> map = new LinkedHashMap<>(); for (Serializable pk : pks) { String t = getTable(pk); @@ -950,7 +1040,9 @@ public final class EntityInfo { } public Map> getTableMap(T... entitys) { - if (tableStrategy == null) return Utility.ofMap(table, Utility.ofList(entitys)); + if (tableStrategy == null) { + return Utility.ofMap(table, Utility.ofList(entitys)); + } Map> map = new LinkedHashMap<>(); for (T entity : entitys) { String t = getTable(entity); @@ -967,7 +1059,9 @@ public final class EntityInfo { * @return String */ public String getTable(Serializable primary) { - if (tableStrategy == null) return table; + if (tableStrategy == null) { + return table; + } String t = tableStrategy.getTable(table, primary); if (t == null || t.isEmpty()) { throw new SourceException(table + " tableStrategy.getTable is empty, primary=" + primary); @@ -983,7 +1077,9 @@ public final class EntityInfo { * @return String */ public String[] getTables(FilterNode node) { - if (tableStrategy == null) return new String[]{table}; + if (tableStrategy == null) { + return new String[]{table}; + } String[] t = tableStrategy.getTables(table, node); if (t == null || t.length < 1) { throw new SourceException(table + " tableStrategy.getTable is empty, filter=" + node); @@ -999,7 +1095,9 @@ public final class EntityInfo { * @return String */ public String getTable(T bean) { - if (tableStrategy == null) return table; + if (tableStrategy == null) { + return table; + } String t = tableStrategy.getTable(table, bean); if (t == null || t.isEmpty()) { throw new SourceException(table + " tableStrategy.getTable is empty, entity=" + bean); @@ -1033,7 +1131,9 @@ public final class EntityInfo { * @return Attribute */ public Attribute getAttribute(String fieldname) { - if (fieldname == null) return null; + if (fieldname == null) { + return null; + } return this.attributeMap.get(fieldname); } @@ -1065,11 +1165,17 @@ public final class EntityInfo { * @return String */ protected String createSQLOrderby(Flipper flipper) { - if (flipper == null || flipper.getSort() == null) return ""; + if (flipper == null || flipper.getSort() == null) { + return ""; + } final String sort = flipper.getSort(); - if (sort.isEmpty() || sort.indexOf(';') >= 0 || sort.indexOf('\n') >= 0) return ""; + if (sort.isEmpty() || sort.indexOf(';') >= 0 || sort.indexOf('\n') >= 0) { + return ""; + } String sql = this.sortOrderbySqls.get(sort); - if (sql != null) return sql; + if (sql != null) { + return sql; + } final StringBuilder sb = new StringBuilder(); sb.append(" ORDER BY "); if (isNoAlias()) { @@ -1077,9 +1183,13 @@ public final class EntityInfo { } else { boolean flag = false; for (String item : sort.split(",")) { - if (item.isEmpty()) continue; + if (item.isEmpty()) { + continue; + } String[] sub = item.split("\\s+"); - if (flag) sb.append(','); + if (flag) { + sb.append(','); + } if (sub.length < 2 || sub[1].equalsIgnoreCase("ASC")) { sb.append(getSQLColumn("a", sub[0])).append(" ASC"); } else { @@ -1116,7 +1226,9 @@ public final class EntityInfo { */ public Object getSQLValue(String fieldname, Serializable fieldvalue) { if (fieldvalue == null && fieldname != null && isNotNullable(fieldname)) { - if (isNotNullJson(getAttribute(fieldname))) return ""; + if (isNotNullJson(getAttribute(fieldname))) { + return ""; + } } return fieldvalue; } @@ -1227,11 +1339,17 @@ public final class EntityInfo { * @return CharSequence */ protected CharSequence formatSQLValue(String sqlColumn, Attribute attr, final ColumnValue cv, BiFunction formatter) { - if (cv == null) return null; + if (cv == null) { + return null; + } Object val = cv.getValue(); //ColumnNodeValue时 cv.getExpress() == ColumnExpress.MOV 只用于updateColumn - if (val instanceof ColumnNodeValue) return formatSQLValue(attr, null, (ColumnNodeValue) val, formatter); - if (val instanceof ColumnFuncNode) return formatSQLValue(attr, null, (ColumnFuncNode) val, formatter); + if (val instanceof ColumnNodeValue) { + return formatSQLValue(attr, null, (ColumnNodeValue) val, formatter); + } + if (val instanceof ColumnFuncNode) { + return formatSQLValue(attr, null, (ColumnFuncNode) val, formatter); + } switch (cv.getExpress()) { case INC: return new StringBuilder().append(sqlColumn).append(" + ").append(val); @@ -1249,7 +1367,9 @@ public final class EntityInfo { return new StringBuilder().append(sqlColumn).append(" | ").append(val); case MOV: CharSequence rs = formatter == null ? formatToString(val) : formatter.apply(this, val); - if (rs == null && isNotNullJson(attr)) rs = ""; + if (rs == null && isNotNullJson(attr)) { + rs = ""; + } return rs; } return formatter == null ? formatToString(val) : formatter.apply(this, val); @@ -1267,7 +1387,9 @@ public final class EntityInfo { Serializable left = node.getLeft(); if (left instanceof CharSequence) { left = this.getSQLColumn(tabalis, left.toString()); - if (node.getExpress() == ColumnExpress.MOV) return (String) left; + if (node.getExpress() == ColumnExpress.MOV) { + return (String) left; + } } else if (left instanceof ColumnNodeValue) { left = "(" + formatSQLValue(attr, tabalis, (ColumnNodeValue) left, formatter) + ")"; } else if (left instanceof ColumnFuncNode) { @@ -1330,7 +1452,9 @@ public final class EntityInfo { } public boolean isNotNullJson(Attribute attr) { - if (attr == null) return false; + if (attr == null) { + return false; + } return notNullColumns.contains(attr.field()) && !Number.class.isAssignableFrom(attr.type()) && !CharSequence.class.isAssignableFrom(attr.type()) @@ -1352,11 +1476,17 @@ public final class EntityInfo { */ public boolean isLoggable(Logger logger, Level l, String str) { boolean rs = logger.isLoggable(l) && l.intValue() >= this.logLevel; - if (this.excludeLogLevels == null || !rs || str == null) return rs; + if (this.excludeLogLevels == null || !rs || str == null) { + return rs; + } String[] keys = this.excludeLogLevels.get(l.intValue()); - if (keys == null) return rs; + if (keys == null) { + return rs; + } for (String key : keys) { - if (str.contains(key)) return false; + if (str.contains(key)) { + return false; + } } return rs; } @@ -1369,7 +1499,9 @@ public final class EntityInfo { * @return String */ private String formatToString(Object value) { - if (value == null) return null; + if (value == null) { + return null; + } if (value instanceof CharSequence) { return new StringBuilder().append('\'').append(value.toString().replace("'", "\\'")).append('\'').toString(); } else if (!(value instanceof Number) && !(value instanceof java.util.Date) @@ -1388,7 +1520,9 @@ public final class EntityInfo { * @return Entity对象 */ protected T getEntityValue(final SelectColumn sels, final DataResultSetRow row) { - if (row.wasNull()) return null; + if (row.wasNull()) { + return null; + } T obj; Attribute[] attrs = this.queryAttributes; if (this.constructorParameters == null) { @@ -1426,7 +1560,9 @@ public final class EntityInfo { * @return Entity对象 */ protected T getEntityValue(final Attribute[] constructorAttrs, final Attribute[] unconstructorAttrs, final DataResultSetRow row) { - if (row.wasNull()) return null; + if (row.wasNull()) { + return null; + } T obj; int index = 0; if (this.constructorParameters == null) { @@ -1435,14 +1571,18 @@ public final class EntityInfo { Object[] cps = new Object[this.constructorParameters.length]; for (int i = 0; i < constructorAttrs.length; i++) { Attribute attr = constructorAttrs[i]; - if (attr == null) continue; + if (attr == null) { + continue; + } cps[i] = getFieldValue(attr, row, ++index); } obj = creator.create(cps); } if (unconstructorAttrs != null) { for (Attribute attr : unconstructorAttrs) { - if (attr == null) continue; + if (attr == null) { + continue; + } attr.set(obj, getFieldValue(attr, row, ++index)); } } diff --git a/src/main/java/org/redkale/source/FilterJoinNode.java b/src/main/java/org/redkale/source/FilterJoinNode.java index 61a577280..9227fbea4 100644 --- a/src/main/java/org/redkale/source/FilterJoinNode.java +++ b/src/main/java/org/redkale/source/FilterJoinNode.java @@ -108,7 +108,9 @@ public class FilterJoinNode extends FilterNode { } if (or == signor || this.column == null) { this.nodes = Utility.append(this.nodes, node); - if (this.column == null) this.or = signor; + if (this.column == null) { + this.or = signor; + } return this; } this.nodes = new FilterNode[]{new FilterJoinNode(this), node}; @@ -130,12 +132,16 @@ public class FilterJoinNode extends FilterNode { @Override protected Predicate createPredicate(final EntityCache cache) { - if (column == null && this.nodes == null) return null; + if (column == null && this.nodes == null) { + return null; + } final EntityCache joinCache = this.joinEntity.getCache(); final AtomicBoolean more = new AtomicBoolean(); Predicate filter = createJoinPredicate(more); Predicate rs = null; - if (filter == null && !more.get()) return rs; + if (filter == null && !more.get()) { + return rs; + } if (filter != null) { final Predicate inner = filter; final String[][] localJoinColumns = new String[joinColumns.length][2]; @@ -176,9 +182,13 @@ public class FilterJoinNode extends FilterNode { if (more.get()) { //存在不同Class的关联表 if (this.nodes != null) { for (FilterNode node : this.nodes) { - if (((FilterJoinNode) node).joinClass == this.joinClass) continue; + if (((FilterJoinNode) node).joinClass == this.joinClass) { + continue; + } Predicate f = node.createPredicate(cache); - if (f == null) continue; + if (f == null) { + continue; + } final Predicate one = rs; final Predicate two = f; rs = (rs == null) ? f : (or ? new Predicate() { @@ -211,7 +221,9 @@ public class FilterJoinNode extends FilterNode { } private Predicate createJoinPredicate(final AtomicBoolean more) { - if (column == null && this.nodes == null) return null; + if (column == null && this.nodes == null) { + return null; + } final EntityCache joinCache = this.joinEntity.getCache(); Predicate filter = createElementPredicate(joinCache, true); if (this.nodes != null) { @@ -221,7 +233,9 @@ public class FilterJoinNode extends FilterNode { continue; } Predicate f = ((FilterJoinNode) node).createJoinPredicate(more); - if (f == null) continue; + if (f == null) { + continue; + } final Predicate one = filter; final Predicate two = f; filter = (filter == null) ? f : (or ? new Predicate() { @@ -256,14 +270,18 @@ public class FilterJoinNode extends FilterNode { protected CharSequence createSQLJoin(final Function func, final boolean update, final Map joinTabalis, final Set haset, final EntityInfo info) { boolean morejoin = false; if (this.joinEntity == null) { - if (this.joinClass != null) this.joinEntity = func.apply(this.joinClass); + if (this.joinClass != null) { + this.joinEntity = func.apply(this.joinClass); + } if (this.nodes != null) { for (FilterNode node : this.nodes) { if (node instanceof FilterJoinNode) { FilterJoinNode joinNode = ((FilterJoinNode) node); if (joinNode.joinClass != null) { joinNode.joinEntity = func.apply(joinNode.joinClass); - if (this.joinClass != null && this.joinClass != joinNode.joinClass) morejoin = true; + if (this.joinClass != null && this.joinClass != joinNode.joinClass) { + morejoin = true; + } } } } @@ -272,11 +290,15 @@ public class FilterJoinNode extends FilterNode { StringBuilder sb = new StringBuilder(); if (this.joinClass != null) { CharSequence cs = createElementSQLJoin(update, joinTabalis, haset, info, this); - if (cs != null) sb.append(cs); + if (cs != null) { + sb.append(cs); + } } if (morejoin) { Set set = new HashSet<>(); - if (this.joinClass != null) set.add(this.joinClass); + if (this.joinClass != null) { + set.add(this.joinClass); + } for (FilterNode node : this.nodes) { if (node instanceof FilterJoinNode) { FilterJoinNode joinNode = ((FilterJoinNode) node); @@ -294,7 +316,9 @@ public class FilterJoinNode extends FilterNode { } private static CharSequence createElementSQLJoin(final boolean update, final Map joinTabalis, final Set haset, final EntityInfo info, final FilterJoinNode node) { - if (node.joinClass == null || (haset != null && haset.contains(joinTabalis.get(node.joinClass)))) return null; + if (node.joinClass == null || (haset != null && haset.contains(joinTabalis.get(node.joinClass)))) { + return null; + } StringBuilder sb = new StringBuilder(); String[] joinColumns = node.joinColumns; int pos = joinColumns[0].indexOf('='); @@ -314,17 +338,27 @@ public class FilterJoinNode extends FilterNode { sb.append(" AND ").append(info.getSQLColumn("a", pos > 0 ? joinColumns[i].substring(0, pos) : joinColumns[i])).append(" = ").append(node.joinEntity.getSQLColumn(joinTabalis.get(node.joinClass), pos > 0 ? joinColumns[i].substring(pos + 1) : joinColumns[i])); } } - if (haset != null) haset.add(joinTabalis.get(node.joinClass)); + if (haset != null) { + haset.add(joinTabalis.get(node.joinClass)); + } return sb; } @Override protected boolean isCacheUseable(final Function entityApplyer) { - if (this.joinEntity == null) this.joinEntity = entityApplyer.apply(this.joinClass); - if (!this.joinEntity.isCacheFullLoaded()) return false; - if (this.nodes == null) return true; + if (this.joinEntity == null) { + this.joinEntity = entityApplyer.apply(this.joinClass); + } + if (!this.joinEntity.isCacheFullLoaded()) { + return false; + } + if (this.nodes == null) { + return true; + } for (FilterNode node : this.nodes) { - if (!node.isCacheUseable(entityApplyer)) return false; + if (!node.isCacheUseable(entityApplyer)) { + return false; + } } return true; } @@ -334,7 +368,9 @@ public class FilterJoinNode extends FilterNode { if (this.joinClass != null && !map.containsKey(this.joinClass)) { map.put(joinClass, "jt" + map.size()); //join_table_1 } - if (this.nodes == null) return; + if (this.nodes == null) { + return; + } for (FilterNode node : this.nodes) { node.putJoinTabalis(map); } diff --git a/src/main/java/org/redkale/source/FilterKey.java b/src/main/java/org/redkale/source/FilterKey.java index c584df799..37ed81ba7 100644 --- a/src/main/java/org/redkale/source/FilterKey.java +++ b/src/main/java/org/redkale/source/FilterKey.java @@ -10,12 +10,12 @@ import org.redkale.annotation.ConstructorParameters; /** * FilterKey主要用于自身字段间的表达式, 如: a.recordid = a.parentid , a.parentid就需要FilterKey来表示 new FilterKey("parentid") - *
+ *
* 注意:该类型不支持表达式:FV_XXX、BETWEEN、NOTBETWEEN、IN、NOTIN * *

* 详情见: https://redkale.org - * + * * @author zhangjx */ public class FilterKey implements java.io.Serializable { diff --git a/src/main/java/org/redkale/source/FilterNode.java b/src/main/java/org/redkale/source/FilterNode.java index 350afed13..6231e82d7 100644 --- a/src/main/java/org/redkale/source/FilterNode.java +++ b/src/main/java/org/redkale/source/FilterNode.java @@ -127,12 +127,20 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } public Serializable findValue(final String col) { - if (this.column != null && this.column.equals(col)) return this.value; - if (this.nodes == null) return null; + if (this.column != null && this.column.equals(col)) { + return this.value; + } + if (this.nodes == null) { + return null; + } for (FilterNode n : this.nodes) { - if (n == null) continue; + if (n == null) { + continue; + } Serializable val = n.findValue(col); - if (val != null) return val; + if (val != null) { + return val; + } } return null; } @@ -170,7 +178,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } protected FilterNode any(FilterNode node, boolean signor) { - if (this.readOnly) throw new SourceException("FilterNode(" + this + ") is ReadOnly"); + if (this.readOnly) { + throw new SourceException("FilterNode(" + this + ") is ReadOnly"); + } Objects.requireNonNull(node); if (this.column == null) { this.column = node.column; @@ -213,12 +223,18 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 * @return SQL的join语句 不存在返回null */ protected CharSequence createSQLJoin(final Function func, final boolean update, final Map joinTabalis, final Set haset, final EntityInfo info) { - if (joinTabalis == null || this.nodes == null) return null; + if (joinTabalis == null || this.nodes == null) { + return null; + } StringBuilder sb = null; for (FilterNode node : this.nodes) { CharSequence cs = node.createSQLJoin(func, update, joinTabalis, haset, info); - if (cs == null) continue; - if (sb == null) sb = new StringBuilder(); + if (cs == null) { + continue; + } + if (sb == null) { + sb = new StringBuilder(); + } sb.append(cs); } return sb; @@ -230,22 +246,30 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 * @return 是否存在关联表 */ protected boolean isjoin() { - if (this.nodes == null) return false; + if (this.nodes == null) { + return false; + } for (FilterNode node : this.nodes) { - if (node.isjoin()) return true; + if (node.isjoin()) { + return true; + } } return false; } protected final Map getJoinTabalis() { - if (!isjoin()) return null; + if (!isjoin()) { + return null; + } Map map = new HashMap<>(); putJoinTabalis(map); return map; } protected void putJoinTabalis(Map map) { - if (this.nodes == null) return; + if (this.nodes == null) { + return; + } for (FilterNode node : this.nodes) { node.putJoinTabalis(map); } @@ -259,9 +283,13 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 * @return 是否可以使用缓存 */ protected boolean isCacheUseable(final Function entityApplyer) { - if (this.nodes == null) return true; + if (this.nodes == null) { + return true; + } for (FilterNode node : this.nodes) { - if (!node.isCacheUseable(entityApplyer)) return false; + if (!node.isCacheUseable(entityApplyer)) { + return false; + } } return true; } @@ -279,7 +307,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 protected CharSequence createSQLExpress(DataSqlSource source, final EntityInfo info, final Map joinTabalis) { CharSequence sb0 = this.column == null || this.column.isEmpty() || this.column.charAt(0) == '#' || info == null ? null : createElementSQLExpress(source, info, joinTabalis == null ? null : joinTabalis.get(info.getType())); - if (this.nodes == null) return sb0; + if (this.nodes == null) { + return sb0; + } final StringBuilder rs = new StringBuilder(); rs.append('('); boolean more = false; @@ -289,13 +319,19 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } for (FilterNode node : this.nodes) { CharSequence f = node.createSQLExpress(source, info, joinTabalis); - if (f == null || f.length() < 3) continue; - if (more) rs.append(or ? " OR " : " AND "); + if (f == null || f.length() < 3) { + continue; + } + if (more) { + rs.append(or ? " OR " : " AND "); + } rs.append(f); more = true; } rs.append(')'); - if (rs.length() < 5) return null; + if (rs.length() < 5) { + return null; + } return rs; } @@ -331,18 +367,24 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } private static boolean needSplit(final FilterExpress express, final Object val0) { - if (val0 == null) return false; + if (val0 == null) { + return false; + } boolean items = express != IN && express != NOTIN; //是否数组集合的表达式 if (!items) { if (val0.getClass().isArray()) { Class comp = val0.getClass().getComponentType(); - if (comp == java.io.Serializable.class) comp = ((Object[]) val0)[0].getClass(); + if (comp == java.io.Serializable.class) { + comp = ((Object[]) val0)[0].getClass(); + } if (!(comp.isPrimitive() || CharSequence.class.isAssignableFrom(comp) || Number.class.isAssignableFrom(comp))) { items = true; } } else if (val0 instanceof Collection) { for (Object fv : (Collection) val0) { - if (fv == null) continue; + if (fv == null) { + continue; + } Class comp = fv.getClass(); if (!(comp.isPrimitive() || CharSequence.class.isAssignableFrom(comp) || Number.class.isAssignableFrom(comp))) { items = true; @@ -360,29 +402,49 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 if (val0 instanceof Collection) { StringBuilder sb = new StringBuilder(); boolean more = ((Collection) val0).size() > 1; - if (more) sb.append('('); + if (more) { + sb.append('('); + } for (Object fv : (Collection) val0) { - if (fv == null) continue; + if (fv == null) { + continue; + } CharSequence cs = createElementSQLExpress(source, info, talis, fv); - if (cs == null) continue; - if (sb.length() > 2) sb.append(itemand ? " AND " : " OR "); + if (cs == null) { + continue; + } + if (sb.length() > 2) { + sb.append(itemand ? " AND " : " OR "); + } sb.append(cs); } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb.length() > 3 ? sb : null; //若sb的值只是(),则不过滤 } else if (val0.getClass().isArray()) { StringBuilder sb = new StringBuilder(); Object[] fvs = (Object[]) val0; boolean more = fvs.length > 1; - if (more) sb.append('('); + if (more) { + sb.append('('); + } for (Object fv : fvs) { - if (fv == null) continue; + if (fv == null) { + continue; + } CharSequence cs = createElementSQLExpress(source, info, talis, fv); - if (cs == null) continue; - if (sb.length() > 2) sb.append(itemand ? " AND " : " OR "); + if (cs == null) { + continue; + } + if (sb.length() > 2) { + sb.append(itemand ? " AND " : " OR "); + } sb.append(cs); } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb.length() > 3 ? sb : null; //若sb的值只是(),则不过滤 } } @@ -391,15 +453,21 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } private CharSequence createElementSQLExpress(DataSqlSource source, final EntityInfo info, String talis, Object val0) { - if (column == null || this.column.isEmpty() || this.column.charAt(0) == '#') return null; - if (talis == null) talis = "a"; + if (column == null || this.column.isEmpty() || this.column.charAt(0) == '#') { + return null; + } + if (talis == null) { + talis = "a"; + } if (express == ISNULL || express == ISNOTNULL) { return new StringBuilder().append(info.getSQLColumn(talis, column)).append(' ').append(express.value()); } if (express == ISEMPTY || express == ISNOTEMPTY) { return new StringBuilder().append(info.getSQLColumn(talis, column)).append(' ').append(express.value()).append(" ''"); } - if (val0 == null) return null; + if (val0 == null) { + return null; + } if (express == FV_MOD || express == FV_DIV) { FilterValue fv = (FilterValue) val0; return new StringBuilder().append(info.getSQLColumn(talis, column)).append(' ').append(express.value()).append(' ').append(fv.getOptvalue()) @@ -407,19 +475,31 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } final boolean fk = (val0 instanceof FilterKey); CharSequence val = fk ? info.getSQLColumn(talis, ((FilterKey) val0).getColumn()) : formatToString(express, info.getSQLValue(column, (Serializable) val0)); - if (val == null) return null; + if (val == null) { + return null; + } StringBuilder sb = new StringBuilder(32); - if (express == CONTAIN) return source.containSQL.replace("${column}", info.getSQLColumn(talis, column)).replace("${keystr}", val); - if (express == IGNORECASECONTAIN) return source.containSQL.replace("${column}", "LOWER(" + info.getSQLColumn(talis, column) + ")").replace("${keystr}", val); - if (express == NOTCONTAIN) return source.notContainSQL.replace("${column}", info.getSQLColumn(talis, column)).replace("${keystr}", val); - if (express == IGNORECASENOTCONTAIN) return source.notContainSQL.replace("${column}", "LOWER(" + info.getSQLColumn(talis, column) + ")").replace("${keystr}", val); + if (express == CONTAIN) { + return source.containSQL.replace("${column}", info.getSQLColumn(talis, column)).replace("${keystr}", val); + } + if (express == IGNORECASECONTAIN) { + return source.containSQL.replace("${column}", "LOWER(" + info.getSQLColumn(talis, column) + ")").replace("${keystr}", val); + } + if (express == NOTCONTAIN) { + return source.notContainSQL.replace("${column}", info.getSQLColumn(talis, column)).replace("${keystr}", val); + } + if (express == IGNORECASENOTCONTAIN) { + return source.notContainSQL.replace("${column}", "LOWER(" + info.getSQLColumn(talis, column) + ")").replace("${keystr}", val); + } if (express == LENGTH_EQUAL || express == LENGTH_LESSTHAN || express == LENGTH_LESSTHANOREQUALTO || express == LENGTH_GREATERTHAN || express == LENGTH_GREATERTHANOREQUALTO) { sb.append("LENGTH(").append(info.getSQLColumn(talis, column)).append(')'); } else if (express == IGNORECASEEQUAL || express == IGNORECASENOTEQUAL || express == IGNORECASELIKE || express == IGNORECASENOTLIKE) { sb.append("LOWER(").append(info.getSQLColumn(talis, column)).append(')'); - if (fk) val = "LOWER(" + info.getSQLColumn(talis, ((FilterKey) val0).getColumn()) + ')'; + if (fk) { + val = "LOWER(" + info.getSQLColumn(talis, ((FilterKey) val0).getColumn()) + ')'; + } } else { sb.append(info.getSQLColumn(talis, column)); } @@ -440,12 +520,18 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } protected Predicate createPredicate(final EntityCache cache) { - if (cache == null || (column == null && this.nodes == null)) return null; + if (cache == null || (column == null && this.nodes == null)) { + return null; + } Predicate filter = createElementPredicate(cache, false); - if (this.nodes == null) return filter; + if (this.nodes == null) { + return filter; + } for (FilterNode node : this.nodes) { Predicate f = node.createPredicate(cache); - if (f == null) continue; + if (f == null) { + continue; + } final Predicate one = filter; final Predicate two = f; filter = (filter == null) ? f : (or ? new Predicate() { @@ -476,7 +562,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } protected final Predicate createElementPredicate(final EntityCache cache, final boolean join) { - if (this.column == null || this.column.isEmpty() || this.column.charAt(0) == '#') return null; + if (this.column == null || this.column.isEmpty() || this.column.charAt(0) == '#') { + return null; + } return createElementPredicate(cache, join, cache.getAttribute(column)); } @@ -487,9 +575,13 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 if (val0 instanceof Collection) { Predicate filter = null; for (Object fv : (Collection) val0) { - if (fv == null) continue; + if (fv == null) { + continue; + } Predicate f = createElementPredicate(cache, join, attr, fv); - if (f == null) continue; + if (f == null) { + continue; + } final Predicate one = filter; final Predicate two = f; filter = (filter == null) ? f : (!itemand ? new Predicate() { @@ -580,9 +672,13 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } Predicate filter = null; for (Object fv : (Object[]) val2) { - if (fv == null) continue; + if (fv == null) { + continue; + } Predicate f = createElementPredicate(cache, join, attr, fv); - if (f == null) continue; + if (f == null) { + continue; + } final Predicate one = filter; final Predicate two = f; filter = (filter == null) ? f : (!itemand ? new Predicate() { @@ -617,9 +713,12 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @SuppressWarnings("unchecked") protected final Predicate createElementPredicate(final EntityCache cache, final boolean join, final Attribute attr, Object val0) { - if (attr == null) return null; + if (attr == null) { + return null; + } final String field = join ? (cache.getType().getSimpleName() + "." + attr.field()) : attr.field(); - if (express == ISNULL) return new Predicate() { + if (express == ISNULL) { + return new Predicate() { @Override public boolean test(T t) { @@ -631,7 +730,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " = null"; } }; - if (express == ISNOTNULL) return new Predicate() { + } + if (express == ISNOTNULL) { + return new Predicate() { @Override public boolean test(T t) { @@ -643,7 +744,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " != null"; } }; - if (express == ISEMPTY) return new Predicate() { + } + if (express == ISEMPTY) { + return new Predicate() { @Override public boolean test(T t) { @@ -656,7 +759,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " = ''"; } }; - if (express == ISNOTEMPTY) return new Predicate() { + } + if (express == ISNOTEMPTY) { + return new Predicate() { @Override public boolean test(T t) { @@ -669,7 +774,10 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " != ''"; } }; - if (val0 == null) return null; + } + if (val0 == null) { + return null; + } final Class atype = attr.type(); final Class valtype = val0.getClass(); @@ -689,10 +797,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } } else if (valtype.isArray()) { final int len = Array.getLength(val0); - if (len == 0 && express == NOTIN) return null; + if (len == 0 && express == NOTIN) { + return null; + } final Class compType = valtype.getComponentType(); if (atype != compType && len > 0) { - if (!compType.isPrimitive() && Number.class.isAssignableFrom(compType)) throw new SourceException("param(" + val0 + ") type not match " + atype + " for column " + column); + if (!compType.isPrimitive() && Number.class.isAssignableFrom(compType)) { + throw new SourceException("param(" + val0 + ") type not match " + atype + " for column " + column); + } if (atype == int.class || atype == Integer.class) { int[] vs = new int[len]; for (int i = 0; i < len; i++) { @@ -733,7 +845,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } } else if (val0 instanceof Collection) { final Collection collection = (Collection) val0; - if (collection.isEmpty() && express == NOTIN) return null; + if (collection.isEmpty() && express == NOTIN) { + return null; + } if (!collection.isEmpty()) { Iterator it = collection.iterator(); it.hasNext(); @@ -786,7 +900,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 final Serializable val = (Serializable) val0; final boolean fk = (val instanceof FilterKey); final Attribute fkattr = fk ? cache.getAttribute(((FilterKey) val).getColumn()) : null; - if (fk && fkattr == null) throw new SourceException(cache.getType() + " not found column(" + ((FilterKey) val).getColumn() + ")"); + if (fk && fkattr == null) { + throw new SourceException(cache.getType() + " not found column(" + ((FilterKey) val).getColumn() + ")"); + } switch (express) { case EQUAL: return fk ? new Predicate() { @@ -819,8 +935,12 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 public boolean test(T t) { Object rs = attr.get(t); Object rs2 = fkattr.get(t); - if (rs == null && rs2 == null) return true; - if (rs == null || rs2 == null) return false; + if (rs == null && rs2 == null) { + return true; + } + if (rs == null || rs2 == null) { + return false; + } return Objects.equals(rs.toString().toLowerCase(), rs2.toString().toLowerCase()); } @@ -833,7 +953,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } return val.toString().equalsIgnoreCase(rs.toString()); } @@ -873,8 +995,12 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 public boolean test(T t) { Object rs = attr.get(t); Object rs2 = fkattr.get(t); - if (rs == null && rs2 == null) return false; - if (rs == null || rs2 == null) return true; + if (rs == null && rs2 == null) { + return false; + } + if (rs == null || rs2 == null) { + return true; + } return !Objects.equals(rs.toString().toLowerCase(), rs2.toString().toLowerCase()); } @@ -887,7 +1013,9 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return true; + if (rs == null) { + return true; + } return !val.toString().equalsIgnoreCase(rs.toString()); } @@ -1315,7 +1443,8 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } }; case IGNORECASELIKE: - if (fk) return new Predicate() { + if (fk) { + return new Predicate() { @Override public boolean test(T t) { @@ -1329,6 +1458,7 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return "LOWER(" + field + ") " + express.value() + " LOWER(" + fkattr.field() + ')'; } }; + } final String valstr = val.toString().toLowerCase(); return new Predicate() { @@ -1398,7 +1528,8 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } }; case IGNORECASENOTLIKE: - if (fk) return new Predicate() { + if (fk) { + return new Predicate() { @Override public boolean test(T t) { @@ -1412,6 +1543,7 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return "LOWER(" + field + ") " + express.value() + " LOWER(" + fkattr.field() + ')'; } }; + } final String valstr2 = val.toString().toLowerCase(); return new Predicate() { @@ -1529,7 +1661,8 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } }; case IGNORECASECONTAIN: - if (fk) return new Predicate() { + if (fk) { + return new Predicate() { @Override public boolean test(T t) { @@ -1543,6 +1676,7 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return " LOWER(" + fkattr.field() + ") " + express.value() + ' ' + "LOWER(" + field + ") "; } }; + } final String valstr3 = val.toString().toLowerCase(); return new Predicate() { @@ -1585,7 +1719,8 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } }; case IGNORECASENOTCONTAIN: - if (fk) return new Predicate() { + if (fk) { + return new Predicate() { @Override public boolean test(T t) { @@ -1599,6 +1734,7 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return " LOWER(" + fkattr.field() + ") " + express.value() + ' ' + "LOWER(" + field + ") "; } }; + } final String valstr4 = val.toString().toLowerCase(); return new Predicate() { @@ -1618,13 +1754,18 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 Range range = (Range) val; final Comparable min = range.getMin(); final Comparable max = range.getMax(); - if (express == BETWEEN) return new Predicate() { + if (express == BETWEEN) { + return new Predicate() { @Override public boolean test(T t) { Comparable rs = (Comparable) attr.get(t); - if (rs == null) return false; - if (min != null && min.compareTo(rs) >= 0) return false; + if (rs == null) { + return false; + } + if (min != null && min.compareTo(rs) >= 0) { + return false; + } return !(max != null && max.compareTo(rs) <= 0); } @@ -1633,13 +1774,19 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " BETWEEN " + min + " AND " + max; } }; - if (express == NOTBETWEEN) return new Predicate() { + } + if (express == NOTBETWEEN) { + return new Predicate() { @Override public boolean test(T t) { Comparable rs = (Comparable) attr.get(t); - if (rs == null) return true; - if (min != null && min.compareTo(rs) >= 0) return true; + if (rs == null) { + return true; + } + if (min != null && min.compareTo(rs) >= 0) { + return true; + } return (max != null && max.compareTo(rs) <= 0); } @@ -1648,6 +1795,7 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return field + " NOT BETWEEN " + min + " AND " + max; } }; + } return null; case IN: case NOTIN: @@ -1703,10 +1851,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } int k = (int) rs; for (int v : (int[]) val) { - if (v == k) return true; + if (v == k) { + return true; + } } return false; } @@ -1722,10 +1874,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } short k = (short) rs; for (short v : (short[]) val) { - if (v == k) return true; + if (v == k) { + return true; + } } return false; } @@ -1741,10 +1897,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } long k = (long) rs; for (long v : (long[]) val) { - if (v == k) return true; + if (v == k) { + return true; + } } return false; } @@ -1760,10 +1920,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } float k = (float) rs; for (float v : (float[]) val) { - if (v == k) return true; + if (v == k) { + return true; + } } return false; } @@ -1779,10 +1943,14 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } double k = (double) rs; for (double v : (double[]) val) { - if (v == k) return true; + if (v == k) { + return true; + } } return false; } @@ -1798,9 +1966,13 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 @Override public boolean test(T t) { Object rs = attr.get(t); - if (rs == null) return false; + if (rs == null) { + return false; + } for (Object v : (Object[]) val) { - if (rs.equals(v)) return true; + if (rs.equals(v)) { + return true; + } } return false; } @@ -1841,17 +2013,25 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 StringBuilder sb = new StringBuilder(); StringBuilder element = toElementString(prefix); boolean more = element != null && element.length() > 0 && this.nodes != null; - if (more) sb.append('('); + if (more) { + sb.append('('); + } sb.append(element); if (this.nodes != null) { for (FilterNode node : this.nodes) { String s = node.toString(); - if (s.length() < 1) continue; - if (sb.length() > 1) sb.append(or ? " OR " : " AND "); + if (s.length() < 1) { + continue; + } + if (sb.length() > 1) { + sb.append(or ? " OR " : " AND "); + } sb.append(s); } } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb; } @@ -1861,29 +2041,49 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 if (val0 instanceof Collection) { StringBuilder sb = new StringBuilder(); boolean more = ((Collection) val0).size() > 1; - if (more) sb.append('('); + if (more) { + sb.append('('); + } for (Object fv : (Collection) val0) { - if (fv == null) continue; + if (fv == null) { + continue; + } CharSequence cs = toElementString(prefix, fv); - if (cs == null) continue; - if (sb.length() > 2) sb.append(itemand ? " AND " : " OR "); + if (cs == null) { + continue; + } + if (sb.length() > 2) { + sb.append(itemand ? " AND " : " OR "); + } sb.append(cs); } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb.length() > 3 ? sb : null; //若sb的值只是(),则不过滤 } else if (val0.getClass().isArray()) { StringBuilder sb = new StringBuilder(); Object[] fvs = (Object[]) val0; boolean more = fvs.length > 1; - if (more) sb.append('('); + if (more) { + sb.append('('); + } for (Object fv : fvs) { - if (fv == null) continue; + if (fv == null) { + continue; + } CharSequence cs = toElementString(prefix, fv); - if (cs == null) continue; - if (sb.length() > 2) sb.append(itemand ? " AND " : " OR "); + if (cs == null) { + continue; + } + if (sb.length() > 2) { + sb.append(itemand ? " AND " : " OR "); + } sb.append(cs); } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb.length() > 3 ? sb : null; //若sb的值只是(),则不过滤 } } @@ -1912,8 +2112,12 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 } private static CharSequence formatToString(FilterExpress express, Object value) { - if (value == null) return null; - if (value instanceof Number) return String.valueOf(value); + if (value == null) { + return null; + } + if (value instanceof Number) { + return String.valueOf(value); + } if (value instanceof CharSequence) { if (express == LIKE || express == NOTLIKE) { value = "%" + value + '%'; @@ -1946,16 +2150,22 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return sb; } else if (value.getClass().isArray()) { int len = Array.getLength(value); - if (len == 0) return express == NOTIN ? null : new StringBuilder("(NULL)"); + if (len == 0) { + return express == NOTIN ? null : new StringBuilder("(NULL)"); + } if (len == 1) { Object firstval = Array.get(value, 0); - if (firstval != null && firstval.getClass().isArray()) return formatToString(express, firstval); + if (firstval != null && firstval.getClass().isArray()) { + return formatToString(express, firstval); + } } StringBuilder sb = new StringBuilder(); sb.append('('); for (int i = 0; i < len; i++) { Object o = Array.get(value, i); - if (sb.length() > 1) sb.append(','); + if (sb.length() > 1) { + sb.append(','); + } if (o instanceof CharSequence) { sb.append('\'').append(o.toString().replace("'", "\\'")).append('\''); } else { @@ -1965,11 +2175,15 @@ public class FilterNode { //FilterNode 不能实现Serializable接口, 否则 return sb.append(')'); } else if (value instanceof Collection) { Collection c = (Collection) value; - if (c.isEmpty()) return express == NOTIN ? null : new StringBuilder("(NULL)"); + if (c.isEmpty()) { + return express == NOTIN ? null : new StringBuilder("(NULL)"); + } StringBuilder sb = new StringBuilder(); sb.append('('); for (Object o : c) { - if (sb.length() > 1) sb.append(','); + if (sb.length() > 1) { + sb.append(','); + } if (o instanceof CharSequence) { sb.append('\'').append(o.toString().replace("'", "\\'")).append('\''); } else { diff --git a/src/main/java/org/redkale/source/FilterNodeBean.java b/src/main/java/org/redkale/source/FilterNodeBean.java index 8a4d149de..abd405551 100644 --- a/src/main/java/org/redkale/source/FilterNodeBean.java +++ b/src/main/java/org/redkale/source/FilterNodeBean.java @@ -75,18 +75,26 @@ public final class FilterNodeBean implements Comparable implements Comparable clazz) { FilterNodeBean rs = beanodes.get(clazz); - if (rs != null) return rs; + if (rs != null) { + return rs; + } synchronized (beanodes) { rs = beanodes.get(clazz); if (rs == null) { @@ -150,7 +162,9 @@ public final class FilterNodeBean implements Comparable implements Comparable implements Comparable implements Comparable implements Comparable implements Comparable o) { - if (this.joinClass == null && o.joinClass == null) return 0; - if (this.joinClass != null && o.joinClass != null) return 0; + if (this.joinClass == null && o.joinClass == null) { + return 0; + } + if (this.joinClass != null && o.joinClass != null) { + return 0; + } return this.joinClass == null ? -1 : 1; } @@ -298,7 +338,9 @@ public final class FilterNodeBean implements Comparable implements Comparable 0 && this.nodeBeans != null; - if (more) sb.append('('); + if (more) { + sb.append('('); + } sb.append(element); if (this.nodeBeans != null) { for (FilterNodeBean node : this.nodeBeans) { String s = node.toString(); - if (s.length() < 1) continue; - if (sb.length() > 1) sb.append(or ? " OR " : " AND "); + if (s.length() < 1) { + continue; + } + if (sb.length() > 1) { + sb.append(or ? " OR " : " AND "); + } sb.append(s); } } - if (more) sb.append(')'); + if (more) { + sb.append(')'); + } return sb; } diff --git a/src/main/java/org/redkale/source/SearchQuery.java b/src/main/java/org/redkale/source/SearchQuery.java index d0f5853a4..c70fbc1ae 100644 --- a/src/main/java/org/redkale/source/SearchQuery.java +++ b/src/main/java/org/redkale/source/SearchQuery.java @@ -142,7 +142,9 @@ public interface SearchQuery extends java.io.Serializable { public SearchSimpleQuery(String keyword, String... fields) { this.keyword = keyword; this.fields = fields; - if (fields == null || fields.length < 1) throw new IllegalArgumentException("fields is empty"); + if (fields == null || fields.length < 1) { + throw new IllegalArgumentException("fields is empty"); + } } public SearchSimpleQuery keyword(String keyword) { @@ -156,7 +158,9 @@ public interface SearchQuery extends java.io.Serializable { } public SearchSimpleQuery fields(String... fields) { - if (fields == null || fields.length < 1) throw new IllegalArgumentException("fields is empty"); + if (fields == null || fields.length < 1) { + throw new IllegalArgumentException("fields is empty"); + } this.fields = fields; return this; } @@ -177,7 +181,9 @@ public interface SearchQuery extends java.io.Serializable { } public SearchSimpleQuery extras(String key, Object value) { - if (this.extras == null) this.extras = new LinkedHashMap<>(); + if (this.extras == null) { + this.extras = new LinkedHashMap<>(); + } this.extras.put(key, value); return this; } @@ -315,7 +321,9 @@ public interface SearchQuery extends java.io.Serializable { } public SearchSimpleHighlight extras(String key, Object value) { - if (this.extras == null) this.extras = new LinkedHashMap<>(); + if (this.extras == null) { + this.extras = new LinkedHashMap<>(); + } this.extras.put(key, value); return this; } diff --git a/src/main/java/org/redkale/util/AnyValue.java b/src/main/java/org/redkale/util/AnyValue.java index c81f2d897..b7b244c75 100644 --- a/src/main/java/org/redkale/util/AnyValue.java +++ b/src/main/java/org/redkale/util/AnyValue.java @@ -9,7 +9,6 @@ import java.io.*; import java.nio.charset.*; import java.util.*; import java.util.function.*; - import org.redkale.annotation.ConstructorParameters; import org.redkale.convert.ConvertDisabled; @@ -170,7 +169,9 @@ public abstract class AnyValue { rs.stringEntrys = new Entry[this.stringEntrys.length]; for (int i = 0; i < rs.stringEntrys.length; i++) { Entry en = this.stringEntrys[i]; - if (en == null) continue; + if (en == null) { + continue; + } rs.stringEntrys[i] = new Entry(en.name, en.value); } } @@ -178,7 +179,9 @@ public abstract class AnyValue { rs.anyEntrys = new Entry[this.anyEntrys.length]; for (int i = 0; i < rs.anyEntrys.length; i++) { Entry en = this.anyEntrys[i]; - if (en == null) continue; + if (en == null) { + continue; + } rs.anyEntrys[i] = new Entry(en.name, en.value == null ? null : en.value.copy()); } } @@ -219,25 +222,35 @@ public abstract class AnyValue { } protected DefaultAnyValue merge(AnyValue node0, String path, MergeFunction func) { - if (node0 == null) return this; - if (node0 == this) throw new IllegalArgumentException(); + if (node0 == null) { + return this; + } + if (node0 == this) { + throw new IllegalArgumentException(); + } DefaultAnyValue node = (DefaultAnyValue) node0; if (node.stringEntrys != null) { for (Entry en : node.stringEntrys) { - if (en == null) continue; + if (en == null) { + continue; + } setValue(en.name, en.value); } } if (node.anyEntrys != null) { for (Entry en : node.anyEntrys) { - if (en == null || en.value == null) continue; + if (en == null || en.value == null) { + continue; + } Entry[] ns = getAnyValueEntrys(en.name); if (ns == null || ns.length < 1) { addValue(en.name, en.value); } else { boolean ok = false; for (Entry item : ns) { - if (item == null) continue; + if (item == null) { + continue; + } if (item.value != null && en.value.parentArrayIndex == ((DefaultAnyValue) item.value).parentArrayIndex) { if (func == null) { item.value.merge(en.value, func); @@ -278,11 +291,17 @@ public abstract class AnyValue { * @return DefaultAnyValue */ public DefaultAnyValue addAllStringSet(final AnyValue av) { - if (av == null) return this; + if (av == null) { + return this; + } final Entry[] strings = av.getStringEntrys(); - if (strings == null) return this; + if (strings == null) { + return this; + } for (Entry en : strings) { - if (!existsValue(en.name)) this.addValue(en.name, en.value); + if (!existsValue(en.name)) { + this.addValue(en.name, en.value); + } } return this; } @@ -295,7 +314,9 @@ public abstract class AnyValue { * @return DefaultAnyValue */ public DefaultAnyValue addAll(final AnyValue av) { - if (av == null) return this; + if (av == null) { + return this; + } if (av instanceof DefaultAnyValue) { final DefaultAnyValue adv = (DefaultAnyValue) av; if (adv.stringEntrys != null) { @@ -333,7 +354,9 @@ public abstract class AnyValue { * @return DefaultAnyValue */ public DefaultAnyValue setAll(final AnyValue av) { - if (av == null) return this; + if (av == null) { + return this; + } if (av instanceof DefaultAnyValue) { final DefaultAnyValue adv = (DefaultAnyValue) av; if (adv.stringEntrys != null) { @@ -452,14 +475,20 @@ public abstract class AnyValue { public String toString() { return toString(0, (any, space) -> { int index = ((DefaultAnyValue) any).parentArrayIndex; - if (index < 0) return null; + if (index < 0) { + return null; + } return new StringBuilder().append(space).append(" '$index': ").append(index).append(",\r\n"); }); } public DefaultAnyValue clear() { - if (this.stringEntrys != null && this.stringEntrys.length > 0) this.stringEntrys = new Entry[0]; - if (this.anyEntrys != null && this.anyEntrys.length > 0) this.anyEntrys = new Entry[0]; + if (this.stringEntrys != null && this.stringEntrys.length > 0) { + this.stringEntrys = new Entry[0]; + } + if (this.anyEntrys != null && this.anyEntrys.length > 0) { + this.anyEntrys = new Entry[0]; + } return this; } @@ -536,28 +565,36 @@ public abstract class AnyValue { public DefaultAnyValue removeAnyValues(String name) { Objects.requireNonNull(name); - if (this.anyEntrys == null) return this; + if (this.anyEntrys == null) { + return this; + } this.anyEntrys = Utility.remove(this.anyEntrys, (t) -> name.equals(((Entry) t).name)); return this; } public DefaultAnyValue removeValue(String name, AnyValue value) { Objects.requireNonNull(name); - if (value == null || this.anyEntrys == null) return this; + if (value == null || this.anyEntrys == null) { + return this; + } this.anyEntrys = Utility.remove(this.anyEntrys, (t) -> name.equals(((Entry) t).name) && ((Entry) t).getValue().equals(value)); return this; } public DefaultAnyValue removeStringValues(String name) { Objects.requireNonNull(name); - if (this.stringEntrys == null) return this; + if (this.stringEntrys == null) { + return this; + } this.stringEntrys = Utility.remove(this.stringEntrys, (t) -> name.equals(((Entry) t).name)); return this; } public DefaultAnyValue removeValue(String name, String value) { Objects.requireNonNull(name); - if (value == null || this.stringEntrys == null) return this; + if (value == null || this.stringEntrys == null) { + return this; + } this.stringEntrys = Utility.remove(this.stringEntrys, (t) -> name.equals(((Entry) t).name) && ((Entry) t).getValue().equals(value)); return this; } @@ -642,7 +679,9 @@ public abstract class AnyValue { ++len; } } - if (len == 0) return new Entry[len]; + if (len == 0) { + return new Entry[len]; + } Entry[] rs = new Entry[len]; int i = 0; for (Entry en : entitys) { @@ -660,7 +699,9 @@ public abstract class AnyValue { ++len; } } - if (len == 0) return new String[len]; + if (len == 0) { + return new String[len]; + } String[] rs = new String[len]; int i = 0; for (Entry en : entitys) { @@ -678,7 +719,9 @@ public abstract class AnyValue { ++len; } } - if (len == 0) return new AnyValue[len]; + if (len == 0) { + return new AnyValue[len]; + } AnyValue[] rs = new AnyValue[len]; int i = 0; for (Entry en : entitys) { @@ -699,7 +742,9 @@ public abstract class AnyValue { } } } - if (len == 0) return new String[len]; + if (len == 0) { + return new String[len]; + } String[] rs = new String[len]; int i = 0; for (Entry en : entitys) { @@ -723,7 +768,9 @@ public abstract class AnyValue { } } } - if (len == 0) return new AnyValue[len]; + if (len == 0) { + return new AnyValue[len]; + } AnyValue[] rs = new AnyValue[len]; int i = 0; for (Entry en : entitys) { @@ -837,7 +884,9 @@ public abstract class AnyValue { * @return AnyValue */ public static AnyValue loadFromProperties(Properties properties, String nameName) { - if (properties == null) return null; + if (properties == null) { + return null; + } DefaultAnyValue conf = new DefaultAnyValue(); final char splitChar = (char) 2; Map prefixArray = new TreeMap<>(); //已处理的数组key,如 redkale.source[0].xx 存redkale.source[0] @@ -922,7 +971,9 @@ public abstract class AnyValue { DefaultAnyValue index = (DefaultAnyValue) field.getAnyValue(keyOrIndex); if (index == null) { index = new DefaultAnyValue(); - if (nameName != null) index.setValue(nameName, keyOrIndex); + if (nameName != null) { + index.setValue(nameName, keyOrIndex); + } field.addValue(keyOrIndex, index); } parent = index; @@ -1064,13 +1115,17 @@ public abstract class AnyValue { * @return String */ public String toString(int indent, BiFunction prefixFunc) { //indent: 缩进长度 - if (indent < 0) indent = 0; + if (indent < 0) { + indent = 0; + } final String space = " ".repeat(indent); StringBuilder sb = new StringBuilder(); sb.append("{\r\n"); if (prefixFunc != null) { CharSequence v = prefixFunc.apply(this, space); - if (v != null) sb.append(v); + if (v != null) { + sb.append(v); + } } Entry[] stringArray = getStringEntrys(); Entry[] anyArray = getAnyEntrys(); @@ -1274,7 +1329,9 @@ public abstract class AnyValue { */ public byte getByteValue(String name, byte defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Byte.decode(value); } catch (NumberFormatException e) { @@ -1293,7 +1350,9 @@ public abstract class AnyValue { */ public byte getByteValue(int radix, String name, byte defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Byte.decode(value) : Byte.parseByte(value, radix)); } catch (NumberFormatException e) { @@ -1346,7 +1405,9 @@ public abstract class AnyValue { */ public short getShortValue(String name, short defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Short.decode(value); } catch (NumberFormatException e) { @@ -1365,7 +1426,9 @@ public abstract class AnyValue { */ public short getShortValue(int radix, String name, short defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Short.decode(value) : Short.parseShort(value, radix)); } catch (NumberFormatException e) { @@ -1394,7 +1457,9 @@ public abstract class AnyValue { */ public int getIntValue(String name, int defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Integer.decode(value); } catch (NumberFormatException e) { @@ -1413,7 +1478,9 @@ public abstract class AnyValue { */ public int getIntValue(int radix, String name, int defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Integer.decode(value) : Integer.parseInt(value, radix)); } catch (NumberFormatException e) { @@ -1442,7 +1509,9 @@ public abstract class AnyValue { */ public long getLongValue(String name, long defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Long.decode(value); } catch (NumberFormatException e) { @@ -1461,7 +1530,9 @@ public abstract class AnyValue { */ public long getLongValue(int radix, String name, long defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return (radix == 10 ? Long.decode(value) : Long.parseLong(value, radix)); } catch (NumberFormatException e) { @@ -1490,7 +1561,9 @@ public abstract class AnyValue { */ public float getFloatValue(String name, float defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Float.parseFloat(value); } catch (NumberFormatException e) { @@ -1519,7 +1592,9 @@ public abstract class AnyValue { */ public double getDoubleValue(String name, double defaultValue) { String value = getValue(name); - if (value == null || value.length() == 0) return defaultValue; + if (value == null || value.length() == 0) { + return defaultValue; + } try { return Double.parseDouble(value); } catch (NumberFormatException e) { @@ -1555,18 +1630,30 @@ public abstract class AnyValue { @Override public boolean equals(Object other) { - if (!(other instanceof AnyValue)) return false; + if (!(other instanceof AnyValue)) { + return false; + } AnyValue conf = (AnyValue) other; - if (!equals(this.getStringEntrys(), conf.getStringEntrys())) return false; + if (!equals(this.getStringEntrys(), conf.getStringEntrys())) { + return false; + } return equals(this.getAnyEntrys(), conf.getAnyEntrys()); } private static boolean equals(Entry[] entry1, Entry[] entry2) { - if ((entry1 == null || entry1.length == 0) && (entry2 == null || entry2.length == 0)) return true; - if (entry1.length != entry2.length) return false; + if ((entry1 == null || entry1.length == 0) && (entry2 == null || entry2.length == 0)) { + return true; + } + if (entry1.length != entry2.length) { + return false; + } for (int i = 0; i < entry1.length; i++) { - if (!entry1[i].name.equals(entry2[i].name)) return false; - if (!entry1[i].getValue().equals(entry2[i].getValue())) return false; + if (!entry1[i].name.equals(entry2[i].name)) { + return false; + } + if (!entry1[i].getValue().equals(entry2[i].getValue())) { + return false; + } } return true; } @@ -1601,14 +1688,18 @@ public abstract class AnyValue { * @return StringBuilder */ protected static StringBuilder toXMLString(StringBuilder sb, String nodeName, AnyValue conf, int indent) { //indent: 缩进长度 - if (indent < 0) indent = 0; + if (indent < 0) { + indent = 0; + } final String space = " ".repeat(indent); Entry[] anys = conf.getAnyEntrys(); sb.append(space).append('<').append(nodeName); for (Entry en : conf.getStringEntrys()) { sb.append(' ').append(en.name).append("=\"").append(en.value).append("\""); } - if (anys == null || anys.length == 0) return sb.append("/>\r\n\r\n"); + if (anys == null || anys.length == 0) { + return sb.append("/>\r\n\r\n"); + } sb.append(">\r\n\r\n"); for (Entry en : conf.getAnyEntrys()) { toXMLString(sb, en.name, en.getValue(), indent + 4); diff --git a/src/main/java/org/redkale/util/Attribute.java b/src/main/java/org/redkale/util/Attribute.java index 80af3b764..7151600f6 100644 --- a/src/main/java/org/redkale/util/Attribute.java +++ b/src/main/java/org/redkale/util/Attribute.java @@ -8,9 +8,11 @@ package org.redkale.util; import java.lang.reflect.TypeVariable; import java.util.*; import java.util.function.*; -import org.redkale.asm.*; import static org.redkale.asm.ClassWriter.COMPUTE_FRAMES; import static org.redkale.asm.Opcodes.*; +import org.redkale.asm.*; +import static org.redkale.asm.Opcodes.*; +import org.redkale.util.Attribute; /** * 该类实现动态映射一个JavaBean类中成员对应的getter、setter方法; 代替低效的反射实现方式。 @@ -412,16 +414,28 @@ public interface Attribute { List> list = new ArrayList<>(); RedkaleClassLoader.putReflectionPublicFields(clazz.getName()); for (java.lang.reflect.Field field : clazz.getFields()) { - if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; - if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) continue; + if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { + continue; + } + if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) { + continue; + } list.add(create(clazz, field)); } RedkaleClassLoader.putReflectionDeclaredMethods(clazz.getName()); for (java.lang.reflect.Method setter : clazz.getDeclaredMethods()) { - if (java.lang.reflect.Modifier.isStatic(setter.getModifiers())) continue; - if (!setter.getName().startsWith("set")) continue; - if (setter.getReturnType() != void.class) continue; - if (setter.getParameterCount() != 1) continue; + if (java.lang.reflect.Modifier.isStatic(setter.getModifiers())) { + continue; + } + if (!setter.getName().startsWith("set")) { + continue; + } + if (setter.getReturnType() != void.class) { + continue; + } + if (setter.getParameterCount() != 1) { + continue; + } Class t = setter.getParameterTypes()[0]; String prefix = t == boolean.class || t == Boolean.class ? "is" : "get"; java.lang.reflect.Method getter = null; @@ -447,16 +461,28 @@ public interface Attribute { List> list = new ArrayList<>(); RedkaleClassLoader.putReflectionPublicFields(clazz.getName()); for (java.lang.reflect.Field field : clazz.getFields()) { - if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; - if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) continue; + if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { + continue; + } + if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) { + continue; + } list.add(create(clazz, field)); } RedkaleClassLoader.putReflectionDeclaredMethods(clazz.getName()); for (java.lang.reflect.Method method : clazz.getDeclaredMethods()) { - if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) continue; - if (method.getReturnType() == void.class) continue; - if (method.getParameterCount() != 0) continue; - if (method.getName().equals("getClass")) continue; + if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) { + continue; + } + if (method.getReturnType() == void.class) { + continue; + } + if (method.getParameterCount() != 0) { + continue; + } + if (method.getName().equals("getClass")) { + continue; + } if ((method.getName().startsWith("get") && method.getName().length() > 3) || (method.getName().startsWith("is") && method.getName().length() > 2) || Utility.isRecordGetter(clazz, method)) { @@ -478,15 +504,25 @@ public interface Attribute { List> list = new ArrayList<>(); RedkaleClassLoader.putReflectionPublicFields(clazz.getName()); for (java.lang.reflect.Field field : clazz.getFields()) { - if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) continue; - if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) continue; + if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) { + continue; + } + if (java.lang.reflect.Modifier.isFinal(field.getModifiers())) { + continue; + } list.add(create(clazz, field)); } RedkaleClassLoader.putReflectionDeclaredMethods(clazz.getName()); for (java.lang.reflect.Method method : clazz.getDeclaredMethods()) { - if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) continue; - if (!method.getName().startsWith("set")) continue; - if (method.getParameterCount() != 1) continue; + if (java.lang.reflect.Modifier.isStatic(method.getModifiers())) { + continue; + } + if (!method.getName().startsWith("set")) { + continue; + } + if (method.getParameterCount() != 1) { + continue; + } list.add(create(clazz, (java.lang.reflect.Method) null, method)); } return list.toArray(new Attribute[list.size()]); @@ -648,8 +684,12 @@ public interface Attribute { */ @SuppressWarnings("unchecked") public static Attribute create(java.lang.reflect.Type subclass, final Class clazz, String fieldAlias, final Class fieldType, final java.lang.reflect.Field field, java.lang.reflect.Method getter, java.lang.reflect.Method setter, Object attach) { - if (subclass == null) subclass = clazz; - if (fieldAlias != null && fieldAlias.isEmpty()) fieldAlias = null; + if (subclass == null) { + subclass = clazz; + } + if (fieldAlias != null && fieldAlias.isEmpty()) { + fieldAlias = null; + } int mod = field == null ? java.lang.reflect.Modifier.STATIC : field.getModifiers(); if (field != null && !java.lang.reflect.Modifier.isStatic(mod) && !java.lang.reflect.Modifier.isPublic(mod)) { Class t = field.getType(); @@ -663,7 +703,9 @@ public interface Attribute { } catch (Exception ex) { try { java.lang.reflect.Method m = clazz.getMethod(field.getName()); - if (Utility.isRecordGetter(clazz, m) && field.getType() == m.getReturnType()) getter = m; + if (Utility.isRecordGetter(clazz, m) && field.getType() == m.getReturnType()) { + getter = m; + } } catch (Exception ex2) { } } @@ -735,7 +777,9 @@ public interface Attribute { if (generictype instanceof java.lang.reflect.TypeVariable) { checkCast = true; generictype = TypeToken.getGenericType(generictype, subclass); - if (generictype instanceof Class) column = (Class) generictype; + if (generictype instanceof Class) { + column = (Class) generictype; + } } StringBuilder newsubname = new StringBuilder(); for (char ch : subclass.toString().replace("class ", "").toCharArray()) { //RetResult与RetResult>是不一样的 @@ -758,7 +802,9 @@ public interface Attribute { tostr += "_getter_setter"; } final Class pcolumn = column; - if (column.isPrimitive()) column = java.lang.reflect.Array.get(java.lang.reflect.Array.newInstance(column, 1), 0).getClass(); + if (column.isPrimitive()) { + column = java.lang.reflect.Array.get(java.lang.reflect.Array.newInstance(column, 1), 0).getClass(); + } final String supDynName = Attribute.class.getName().replace('.', '/'); final String interName = TypeToken.typeToClass(subclass).getName().replace('.', '/'); final String columnName = column.getName().replace('.', '/'); @@ -776,7 +822,9 @@ public interface Attribute { if (realclz != null) { pkgname = realclz.getName(); int pos = pkgname.lastIndexOf('.'); - if (pos > 0) pkgname = pkgname.substring(0, pos + 1); + if (pos > 0) { + pkgname = pkgname.substring(0, pos + 1); + } pkgname = pkgname.replace('.', '/'); } final String newDynName = "org/redkaledyn/attribute/" + pkgname + "_Dyn" + Attribute.class.getSimpleName() @@ -883,7 +931,9 @@ public interface Attribute { mv.visitMethodInsn(INVOKESTATIC, columnName, "valueOf", "(" + Type.getDescriptor(pcolumn) + ")" + columnDesc, false); m = 2; } else { - if (checkCast) mv.visitTypeInsn(CHECKCAST, columnName); + if (checkCast) { + mv.visitTypeInsn(CHECKCAST, columnName); + } } } } else { @@ -893,7 +943,9 @@ public interface Attribute { mv.visitMethodInsn(INVOKESTATIC, columnName, "valueOf", "(" + Type.getDescriptor(pcolumn) + ")" + columnDesc, false); m = 2; } else { - if (checkCast) mv.visitTypeInsn(CHECKCAST, columnName); + if (checkCast) { + mv.visitTypeInsn(CHECKCAST, columnName); + } } } mv.visitInsn(ARETURN); @@ -1073,8 +1125,12 @@ public interface Attribute { Objects.requireNonNull(fieldName); Objects.requireNonNull(fieldType); String str = Attribute.class.getSimpleName() + "_" + fieldName + "_" + fieldType.getSimpleName(); - if (getter != null) str += "_getter"; - if (setter != null) str += "_setter"; + if (getter != null) { + str += "_getter"; + } + if (setter != null) { + str += "_setter"; + } final String tostr = str; return new Attribute() { @Override @@ -1109,7 +1165,9 @@ public interface Attribute { @Override public void set(T obj, F value) { - if (setter != null) setter.accept(obj, value); + if (setter != null) { + setter.accept(obj, value); + } } @Override diff --git a/src/main/java/org/redkale/util/ByteArray.java b/src/main/java/org/redkale/util/ByteArray.java index 176c17882..a4656a86d 100644 --- a/src/main/java/org/redkale/util/ByteArray.java +++ b/src/main/java/org/redkale/util/ByteArray.java @@ -74,12 +74,18 @@ public final class ByteArray implements ByteTuple { * @return 是否相同 */ public boolean equal(final byte[] bytes) { - if (bytes == null) return false; + if (bytes == null) { + return false; + } int len = count; - if (len != bytes.length) return false; + if (len != bytes.length) { + return false; + } byte[] ba = content; for (int i = 0; i < len; i++) { - if (ba[i] != bytes[i]) return false; + if (ba[i] != bytes[i]) { + return false; + } } return true; } @@ -218,13 +224,19 @@ public final class ByteArray implements ByteTuple { * @param buffer ByteBuffer */ public void put(ByteBuffer buffer) { - if (buffer == null) return; + if (buffer == null) { + return; + } int remain = buffer.remaining(); - if (remain == 0) return; + if (remain == 0) { + return; + } int l = this.content.length - count; if (remain > l) { byte[] ns = new byte[this.content.length + remain]; - if (count > 0) System.arraycopy(content, 0, ns, 0, count); + if (count > 0) { + System.arraycopy(content, 0, ns, 0, count); + } this.content = ns; } buffer.get(content, count, remain); @@ -294,7 +306,9 @@ public final class ByteArray implements ByteTuple { * @return byte[] */ public byte[] getBytes(int offset, int length) { - if (length < 1) return new byte[0]; + if (length < 1) { + return new byte[0]; + } byte[] bs = new byte[length]; System.arraycopy(this.content, offset, bs, 0, length); return bs; @@ -361,7 +375,9 @@ public final class ByteArray implements ByteTuple { byte[] bytes = this.content; int end = limit > 0 ? limit : count; for (int i = offset; i < end; i++) { - if (bytes[i] == value) return i; + if (bytes[i] == value) { + return i; + } } return -1; } @@ -372,7 +388,9 @@ public final class ByteArray implements ByteTuple { * @return ByteArray */ public ByteArray removeLastByte() { - if (count > 0) count--; + if (count > 0) { + count--; + } return this; } @@ -738,7 +756,9 @@ public final class ByteArray implements ByteTuple { * @return ByteArray */ public ByteArray put(byte... values) { - if (values.length < 1) return this; + if (values.length < 1) { + return this; + } if (count >= content.length - values.length) { byte[] ns = new byte[content.length + values.length]; System.arraycopy(content, 0, ns, 0, count); @@ -758,7 +778,9 @@ public final class ByteArray implements ByteTuple { * @return ByteArray */ public ByteArray put(int offset, byte... values) { - if (values.length < 1) throw new IllegalArgumentException(); + if (values.length < 1) { + throw new IllegalArgumentException(); + } System.arraycopy(values, 0, content, offset, values.length); return this; } @@ -827,7 +849,9 @@ public final class ByteArray implements ByteTuple { * @return ByteArray */ public ByteArray put(ByteBuffer buffer, int len) { - if (len < 1) return this; + if (len < 1) { + return this; + } if (count >= content.length - len) { byte[] ns = new byte[content.length + len]; System.arraycopy(content, 0, ns, 0, count); @@ -864,7 +888,9 @@ public final class ByteArray implements ByteTuple { * @return 字符串 */ public String toString(final int offset, int len, final Charset charset) { - if (charset == null) return new String(content, offset, len, StandardCharsets.UTF_8); + if (charset == null) { + return new String(content, offset, len, StandardCharsets.UTF_8); + } return new String(content, offset, len, charset); } @@ -877,7 +903,9 @@ public final class ByteArray implements ByteTuple { * @return 字符串 */ public String toString(final int offset, final Charset charset) { - if (charset == null) return new String(content, offset, count - offset, StandardCharsets.UTF_8); + if (charset == null) { + return new String(content, offset, count - offset, StandardCharsets.UTF_8); + } return new String(content, offset, count - offset, charset); } diff --git a/src/main/java/org/redkale/util/ByteBufferReader.java b/src/main/java/org/redkale/util/ByteBufferReader.java index 8eeeb1c5c..0a4d3fd28 100644 --- a/src/main/java/org/redkale/util/ByteBufferReader.java +++ b/src/main/java/org/redkale/util/ByteBufferReader.java @@ -72,7 +72,9 @@ public class ByteBufferReader { } public static byte[] toBytes(ByteBuffer[] buffers) { - if (buffers == null) return null; + if (buffers == null) { + return null; + } int size = 0; for (ByteBuffer buffer : buffers) { size += buffer.remaining(); @@ -89,7 +91,9 @@ public class ByteBufferReader { public static boolean hasRemaining(ByteBuffer... buffers) { for (ByteBuffer buf : buffers) { - if (buf.hasRemaining()) return true; + if (buf.hasRemaining()) { + return true; + } } return false; } @@ -113,10 +117,16 @@ public class ByteBufferReader { public boolean hasRemaining() { boolean v = this.currBuffer.hasRemaining(); - if (v) return v; - if (this.currIndex == this.buffers.length - 1) return false; + if (v) { + return v; + } + if (this.currIndex == this.buffers.length - 1) { + return false; + } for (int i = this.currIndex + 1; i < this.buffers.length; i++) { - if (this.buffers[i].hasRemaining()) return true; + if (this.buffers[i].hasRemaining()) { + return true; + } } return false; } @@ -150,20 +160,26 @@ public class ByteBufferReader { public short getShort() { ByteBuffer buf = this.currBuffer; int remain = buf.remaining(); - if (remain >= 2) return buf.getShort(); + if (remain >= 2) { + return buf.getShort(); + } if (remain == 0) { buf = this.buffers[++this.currIndex]; this.currBuffer = buf; return buf.getShort(); } - if (bigEndian) return (short) ((buf.get() << 8) | (get() & 0xff)); + if (bigEndian) { + return (short) ((buf.get() << 8) | (get() & 0xff)); + } return (short) ((buf.get() & 0xff) | (get() << 8)); } public int getInt() { ByteBuffer buf = this.currBuffer; int remain = buf.remaining(); - if (remain >= 4) return buf.getInt(); + if (remain >= 4) { + return buf.getInt(); + } if (remain == 0) { buf = this.buffers[++this.currIndex]; this.currBuffer = buf; @@ -214,7 +230,9 @@ public class ByteBufferReader { public long getLong() { ByteBuffer buf = this.currBuffer; int remain = buf.remaining(); - if (remain >= 8) return buf.getLong(); + if (remain >= 8) { + return buf.getLong(); + } if (remain == 0) { buf = this.buffers[++this.currIndex]; this.currBuffer = buf; diff --git a/src/main/java/org/redkale/util/ByteBufferWriter.java b/src/main/java/org/redkale/util/ByteBufferWriter.java index 5938a05e7..98c74b266 100644 --- a/src/main/java/org/redkale/util/ByteBufferWriter.java +++ b/src/main/java/org/redkale/util/ByteBufferWriter.java @@ -70,7 +70,9 @@ public class ByteBufferWriter { } public ByteBuffer[] toBuffers() { - if (buffers == null) return new ByteBuffer[0]; + if (buffers == null) { + return new ByteBuffer[0]; + } for (ByteBuffer buf : this.buffers) { buf.flip(); } @@ -189,12 +191,16 @@ public class ByteBufferWriter { int remain = buf.remaining(); if (remain >= length + length2) { buf.put(src, offset, length); - if (src2 != null) buf.put(src2, offset2, length2); + if (src2 != null) { + buf.put(src2, offset2, length2); + } position += length + length2; this.writeBytesCounter++; } else { put(true, src, offset, length); - if (src2 != null) put(false, src2, offset2, length2); + if (src2 != null) { + put(false, src2, offset2, length2); + } } return writeBytesCounter; } @@ -210,7 +216,9 @@ public class ByteBufferWriter { position += remain; put(false, src, offset + remain, length - remain); } - if (outside) this.writeBytesCounter++; + if (outside) { + this.writeBytesCounter++; + } return writeBytesCounter; } diff --git a/src/main/java/org/redkale/util/DLong.java b/src/main/java/org/redkale/util/DLong.java index 7481f6895..ed716fb81 100644 --- a/src/main/java/org/redkale/util/DLong.java +++ b/src/main/java/org/redkale/util/DLong.java @@ -5,8 +5,8 @@ */ package org.redkale.util; -import java.nio.*; -import java.util.*; +import java.nio.ByteBuffer; +import java.util.Arrays; /** * 16bytes数据结构 @@ -30,7 +30,9 @@ public final class DLong extends Number implements Comparable { } protected DLong(byte[] bytes) { - if (bytes == null || bytes.length != 16) throw new NumberFormatException("Not 16 length bytes"); + if (bytes == null || bytes.length != 16) { + throw new NumberFormatException("Not 16 length bytes"); + } this.value = bytes; } @@ -73,8 +75,12 @@ public final class DLong extends Number implements Comparable { @Override public boolean equals(Object obj) { - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } final DLong other = (DLong) obj; return Arrays.equals(this.value, other.value); } @@ -86,7 +92,9 @@ public final class DLong extends Number implements Comparable { @Override public String toString() { - if (this == ZERO) return "0"; + if (this == ZERO) { + return "0"; + } return new String(Utility.binToHex(value)); } @@ -119,9 +127,13 @@ public final class DLong extends Number implements Comparable { @Override public int compareTo(DLong o) { - if (o == null) return 1; + if (o == null) { + return 1; + } for (int i = 0; i < value.length; i++) { - if (this.value[i] != o.value[i]) return this.value[i] - o.value[i]; + if (this.value[i] != o.value[i]) { + return this.value[i] - o.value[i]; + } } return 0; } diff --git a/src/main/java/org/redkale/util/Flows.java b/src/main/java/org/redkale/util/Flows.java index d17478a16..d2f7bc02a 100644 --- a/src/main/java/org/redkale/util/Flows.java +++ b/src/main/java/org/redkale/util/Flows.java @@ -154,36 +154,64 @@ public abstract class Flows { } public static boolean maybePublisherClass(Class value) { - if (value == null) return false; + if (value == null) { + return false; + } if (reactorFluxFunction != null) { - if (reactorMonoClass.isAssignableFrom(value)) return true; - if (reactorFluxClass.isAssignableFrom(value)) return true; + if (reactorMonoClass.isAssignableFrom(value)) { + return true; + } + if (reactorFluxClass.isAssignableFrom(value)) { + return true; + } } return Flow.Publisher.class.isAssignableFrom(value); } public static Type maybePublisherSubType(Type value) { - if (value == null) return null; - if (!(value instanceof ParameterizedType)) return null; + if (value == null) { + return null; + } + if (!(value instanceof ParameterizedType)) { + return null; + } ParameterizedType pt = (ParameterizedType) value; Type parent = pt.getRawType() == null ? pt.getOwnerType() : pt.getRawType(); - if (!(parent instanceof Class)) return null; - if (pt.getActualTypeArguments().length != 1) return null; - if (reactorFluxFunction != null) { - if (reactorMonoClass.isAssignableFrom((Class) parent)) return pt.getActualTypeArguments()[0]; - if (reactorFluxClass.isAssignableFrom((Class) parent)) return pt.getActualTypeArguments()[0]; + if (!(parent instanceof Class)) { + return null; + } + if (pt.getActualTypeArguments().length != 1) { + return null; + } + if (reactorFluxFunction != null) { + if (reactorMonoClass.isAssignableFrom((Class) parent)) { + return pt.getActualTypeArguments()[0]; + } + if (reactorFluxClass.isAssignableFrom((Class) parent)) { + return pt.getActualTypeArguments()[0]; + } + } + if (Flow.Publisher.class.isAssignableFrom((Class) parent)) { + return pt.getActualTypeArguments()[0]; } - if (Flow.Publisher.class.isAssignableFrom((Class) parent)) return pt.getActualTypeArguments()[0]; return null; } public static Object maybePublisherToFuture(Object value) { - if (value == null) return value; + if (value == null) { + return value; + } if (reactorFluxFunction != null) { Class clazz = value.getClass(); - if (reactorMonoClass.isAssignableFrom(clazz)) return reactorMonoFunction.apply(value); - if (reactorFluxClass.isAssignableFrom(clazz)) return reactorFluxFunction.apply(value); - if (Flow.Publisher.class.isAssignableFrom(clazz)) return createMonoFuture((Flow.Publisher) value); + if (reactorMonoClass.isAssignableFrom(clazz)) { + return reactorMonoFunction.apply(value); + } + if (reactorFluxClass.isAssignableFrom(clazz)) { + return reactorFluxFunction.apply(value); + } + if (Flow.Publisher.class.isAssignableFrom(clazz)) { + return createMonoFuture((Flow.Publisher) value); + } } return value; } @@ -254,7 +282,9 @@ public abstract class Flows { @Override public void onNext(T item) { - if (rs == null) rs = new ArrayList<>(); + if (rs == null) { + rs = new ArrayList<>(); + } rs.add(item); } diff --git a/src/main/java/org/redkale/util/Invoker.java b/src/main/java/org/redkale/util/Invoker.java index 562b74473..55560e3e1 100644 --- a/src/main/java/org/redkale/util/Invoker.java +++ b/src/main/java/org/redkale/util/Invoker.java @@ -7,8 +7,8 @@ package org.redkale.util; import java.lang.reflect.*; import org.redkale.asm.*; -import org.redkale.asm.Type; import static org.redkale.asm.Opcodes.*; +import org.redkale.asm.Type; /** * 动态生成指定方法的调用对象, 替代Method.invoke的反射方式 @@ -154,7 +154,9 @@ public interface Invoker { mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Double", "doubleValue", "()D", false); } else { paramDescs.append(Type.getDescriptor(paramType)); - if (paramType != Object.class) mv.visitTypeInsn(CHECKCAST, paramType.getName().replace('.', '/')); + if (paramType != Object.class) { + mv.visitTypeInsn(CHECKCAST, paramType.getName().replace('.', '/')); + } } paramIndex++; } @@ -208,11 +210,13 @@ public interface Invoker { final byte[] bytes = cw.toByteArray(); Class resultClazz = null; try { - if (resultClazz == null) resultClazz = new ClassLoader(loader) { + if (resultClazz == null) { + resultClazz = new ClassLoader(loader) { public final Class loadClass(String name, byte[] b) { return defineClass(name, b, 0, b.length); } }.loadClass(newDynName.replace('/', '.'), bytes); + } RedkaleClassLoader.putDynClass(newDynName.replace('/', '.'), bytes, resultClazz); RedkaleClassLoader.putReflectionDeclaredConstructors(resultClazz, newDynName.replace('/', '.')); return (Invoker) resultClazz.getDeclaredConstructor().newInstance(); diff --git a/src/main/java/org/redkale/util/ObjectPool.java b/src/main/java/org/redkale/util/ObjectPool.java index 059307c91..03981c89b 100644 --- a/src/main/java/org/redkale/util/ObjectPool.java +++ b/src/main/java/org/redkale/util/ObjectPool.java @@ -204,19 +204,27 @@ public class ObjectPool implements Supplier, Consumer { } T result = queue.poll(); if (result == null) { - if (parent != null) result = parent.queue.poll(); + if (parent != null) { + result = parent.queue.poll(); + } if (result == null) { - if (creatCounter != null) creatCounter.increment(); + if (creatCounter != null) { + creatCounter.increment(); + } result = this.creator.create(); } } - if (prepare != null) prepare.accept(result); + if (prepare != null) { + prepare.accept(result); + } return result; } @Override public void accept(final T e) { - if (e == null) return; + if (e == null) { + return; + } if (unsafeDequeable) { if (unsafeThread == null) { unsafeThread = Thread.currentThread(); @@ -225,7 +233,9 @@ public class ObjectPool implements Supplier, Consumer { } } if (recycler.test(e)) { - if (cycleCounter != null) cycleCounter.increment(); + if (cycleCounter != null) { + cycleCounter.increment(); + } // if (debug) { // for (T t : queue) { // if (t == e) { @@ -235,7 +245,9 @@ public class ObjectPool implements Supplier, Consumer { // } // } boolean rs = unsafeDequeable ? queue.size() < max && queue.offer(e) : queue.offer(e); - if (!rs && parent != null) parent.accept(e); + if (!rs && parent != null) { + parent.accept(e); + } } } diff --git a/src/main/java/org/redkale/util/OneOrList.java b/src/main/java/org/redkale/util/OneOrList.java index e47c4b1f1..abb42ab61 100644 --- a/src/main/java/org/redkale/util/OneOrList.java +++ b/src/main/java/org/redkale/util/OneOrList.java @@ -53,7 +53,9 @@ public class OneOrList implements java.io.Serializable { //序列化 protected static Encodeable createEncoder(final org.redkale.convert.json.JsonFactory factory, final Type type) { Type itemType = parseItemType(type); - if (itemType == null) return null; + if (itemType == null) { + return null; + } Encodeable oneEncoder = factory.loadEncoder(itemType); Encodeable listEncoder = factory.loadEncoder(TypeToken.createParameterizedType(null, List.class, itemType)); return new Encodeable() { @@ -79,7 +81,9 @@ public class OneOrList implements java.io.Serializable { //反序列化 protected static Decodeable createDecoder(final org.redkale.convert.json.JsonFactory factory, final Type type) { Type itemType = parseItemType(type); - if (itemType == null) return null; + if (itemType == null) { + return null; + } Creator creator = Creator.create(type instanceof Class ? (Class) type : (Class) ((ParameterizedType) type).getRawType()); Decodeable oneDecoder = factory.loadDecoder(itemType); Decodeable listDecoder = factory.loadDecoder(TypeToken.createParameterizedType(null, List.class, itemType)); @@ -109,13 +113,17 @@ public class OneOrList implements java.io.Serializable { protected static Type parseItemType(Type type) { if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; - if (pt.getRawType() != OneOrList.class) return null; + if (pt.getRawType() != OneOrList.class) { + return null; + } return pt.getActualTypeArguments()[0]; } else if (type instanceof Class) { Class clz = (Class) type; while (clz.getSuperclass() != OneOrList.class) { clz = clz.getSuperclass(); - if (clz == Object.class) return null; + if (clz == Object.class) { + return null; + } } return ((ParameterizedType) clz.getGenericSuperclass()).getActualTypeArguments()[0]; } else { diff --git a/src/main/java/org/redkale/util/ResourceFactory.java b/src/main/java/org/redkale/util/ResourceFactory.java index f252c9858..fccda4fca 100644 --- a/src/main/java/org/redkale/util/ResourceFactory.java +++ b/src/main/java/org/redkale/util/ResourceFactory.java @@ -97,7 +97,9 @@ public final class ResourceFactory { List result = new ArrayList<>(); for (WeakReference ref : chidren) { ResourceFactory rf = ref.get(); - if (rf != null) result.add(rf); + if (rf != null) { + result.add(rf); + } } return result; } @@ -129,7 +131,9 @@ public final class ResourceFactory { public static Class getResourceType(Type type) { Class clazz = TypeToken.typeToClass(type); ResourceType rt = clazz.getAnnotation(ResourceType.class); - if (rt != null) return rt.value(); + if (rt != null) { + return rt.value(); + } org.redkale.util.ResourceType rt2 = clazz.getAnnotation(org.redkale.util.ResourceType.class); return rt2 == null ? clazz : rt2.value(); } @@ -183,7 +187,9 @@ public final class ResourceFactory { * @return 旧资源对象 */ public A register(final boolean autoSync, final A rs) { - if (rs == null) return null; + if (rs == null) { + return null; + } return (A) register(autoSync, "", rs); } @@ -390,7 +396,9 @@ public final class ResourceFactory { } else { A old = null; A t = (A) register(autoSync, name, rt, val); - if (t != null) old = t; + if (t != null) { + old = t; + } return old; } } @@ -457,7 +465,9 @@ public final class ResourceFactory { * */ public void register(Properties properties, String environmentName, Class environmentType) { - if (properties == null || properties.isEmpty()) return; + if (properties == null || properties.isEmpty()) { + return; + } List wrappers = new ArrayList<>(); List environmentEventList = new ArrayList<>(); properties.forEach((k, v) -> { @@ -478,14 +488,18 @@ public final class ResourceFactory { } } } - if (wrappers.isEmpty() && envListenMap.isEmpty()) return; + if (wrappers.isEmpty() && envListenMap.isEmpty()) { + return; + } Map> map = new LinkedHashMap<>(); for (ResourceChangeWrapper wrapper : wrappers) { map.computeIfAbsent(wrapper.dest, k -> new ArrayList<>()).add(wrapper); } if (!map.isEmpty()) { map.forEach((dest, list) -> { - if (envListenMap.containsKey(dest)) return; //跳过含有@Resource Environment字段的对象 + if (envListenMap.containsKey(dest)) { + return; //跳过含有@Resource Environment字段的对象 + } Method listener = list.get(0).listener; try { ResourceEvent[] events = new ResourceEvent[list.size()]; @@ -553,8 +567,12 @@ public final class ResourceFactory { */ public ResourceFactory findResourceFactory(String name, Type clazz) { Map map = this.store.get(clazz); - if (map != null && map.containsKey(name)) return this; - if (parent != null) return parent.findResourceFactory(name, clazz); + if (map != null && map.containsKey(name)) { + return this; + } + if (parent != null) { + return parent.findResourceFactory(name, clazz); + } return null; } @@ -574,12 +592,20 @@ public final class ResourceFactory { public A findChild(final String name, final Class clazz) { A rs = find(name, clazz); - if (rs != null) return rs; + if (rs != null) { + return rs; + } for (Map.Entry> en : this.store.entrySet()) { - if (!(en.getKey() instanceof Class)) continue; - if (!clazz.isAssignableFrom((Class) en.getKey())) continue; + if (!(en.getKey() instanceof Class)) { + continue; + } + if (!clazz.isAssignableFrom((Class) en.getKey())) { + continue; + } ResourceEntry v = en.getValue().get(name); - if (v != null) return (A) v.value; + if (v != null) { + return (A) v.value; + } } return null; } @@ -588,9 +614,13 @@ public final class ResourceFactory { Map map = this.store.get(clazz); if (map != null) { ResourceEntry re = map.get(name); - if (re != null) return re; + if (re != null) { + return re; + } + } + if (parent != null) { + return parent.findEntry(name, clazz); } - if (parent != null) return parent.findEntry(name, clazz); return null; } @@ -606,10 +636,14 @@ public final class ResourceFactory { Map map = this.store.get(clazz); if (map != null) { for (ResourceEntry re : map.values()) { - if (re.value != null) list.add((A) re.value); + if (re.value != null) { + list.add((A) re.value); + } } } - if (parent != null) parent.query(list, clazz); + if (parent != null) { + parent.query(list, clazz); + } return list; } @@ -618,7 +652,9 @@ public final class ResourceFactory { } private List query(final List list, final BiPredicate predicate) { - if (predicate == null) return list; + if (predicate == null) { + return list; + } for (ConcurrentHashMap map : this.store.values()) { for (Map.Entry en : map.entrySet()) { if (predicate.test(en.getKey(), en.getValue().value)) { @@ -626,7 +662,9 @@ public final class ResourceFactory { } } } - if (parent != null) parent.query(list, predicate); + if (parent != null) { + parent.query(list, predicate); + } return list; } @@ -634,9 +672,13 @@ public final class ResourceFactory { Map map = this.store.get(clazz); if (map != null) { ResourceEntry rs = map.get(name); - if (rs != null) return rs; + if (rs != null) { + return rs; + } + } + if (parent != null) { + return parent.findEntry(name, clazz); } - if (parent != null) return parent.findEntry(name, clazz); return null; } @@ -677,42 +719,62 @@ public final class ResourceFactory { } public static String formatResourceName(String parent, String name) { - if (name == null) return null; + if (name == null) { + return null; + } int pos = name.indexOf("{system.property."); - if (pos < 0) return (name.contains(RESOURCE_PARENT_NAME) && parent != null) ? name.replace(RESOURCE_PARENT_NAME, parent) : name; + if (pos < 0) { + return (name.contains(RESOURCE_PARENT_NAME) && parent != null) ? name.replace(RESOURCE_PARENT_NAME, parent) : name; + } String prefix = name.substring(0, pos); String subName = name.substring(pos + "{system.property.".length()); pos = subName.lastIndexOf('}'); - if (pos < 0) return (name.contains(RESOURCE_PARENT_NAME) && parent != null) ? name.replace(RESOURCE_PARENT_NAME, parent) : name; + if (pos < 0) { + return (name.contains(RESOURCE_PARENT_NAME) && parent != null) ? name.replace(RESOURCE_PARENT_NAME, parent) : name; + } String postfix = subName.substring(pos + 1); String property = subName.substring(0, pos); return formatResourceName(parent, prefix + System.getProperty(property, "") + postfix); } private boolean inject(String srcResourceName, final Object srcObj, final T attachment, final BiConsumer consumer, final List list) { - if (srcObj == null) return false; + if (srcObj == null) { + return false; + } try { list.add(srcObj); Class clazz = srcObj.getClass(); final boolean diyloaderflag = !parentRoot().resAnnotationProviderMap.isEmpty(); do { - if (java.lang.Enum.class.isAssignableFrom(clazz)) break; + if (java.lang.Enum.class.isAssignableFrom(clazz)) { + break; + } final String cname = clazz.getName(); if (cname.startsWith("java.") || cname.startsWith("javax.") - || cname.startsWith("jdk.") || cname.startsWith("sun.")) break; + || cname.startsWith("jdk.") || cname.startsWith("sun.")) { + break; + } if (cname.indexOf('/') < 0) {//排除内部类, 如:JsonConvert$$Lambda$87/0x0000000100197440- RedkaleClassLoader.putReflectionDeclaredFields(cname); } for (Field field : clazz.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) continue; + if (Modifier.isStatic(field.getModifiers())) { + continue; + } field.setAccessible(true); final Class classType = field.getType(); Resource rc1 = field.getAnnotation(Resource.class); javax.annotation.Resource rc2 = field.getAnnotation(javax.annotation.Resource.class); if (rc1 == null && rc2 == null) { //深度注入 - if (Convert.class.isAssignableFrom(classType)) continue; - if (ConvertFactory.class.isAssignableFrom(classType)) continue; - if (ResourceFactory.class.isAssignableFrom(classType)) continue; + if (Convert.class.isAssignableFrom(classType)) { + continue; + } + if (ConvertFactory.class.isAssignableFrom(classType)) { + continue; + } + if (ResourceFactory.class.isAssignableFrom(classType)) { + continue; + } boolean flag = true; //是否没有重复 Object ns = field.get(srcObj); for (Object o : list) { @@ -724,23 +786,35 @@ public final class ResourceFactory { if (flag && diyloaderflag) { parentRoot().resAnnotationProviderMap.values().stream().forEach(iloader -> { Annotation ann = field.getAnnotation(iloader.annotationType()); - if (ann == null) return; + if (ann == null) { + return; + } iloader.load(this, srcResourceName, srcObj, ann, field, attachment); }); } - if (ns == null) continue; + if (ns == null) { + continue; + } final String nsname = ns.getClass().getName(); if (ns.getClass().isPrimitive() || ns.getClass().isArray() || nsname.startsWith("java.") || nsname.startsWith("javax.") - || nsname.startsWith("jdk.") || nsname.startsWith("sun.")) continue; - if (flag) this.inject(null, ns, attachment, consumer, list); + || nsname.startsWith("jdk.") || nsname.startsWith("sun.")) { + continue; + } + if (flag) { + this.inject(null, ns, attachment, consumer, list); + } + continue; + } + if (Modifier.isFinal(field.getModifiers())) { continue; } - if (Modifier.isFinal(field.getModifiers())) continue; RedkaleClassLoader.putReflectionField(cname, field); final Type gencType = TypeToken.containsUnknownType(field.getGenericType()) ? TypeToken.getGenericType(field.getGenericType(), srcObj.getClass()) : field.getGenericType(); - if (consumer != null) consumer.accept(srcObj, field); + if (consumer != null) { + consumer.accept(srcObj, field); + } String tname = rc1 == null ? rc2.name() : rc1.name(); if (tname.contains(RESOURCE_PARENT_NAME)) { Resource res1 = srcObj.getClass().getAnnotation(Resource.class); @@ -848,7 +922,9 @@ public final class ResourceFactory { rs = new BigInteger(rs.toString()); } } - if (rs != null) field.set(srcObj, rs); + if (rs != null) { + field.set(srcObj, rs); + } if (rs == null && !skipCheckRequired && rc1 != null && rc1.required()) { throw new ResourceInjectException("resource(type=" + field.getType().getSimpleName() + ".class, field=" + field.getName() + ", name='" + rcname + "') must exists in " + srcObj.getClass().getName()); } @@ -864,12 +940,16 @@ public final class ResourceFactory { } public void register(final ResourceAnnotationProvider loader) { - if (loader == null) return; + if (loader == null) { + return; + } parentRoot().resAnnotationProviderMap.put(loader.annotationType(), loader); } public void register(final ResourceTypeLoader rs, final Type... clazzs) { - if (clazzs == null || rs == null) return; + if (clazzs == null || rs == null) { + return; + } for (Type clazz : clazzs) { resTypeLoaderMap.put(clazz, rs); } @@ -877,29 +957,43 @@ public final class ResourceFactory { public ResourceTypeLoader findResourceTypeLoader(Type clazz) { ResourceTypeLoader it = this.resTypeLoaderMap.get(clazz); - if (it != null) return it; + if (it != null) { + return it; + } return parent == null ? null : parent.findResourceTypeLoader(clazz); } private ResourceFactory parentRoot() { - if (parent == null) return this; + if (parent == null) { + return this; + } return parent.parentRoot(); } private ResourceTypeLoader findMatchTypeLoader(Type ft, Field field) { ResourceTypeLoader it = this.resTypeLoaderMap.get(ft); - if (it == null && field != null) it = this.resTypeLoaderMap.get(field.getType()); - if (it != null) return it; + if (it == null && field != null) { + it = this.resTypeLoaderMap.get(field.getType()); + } + if (it != null) { + return it; + } return parent == null ? null : parent.findMatchTypeLoader(ft, field); } private ResourceTypeLoader findRegxTypeLoader(Type ft, Field field) { - if (field == null) return null; + if (field == null) { + return null; + } Class c = field.getType(); for (Map.Entry en : this.resTypeLoaderMap.entrySet()) { Type t = en.getKey(); - if (t == ft) return en.getValue(); - if (t instanceof Class && (((Class) t)).isAssignableFrom(c)) return en.getValue(); + if (t == ft) { + return en.getValue(); + } + if (t instanceof Class && (((Class) t)).isAssignableFrom(c)) { + return en.getValue(); + } } return parent == null ? null : parent.findRegxTypeLoader(ft, field); } @@ -950,7 +1044,9 @@ public final class ResourceFactory { if (sync && elements != null && !elements.isEmpty()) { for (ResourceElement element : elements) { Object dest = element.dest.get(); - if (dest == null) continue; //依赖对象可能被销毁了 + if (dest == null) { + continue; //依赖对象可能被销毁了 + } Object newVal = value; final Class classType = element.fieldType; if (newVal != null && !newVal.getClass().isPrimitive() && (classType.isPrimitive() || Number.class.isAssignableFrom(classType))) { @@ -974,7 +1070,9 @@ public final class ResourceFactory { newVal = new BigDecimal(newVal.toString()); } } - if (newVal == null && classType.isPrimitive()) newVal = Array.get(Array.newInstance(classType, 1), 0); + if (newVal == null && classType.isPrimitive()) { + newVal = Array.get(Array.newInstance(classType, 1), 0); + } Object oldVal = null; if (element.listener != null) { try { @@ -1036,13 +1134,17 @@ public final class ResourceFactory { synchronized (listenerMethods) { Class loop = clazz; Method m = listenerMethods.get(clazz.getName() + "-" + fieldType.getName()); - if (m != null) return m; + if (m != null) { + return m; + } do { RedkaleClassLoader.putReflectionDeclaredMethods(loop.getName()); for (Method method : loop.getDeclaredMethods()) { ResourceListener rl = method.getAnnotation(ResourceListener.class); org.redkale.util.ResourceListener rl2 = method.getAnnotation(org.redkale.util.ResourceListener.class); - if (rl == null && rl2 == null) continue; + if (rl == null && rl2 == null) { + continue; + } if (method.getParameterCount() == 1 && method.getParameterTypes()[0] == ResourceEvent[].class) { m = method; m.setAccessible(true); @@ -1088,11 +1190,19 @@ public final class ResourceFactory { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } final ResourceChangeWrapper other = (ResourceChangeWrapper) obj; - if (!Objects.equals(this.dest, other.dest)) return false; + if (!Objects.equals(this.dest, other.dest)) { + return false; + } return Objects.equals(this.listener, other.listener); } diff --git a/src/main/java/org/redkale/util/SelectColumn.java b/src/main/java/org/redkale/util/SelectColumn.java index c819e0449..927cb8998 100644 --- a/src/main/java/org/redkale/util/SelectColumn.java +++ b/src/main/java/org/redkale/util/SelectColumn.java @@ -5,9 +5,9 @@ */ package org.redkale.util; -import java.util.*; -import java.util.function.*; -import java.util.regex.*; +import java.util.Arrays; +import java.util.function.Predicate; +import java.util.regex.Pattern; /** * 判断字符串数组是否包含或排除指定字符串的操作类 @@ -31,7 +31,9 @@ public class SelectColumn implements Predicate { protected SelectColumn(final String[] columns0, final boolean excludable) { this.excludable = excludable; final int len = columns0.length; - if (len < 1) return; + if (len < 1) { + return; + } Pattern[] regs = null; String[] cols = null; int regcount = 0; @@ -46,10 +48,14 @@ public class SelectColumn implements Predicate { } } if (reg) { - if (regs == null) regs = new Pattern[len]; + if (regs == null) { + regs = new Pattern[len]; + } regs[regcount++] = Pattern.compile(col); } else { - if (cols == null) cols = new String[len]; + if (cols == null) { + cols = new String[len]; + } cols[colcount++] = col; } } @@ -80,7 +86,6 @@ public class SelectColumn implements Predicate { // public static SelectColumn createIncludes(String... columns) { // return new SelectColumn(columns, false); // } - /** * class中的字段名 * @@ -104,7 +109,6 @@ public class SelectColumn implements Predicate { // public static SelectColumn createIncludes(String[] cols, String... columns) { // return new SelectColumn(Utility.append(cols, columns), false); // } - /** * class中的字段名 * @@ -129,7 +133,6 @@ public class SelectColumn implements Predicate { // public static SelectColumn createExcludes(String... columns) { // return new SelectColumn(columns, true); // } - /** * class中的字段名 * @@ -153,7 +156,6 @@ public class SelectColumn implements Predicate { // public static SelectColumn createExcludes(String[] cols, String... columns) { // return new SelectColumn(Utility.append(cols, columns), true); // } - /** * * class中的字段名 @@ -175,12 +177,16 @@ public class SelectColumn implements Predicate { public boolean test(final String column) { if (this.columns != null) { for (String col : this.columns) { - if (col.equalsIgnoreCase(column)) return !excludable; + if (col.equalsIgnoreCase(column)) { + return !excludable; + } } } if (this.patterns != null) { for (Pattern reg : this.patterns) { - if (reg.matcher(column).find()) return !excludable; + if (reg.matcher(column).find()) { + return !excludable; + } } } return excludable; @@ -214,8 +220,12 @@ public class SelectColumn implements Predicate { public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("{excludable=").append(excludable); - if (columns != null) sb.append(", columns=").append(Arrays.toString(columns)); - if (patterns != null) sb.append(", patterns=").append(Arrays.toString(patterns)); + if (columns != null) { + sb.append(", columns=").append(Arrays.toString(columns)); + } + if (patterns != null) { + sb.append(", patterns=").append(Arrays.toString(patterns)); + } return sb.append('}').toString(); } diff --git a/src/main/java/org/redkale/util/Traces.java b/src/main/java/org/redkale/util/Traces.java index 83f2ddefc..c3be5e082 100644 --- a/src/main/java/org/redkale/util/Traces.java +++ b/src/main/java/org/redkale/util/Traces.java @@ -49,7 +49,6 @@ public class Traces { // } // return traceid; // } - public static void currTraceid(String traceid) { if (enable) { localTrace.set(traceid); diff --git a/src/main/java/org/redkale/util/TypeToken.java b/src/main/java/org/redkale/util/TypeToken.java index c370ec95e..78a08dbd4 100644 --- a/src/main/java/org/redkale/util/TypeToken.java +++ b/src/main/java/org/redkale/util/TypeToken.java @@ -7,8 +7,8 @@ package org.redkale.util; import java.lang.reflect.Type; import java.lang.reflect.*; import java.util.*; -import org.redkale.asm.*; import static org.redkale.asm.ClassWriter.COMPUTE_FRAMES; +import org.redkale.asm.*; import static org.redkale.asm.Opcodes.*; /** @@ -43,34 +43,66 @@ public abstract class TypeToken { * @return 是否可反解析 */ public final static boolean isClassType(final Type type) { - if (type instanceof Class) return true; - if (type instanceof WildcardType) return false; - if (type instanceof TypeVariable) return false; - if (type instanceof GenericArrayType) return isClassType(((GenericArrayType) type).getGenericComponentType()); - if (!(type instanceof ParameterizedType)) return false; //只能是null了 + if (type instanceof Class) { + return true; + } + if (type instanceof WildcardType) { + return false; + } + if (type instanceof TypeVariable) { + return false; + } + if (type instanceof GenericArrayType) { + return isClassType(((GenericArrayType) type).getGenericComponentType()); + } + if (!(type instanceof ParameterizedType)) { + return false; //只能是null了 + } final ParameterizedType ptype = (ParameterizedType) type; - if (ptype.getOwnerType() != null && !isClassType(ptype.getOwnerType())) return false; - if (!isClassType(ptype.getRawType())) return false; + if (ptype.getOwnerType() != null && !isClassType(ptype.getOwnerType())) { + return false; + } + if (!isClassType(ptype.getRawType())) { + return false; + } for (Type t : ptype.getActualTypeArguments()) { - if (!isClassType(t)) return false; + if (!isClassType(t)) { + return false; + } } return true; } public final static boolean containsUnknownType(final Type type) { - if (type == null) return false; - if (type instanceof Class) return false; - if (type instanceof WildcardType) return true; - if (type instanceof TypeVariable) return true; - if (type instanceof GenericArrayType) return containsUnknownType(((GenericArrayType) type).getGenericComponentType()); + if (type == null) { + return false; + } + if (type instanceof Class) { + return false; + } + if (type instanceof WildcardType) { + return true; + } + if (type instanceof TypeVariable) { + return true; + } + if (type instanceof GenericArrayType) { + return containsUnknownType(((GenericArrayType) type).getGenericComponentType()); + } if (type instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) type; - if (containsUnknownType(pt.getRawType())) return true; - if (containsUnknownType(pt.getOwnerType())) return true; + if (containsUnknownType(pt.getRawType())) { + return true; + } + if (containsUnknownType(pt.getOwnerType())) { + return true; + } Type[] ts = pt.getActualTypeArguments(); if (ts != null) { for (Type t : ts) { - if (containsUnknownType(t)) return true; + if (containsUnknownType(t)) { + return true; + } } } return false; @@ -79,11 +111,21 @@ public abstract class TypeToken { } public final static Class typeToClass(final Type type) { - if (type instanceof Class) return (Class) type; - if (type instanceof WildcardType) return null; - if (type instanceof TypeVariable) return null; - if (type instanceof GenericArrayType) return Array.newInstance(typeToClass(((GenericArrayType) type).getGenericComponentType()), 0).getClass(); - if (!(type instanceof ParameterizedType)) return null; //只能是null了 + if (type instanceof Class) { + return (Class) type; + } + if (type instanceof WildcardType) { + return null; + } + if (type instanceof TypeVariable) { + return null; + } + if (type instanceof GenericArrayType) { + return Array.newInstance(typeToClass(((GenericArrayType) type).getGenericComponentType()), 0).getClass(); + } + if (!(type instanceof ParameterizedType)) { + return null; //只能是null了 + } Type owner = ((ParameterizedType) type).getOwnerType(); Type raw = ((ParameterizedType) type).getRawType(); //A$B owner=A raw=A$B, 所以内部类情况下使用owner是错误的 @@ -207,7 +249,9 @@ public abstract class TypeToken { * @return Type */ public static Type getGenericType(final Type type, final Type declaringClass) { - if (type == null || declaringClass == null) return type; + if (type == null || declaringClass == null) { + return type; + } if (type instanceof TypeVariable) { Type superType = null; Class declaringClass0 = null; @@ -218,13 +262,17 @@ public abstract class TypeToken { Map map = new HashMap<>(); parseType(map, declaringClass0); Type rstype = getType(map, type); - if (rstype instanceof Class) return rstype; + if (rstype instanceof Class) { + return rstype; + } } while (superType instanceof Class && superType != Object.class) superType = ((Class) superType).getGenericSuperclass(); } else if (declaringClass instanceof ParameterizedType) { superType = declaringClass; Type rawType = ((ParameterizedType) declaringClass).getRawType(); - if (rawType instanceof Class) declaringClass0 = (Class) rawType; + if (rawType instanceof Class) { + declaringClass0 = (Class) rawType; + } } if (declaringClass0 != null && superType instanceof ParameterizedType) { ParameterizedType superPT = (ParameterizedType) superType; @@ -245,10 +293,14 @@ public abstract class TypeToken { Class raw = (Class) superPT.getRawType(); do { Type rawsuper = raw.getGenericSuperclass(); - if (!(rawsuper instanceof ParameterizedType)) break; + if (!(rawsuper instanceof ParameterizedType)) { + break; + } ParameterizedType rpt = (ParameterizedType) rawsuper; Type supraw = rpt.getRawType(); - if (!(supraw instanceof Class)) break; + if (!(supraw instanceof Class)) { + break; + } Type[] tps = ((Class) supraw).getTypeParameters(); if (rpt.getActualTypeArguments().length == tps.length) { for (int k = 0; k < rpt.getActualTypeArguments().length; k++) { @@ -259,7 +311,9 @@ public abstract class TypeToken { } } Type rtrt = rpt.getRawType(); - if (!(rtrt instanceof Class)) break; + if (!(rtrt instanceof Class)) { + break; + } raw = (Class) rtrt; } while (raw != Object.class); } @@ -268,8 +322,9 @@ public abstract class TypeToken { if (atas[i] instanceof Class && ((TypeVariable) type).getBounds().length == 1 && ((TypeVariable) type).getBounds()[0] instanceof Class - && ((Class) ((TypeVariable) type).getBounds()[0]).isAssignableFrom((Class) atas[i])) + && ((Class) ((TypeVariable) type).getBounds()[0]).isAssignableFrom((Class) atas[i])) { return atas[i]; + } if (atas[i] instanceof Class && ((TypeVariable) type).getBounds().length == 1 && ((TypeVariable) type).getBounds()[0] instanceof ParameterizedType) { @@ -280,8 +335,9 @@ public abstract class TypeToken { } if (atas[i] instanceof ParameterizedType && ((TypeVariable) type).getBounds().length == 1 - && ((TypeVariable) type).getBounds()[0] == Object.class) + && ((TypeVariable) type).getBounds()[0] == Object.class) { return atas[i]; + } } } ParameterizedType cycType = superPT; @@ -292,18 +348,23 @@ public abstract class TypeToken { if (argTypes[i] == type) { if (atas[i] instanceof TypeVariable && ((TypeVariable) atas[i]).getBounds().length == 1 - && ((TypeVariable) atas[i]).getBounds()[0] instanceof Class) + && ((TypeVariable) atas[i]).getBounds()[0] instanceof Class) { return ((Class) ((TypeVariable) atas[i]).getBounds()[0]); + } } } } } } Type moreType = ((ParameterizedType) superType).getRawType(); - if (moreType != Object.class) return getGenericType(type, moreType); + if (moreType != Object.class) { + return getGenericType(type, moreType); + } } TypeVariable tv = (TypeVariable) type; - if (tv.getBounds().length == 1) return tv.getBounds()[0]; + if (tv.getBounds().length == 1) { + return tv.getBounds()[0]; + } } else if (type instanceof GenericArrayType) { final Type rst = getGenericType(((GenericArrayType) type).getGenericComponentType(), declaringClass); return (GenericArrayType) () -> rst; @@ -319,23 +380,35 @@ public abstract class TypeToken { private static Type getType(Map map, Type type) { Type one = map.get(type); - if (one == null) return type; + if (one == null) { + return type; + } return getType(map, one); } private static Map parseType(Map map, Class clzz) { - if (clzz == Object.class) return map; + if (clzz == Object.class) { + return map; + } Type superType = clzz.getGenericSuperclass(); - if (!(superType instanceof ParameterizedType)) return map; + if (!(superType instanceof ParameterizedType)) { + return map; + } ParameterizedType pt = (ParameterizedType) superType; Type[] ptt = pt.getActualTypeArguments(); Type superRaw = pt.getRawType(); - if (!(superRaw instanceof Class)) return map; + if (!(superRaw instanceof Class)) { + return map; + } Class superClazz = (Class) superRaw; TypeVariable[] scs = superClazz.getTypeParameters(); - if (scs.length != ptt.length) return map; + if (scs.length != ptt.length) { + return map; + } for (int i = 0; i < scs.length; i++) { - if (scs[i] == ptt[i]) continue; + if (scs[i] == ptt[i]) { + continue; + } map.put(scs[i], ptt[i]); } return parseType(map, clzz.getSuperclass()); @@ -350,7 +423,9 @@ public abstract class TypeToken { * @return Type */ public static Type createClassType(final Type type, final Type declaringType0) { - if (isClassType(type)) return type; + if (isClassType(type)) { + return type; + } if (type instanceof ParameterizedType) { // e.g. Map final ParameterizedType pt = (ParameterizedType) type; final Type[] paramTypes = pt.getActualTypeArguments(); @@ -363,11 +438,15 @@ public abstract class TypeToken { if (declaringType instanceof Class) { do { declaringType = ((Class) declaringType).getGenericSuperclass(); - if (declaringType == Object.class) return Object.class; + if (declaringType == Object.class) { + return Object.class; + } } while (declaringType instanceof Class); } //存在通配符则declaringType 必须是 ParameterizedType - if (!(declaringType instanceof ParameterizedType)) return Object.class; + if (!(declaringType instanceof ParameterizedType)) { + return Object.class; + } final ParameterizedType declaringPType = (ParameterizedType) declaringType; final Type[] virTypes = ((Class) declaringPType.getRawType()).getTypeParameters(); final Type[] desTypes = declaringPType.getActualTypeArguments(); @@ -375,12 +454,16 @@ public abstract class TypeToken { final WildcardType wt = (WildcardType) type; for (Type f : wt.getUpperBounds()) { for (int i = 0; i < virTypes.length; i++) { - if (virTypes[i].equals(f)) return desTypes.length <= i ? Object.class : desTypes[i]; + if (virTypes[i].equals(f)) { + return desTypes.length <= i ? Object.class : desTypes[i]; + } } } } else if (type instanceof TypeVariable) { // e.g. for (int i = 0; i < virTypes.length; i++) { - if (virTypes[i].equals(type)) return desTypes.length <= i ? Object.class : desTypes[i]; + if (virTypes[i].equals(type)) { + return desTypes.length <= i ? Object.class : desTypes[i]; + } } } return type; @@ -399,9 +482,13 @@ public abstract class TypeToken { if (ownerType0 == null && rawType0 instanceof Class) { int count = 0; for (Type t : actualTypeArguments0) { - if (isClassType(t)) count++; + if (isClassType(t)) { + count++; + } + } + if (count == actualTypeArguments0.length) { + return createParameterizedType0((Class) rawType0, actualTypeArguments0); } - if (count == actualTypeArguments0.length) return createParameterizedType0((Class) rawType0, actualTypeArguments0); } return new ParameterizedType() { private final Class rawType = (Class) rawType0; @@ -432,9 +519,13 @@ public abstract class TypeToken { @Override public boolean equals(Object o) { - if (!(o instanceof ParameterizedType)) return false; + if (!(o instanceof ParameterizedType)) { + return false; + } final ParameterizedType that = (ParameterizedType) o; - if (this == that) return true; + if (this == that) { + return true; + } return Objects.equals(ownerType, that.getOwnerType()) && Objects.equals(rawType, that.getRawType()) && Arrays.equals(actualTypeArguments, that.getActualTypeArguments()); @@ -443,14 +534,18 @@ public abstract class TypeToken { @Override public String toString() { StringBuilder sb = new StringBuilder(); - if (ownerType != null) sb.append((ownerType instanceof Class) ? (((Class) ownerType).getName()) : ownerType.toString()).append("."); + if (ownerType != null) { + sb.append((ownerType instanceof Class) ? (((Class) ownerType).getName()) : ownerType.toString()).append("."); + } sb.append(rawType.getName()); if (actualTypeArguments != null && actualTypeArguments.length > 0) { sb.append("<"); boolean first = true; for (Type t : actualTypeArguments) { - if (!first) sb.append(", "); + if (!first) { + sb.append(", "); + } sb.append(t); first = false; } @@ -527,9 +622,15 @@ public abstract class TypeToken { } private static CharSequence getClassTypeDescriptor(Type type) { - if (!isClassType(type)) throw new IllegalArgumentException(type + " not a class type"); - if (type instanceof Class) return org.redkale.asm.Type.getDescriptor((Class) type); - if (type instanceof GenericArrayType) return getClassTypeDescriptor(((GenericArrayType) type).getGenericComponentType()) + "[]"; + if (!isClassType(type)) { + throw new IllegalArgumentException(type + " not a class type"); + } + if (type instanceof Class) { + return org.redkale.asm.Type.getDescriptor((Class) type); + } + if (type instanceof GenericArrayType) { + return getClassTypeDescriptor(((GenericArrayType) type).getGenericComponentType()) + "[]"; + } final ParameterizedType pt = (ParameterizedType) type; CharSequence rawTypeDesc = getClassTypeDescriptor(pt.getRawType()); StringBuilder sb = new StringBuilder(); diff --git a/src/main/java/org/redkale/util/Utility.java b/src/main/java/org/redkale/util/Utility.java index c97da91f4..1f46d4830 100644 --- a/src/main/java/org/redkale/util/Utility.java +++ b/src/main/java/org/redkale/util/Utility.java @@ -221,8 +221,12 @@ public final class Utility { * @throws IllegalArgumentException is value is more than MAX_POW2 or less than 0 */ public static int roundToPowerOfTwo(final int value) { - if (value > MAX_POW2) throw new IllegalArgumentException("There is no larger power of 2 int for value:" + value + " since it exceeds 2^31."); - if (value < 0) throw new IllegalArgumentException("Given value:" + value + ". Expecting value >= 0."); + if (value > MAX_POW2) { + throw new IllegalArgumentException("There is no larger power of 2 int for value:" + value + " since it exceeds 2^31."); + } + if (value < 0) { + throw new IllegalArgumentException("Given value:" + value + ". Expecting value >= 0."); + } return 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); } @@ -231,12 +235,22 @@ public final class Utility { } public static boolean isRecordGetter(Class clazz, Method method) { - if (JAVA_RECORD_CLASS == null) return false; - if (method.getReturnType() == void.class) return false; - if (method.getParameterCount() != 0) return false; - if (method.getName().equals("getClass")) return false; + if (JAVA_RECORD_CLASS == null) { + return false; + } + if (method.getReturnType() == void.class) { + return false; + } + if (method.getParameterCount() != 0) { + return false; + } + if (method.getName().equals("getClass")) { + return false; + } Class clz = (clazz == null ? method.getDeclaringClass() : clazz); - if (!JAVA_RECORD_CLASS.isAssignableFrom(clz)) return false; + if (!JAVA_RECORD_CLASS.isAssignableFrom(clz)) { + return false; + } try { return clz.getDeclaredField(method.getName()).getType() == method.getReturnType(); } catch (Throwable t) { @@ -520,7 +534,9 @@ public final class Utility { * @return List */ public static List limit(List list, int limit) { - if (list == null || list.isEmpty() || list.size() <= limit) return list; + if (list == null || list.isEmpty() || list.size() <= limit) { + return list; + } return list.subList(0, limit); } @@ -543,7 +559,9 @@ public final class Utility { * @return 新数组 */ public static T[] unshift(final T[] array, final T... objs) { - if (array == null || array.length == 0) return objs; + if (array == null || array.length == 0) { + return objs; + } final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.length); System.arraycopy(objs, 0, news, 0, objs.length); System.arraycopy(array, 0, news, objs.length, array.length); @@ -560,14 +578,20 @@ public final class Utility { * @return 新数组 */ public static T[] unshift(final T[] array, final Collection objs) { - if (objs == null || objs.isEmpty()) return array; + if (objs == null || objs.isEmpty()) { + return array; + } if (array == null) { T one = null; for (T t : objs) { - if (t != null) one = t; + if (t != null) { + one = t; + } break; } - if (one == null) return array; + if (one == null) { + return array; + } T[] news = (T[]) Array.newInstance(one.getClass(), objs.size()); return objs.toArray(news); } @@ -601,7 +625,9 @@ public final class Utility { */ public static int sum(boolean check, final int... array) { if (array == null || array.length == 0) { - if (!check) return 0; + if (!check) { + return 0; + } throw new NullPointerException("array is null or empty"); } int sum = 0; @@ -632,7 +658,9 @@ public final class Utility { */ public static long sum(boolean check, final long... array) { if (array == null || array.length == 0) { - if (!check) return 0; + if (!check) { + return 0; + } throw new NullPointerException("array is null or empty"); } long sum = 0L; @@ -650,10 +678,14 @@ public final class Utility { * @return int */ public static int max(final int... array) { - if (array == null || array.length == 0) throw new NullPointerException("array is null or empty"); + if (array == null || array.length == 0) { + throw new NullPointerException("array is null or empty"); + } int max = array[0]; for (int i : array) { - if (i > max) i = max; + if (i > max) { + i = max; + } } return max; } @@ -666,10 +698,14 @@ public final class Utility { * @return long */ public static long max(final long... array) { - if (array == null || array.length == 0) throw new NullPointerException("array is null or empty"); + if (array == null || array.length == 0) { + throw new NullPointerException("array is null or empty"); + } long max = array[0]; for (long i : array) { - if (i > max) i = max; + if (i > max) { + i = max; + } } return max; } @@ -682,10 +718,14 @@ public final class Utility { * @return int */ public static long min(final int... array) { - if (array == null || array.length == 0) throw new NullPointerException("array is null or empty"); + if (array == null || array.length == 0) { + throw new NullPointerException("array is null or empty"); + } int min = array[0]; for (int i : array) { - if (i < min) i = min; + if (i < min) { + i = min; + } } return min; } @@ -698,10 +738,14 @@ public final class Utility { * @return long */ public static long min(final long... array) { - if (array == null || array.length == 0) throw new NullPointerException("array is null or empty"); + if (array == null || array.length == 0) { + throw new NullPointerException("array is null or empty"); + } long min = array[0]; for (long i : array) { - if (i < min) i = min; + if (i < min) { + i = min; + } } return min; } @@ -715,10 +759,14 @@ public final class Utility { * @return String */ public static String joining(final char[] array, final String delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (char i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); } return sb.toString(); @@ -733,10 +781,14 @@ public final class Utility { * @return String */ public static String joining(final int[] array, final String delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (int i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); } return sb.toString(); @@ -751,10 +803,14 @@ public final class Utility { * @return String */ public static String joining(final long[] array, final String delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (long i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); } return sb.toString(); @@ -770,10 +826,14 @@ public final class Utility { * @return String */ public static String joining(final T[] array, final String delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (T i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); } return sb.toString(); @@ -789,10 +849,14 @@ public final class Utility { * @return String */ public static String joining(final Stream stream, final String delimiter) { - if (stream == null) return ""; + if (stream == null) { + return ""; + } StringBuilder sb = new StringBuilder(); stream.forEach(i -> { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); }); return sb.toString(); @@ -808,10 +872,14 @@ public final class Utility { * @return String */ public static String joining(final String[] array, final char delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (String i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } sb.append(i); } return sb.toString(); @@ -827,10 +895,14 @@ public final class Utility { * @return String */ public static String joiningHex(final byte[] array, final char delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); for (byte i : array) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } String s = Integer.toHexString(i & 0xff); sb.append(s.length() > 1 ? "0x" : "0x0").append(s); } @@ -849,11 +921,15 @@ public final class Utility { * @return String */ public static String joiningHex(final byte[] array, int offset, int length, final char delimiter) { - if (array == null || array.length == 0) return ""; + if (array == null || array.length == 0) { + return ""; + } StringBuilder sb = new StringBuilder(); int len = offset + length; for (int i = offset; i < len; i++) { - if (sb.length() > 0) sb.append(delimiter); + if (sb.length() > 0) { + sb.append(delimiter); + } String s = Integer.toHexString(array[i] & 0xff); sb.append(s.length() > 1 ? "0x" : "0x0").append(s); } @@ -869,8 +945,12 @@ public final class Utility { * @return 新数组 */ public static byte[] append(final byte[] array, final byte... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final byte[] news = new byte[array.length + objs.length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -889,12 +969,16 @@ public final class Utility { */ public static byte[] append(final byte[] array, final byte[] objs, int offset, int length) { if (array == null || array.length == 0) { - if (objs != null && offset == 0 && objs.length == length) return objs; + if (objs != null && offset == 0 && objs.length == length) { + return objs; + } final byte[] news = new byte[length]; System.arraycopy(objs, 0, news, 0, length); return news; } - if (objs == null || length == 0) return array; + if (objs == null || length == 0) { + return array; + } final byte[] news = new byte[array.length + length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, offset, news, array.length, length); @@ -910,8 +994,12 @@ public final class Utility { * @return 新数组 */ public static short[] append(final short[] array, final short... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final short[] news = new short[array.length + objs.length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -927,8 +1015,12 @@ public final class Utility { * @return 新数组 */ public static char[] append(final char[] array, final char... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final char[] news = new char[array.length + objs.length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -944,8 +1036,12 @@ public final class Utility { * @return 新数组 */ public static int[] append(final int[] array, final int... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final int[] news = new int[array.length + objs.length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -961,8 +1057,12 @@ public final class Utility { * @return 新数组 */ public static long[] append(final long[] array, final long... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final long[] news = new long[array.length + objs.length]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -979,8 +1079,12 @@ public final class Utility { * @return 新数组 */ public static T[] append(final T[] array, final T... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.length); System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -997,8 +1101,12 @@ public final class Utility { * @return 新数组 */ public static Object[][] append(final Object[][] array, final Object[]... objs) { - if (array == null || array.length == 0) return objs; - if (objs == null || objs.length == 0) return array; + if (array == null || array.length == 0) { + return objs; + } + if (objs == null || objs.length == 0) { + return array; + } final Object[][] news = new Object[array.length + objs.length][]; System.arraycopy(array, 0, news, 0, array.length); System.arraycopy(objs, 0, news, array.length, objs.length); @@ -1015,14 +1123,20 @@ public final class Utility { * @return 新数组 */ public static T[] append(final T[] array, final Collection objs) { - if (objs == null || objs.isEmpty()) return array; + if (objs == null || objs.isEmpty()) { + return array; + } if (array == null) { T one = null; for (T t : objs) { - if (t != null) one = t; + if (t != null) { + one = t; + } break; } - if (one == null) return array; + if (one == null) { + return array; + } T[] news = (T[]) Array.newInstance(one.getClass(), objs.size()); return objs.toArray(news); } @@ -1043,7 +1157,9 @@ public final class Utility { * @return 新数组 */ public static int[] reverseSort(final int[] array) { - if (array == null || array.length == 0) return array; + if (array == null || array.length == 0) { + return array; + } return Arrays.stream(array).boxed().sorted(Collections.reverseOrder()).mapToInt(x -> x).toArray(); } @@ -1055,7 +1171,9 @@ public final class Utility { * @return 新数组 */ public static long[] reverseSort(final long[] array) { - if (array == null || array.length == 0) return array; + if (array == null || array.length == 0) { + return array; + } return Arrays.stream(array).boxed().sorted(Collections.reverseOrder()).mapToLong(x -> x).toArray(); } @@ -1082,7 +1200,9 @@ public final class Utility { * @return 新数组 */ public static T[] remove(final T[] array, final Predicate filter) { - if (array == null || array.length == 0 || filter == null) return array; + if (array == null || array.length == 0 || filter == null) { + return array; + } final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length); int index = 0; for (int i = 0; i < news.length; i++) { @@ -1090,7 +1210,9 @@ public final class Utility { news[index++] = array[i]; } } - if (index == array.length) return array; + if (index == array.length) { + return array; + } final T[] rs = (T[]) Array.newInstance(array.getClass().getComponentType(), index); System.arraycopy(news, 0, rs, 0, index); return rs; @@ -1105,7 +1227,9 @@ public final class Utility { * @return 新数组 */ public static String[] remove(final String[] array, final String item) { - if (array == null || array.length == 0) return array; + if (array == null || array.length == 0) { + return array; + } final String[] news = new String[array.length]; int index = 0; for (int i = 0; i < news.length; i++) { @@ -1115,7 +1239,9 @@ public final class Utility { news[index++] = array[i]; } } - if (index == array.length) return array; + if (index == array.length) { + return array; + } final String[] rs = new String[index]; System.arraycopy(news, 0, rs, 0, index); return rs; @@ -1148,7 +1274,9 @@ public final class Utility { * @return 新数组 */ public static short[] remove(final short[] array, boolean repeat, final short... items) { - if (array == null || array.length == 0 || items == null || items.length == 0) return array; + if (array == null || array.length == 0 || items == null || items.length == 0) { + return array; + } final short[] news = new short[array.length]; short[] subs = items; int index = 0; @@ -1173,7 +1301,9 @@ public final class Utility { news[index++] = array[i]; } } - if (index == array.length) return array; + if (index == array.length) { + return array; + } final short[] rs = new short[index]; System.arraycopy(news, 0, rs, 0, index); return rs; @@ -1206,7 +1336,9 @@ public final class Utility { * @return 新数组 */ public static int[] remove(final int[] array, boolean repeat, final int... items) { - if (array == null || array.length == 0 || items == null || items.length == 0) return array; + if (array == null || array.length == 0 || items == null || items.length == 0) { + return array; + } final int[] news = new int[array.length]; int[] subs = items; int index = 0; @@ -1231,7 +1363,9 @@ public final class Utility { news[index++] = array[i]; } } - if (index == array.length) return array; + if (index == array.length) { + return array; + } final int[] rs = new int[index]; System.arraycopy(news, 0, rs, 0, index); return rs; @@ -1291,7 +1425,9 @@ public final class Utility { news[index++] = array[i]; } } - if (index == array.length) return array; + if (index == array.length) { + return array; + } final long[] rs = new long[index]; System.arraycopy(news, 0, rs, 0, index); return rs; @@ -1331,10 +1467,14 @@ public final class Utility { * @return boolean */ public static boolean contains(String string, char... values) { - if (string == null) return false; + if (string == null) { + return false; + } for (char ch : Utility.charArray(string)) { for (char ch2 : values) { - if (ch == ch2) return true; + if (ch == ch2) { + return true; + } } } return false; @@ -1350,9 +1490,15 @@ public final class Utility { * @return 元素是否完全相同 */ public static boolean equalsElement(T[] array1, T[] array2) { - if (array1 == null && array2 == null) return true; - if (array1 == null || array2 == null) return false; - if (array1.length != array2.length) return false; + if (array1 == null && array2 == null) { + return true; + } + if (array1 == null || array2 == null) { + return false; + } + if (array1.length != array2.length) { + return false; + } return equalsElement(ofList(array1), ofList(array2)); } @@ -1366,13 +1512,21 @@ public final class Utility { * @return 元素是否完全相同 */ public static boolean equalsElement(Collection col1, Collection col2) { - if (col1 == null && col2 == null) return true; - if (col1 == null || col2 == null) return false; - if (col1.size() != col2.size()) return false; + if (col1 == null && col2 == null) { + return true; + } + if (col1 == null || col2 == null) { + return false; + } + if (col1.size() != col2.size()) { + return false; + } //{1,2,2}, {1,1,2} List list = new ArrayList<>(col2); for (T item : col1) { - if (!list.remove(item)) return false; + if (!list.remove(item)) { + return false; + } } return list.isEmpty(); } @@ -1388,11 +1542,19 @@ public final class Utility { * @return 元素是否完全相同 */ public static boolean equalsElement(Map map1, Map map2) { - if (map1 == null && map2 == null) return true; - if (map1 == null || map2 == null) return false; - if (map1.size() != map2.size()) return false; + if (map1 == null && map2 == null) { + return true; + } + if (map1 == null || map2 == null) { + return false; + } + if (map1.size() != map2.size()) { + return false; + } for (Map.Entry en : map1.entrySet()) { - if (!Objects.equals(en.getValue(), map2.get(en.getKey()))) return false; + if (!Objects.equals(en.getValue(), map2.get(en.getKey()))) { + return false; + } } return true; } @@ -1406,9 +1568,13 @@ public final class Utility { * @return boolean */ public static boolean contains(char[] values, char value) { - if (values == null) return false; + if (values == null) { + return false; + } for (char v : values) { - if (v == value) return true; + if (v == value) { + return true; + } } return false; } @@ -1422,9 +1588,13 @@ public final class Utility { * @return boolean */ public static boolean contains(short[] values, short value) { - if (values == null) return false; + if (values == null) { + return false; + } for (short v : values) { - if (v == value) return true; + if (v == value) { + return true; + } } return false; } @@ -1438,9 +1608,13 @@ public final class Utility { * @return boolean */ public static boolean contains(short[] values, short... items) { - if (values == null) return false; + if (values == null) { + return false; + } for (short item : items) { - if (!contains(values, item)) return false; + if (!contains(values, item)) { + return false; + } } return true; } @@ -1454,9 +1628,13 @@ public final class Utility { * @return boolean */ public static boolean contains(int[] values, int value) { - if (values == null) return false; + if (values == null) { + return false; + } for (int v : values) { - if (v == value) return true; + if (v == value) { + return true; + } } return false; } @@ -1470,9 +1648,13 @@ public final class Utility { * @return boolean */ public static boolean contains(int[] values, int... items) { - if (values == null) return false; + if (values == null) { + return false; + } for (int item : items) { - if (!contains(values, item)) return false; + if (!contains(values, item)) { + return false; + } } return true; } @@ -1486,9 +1668,13 @@ public final class Utility { * @return boolean */ public static boolean contains(long[] values, long value) { - if (values == null) return false; + if (values == null) { + return false; + } for (long v : values) { - if (v == value) return true; + if (v == value) { + return true; + } } return false; } @@ -1502,9 +1688,13 @@ public final class Utility { * @return boolean */ public static boolean contains(long[] values, long... items) { - if (values == null) return false; + if (values == null) { + return false; + } for (long item : items) { - if (!contains(values, item)) return false; + if (!contains(values, item)) { + return false; + } } return true; } @@ -1519,9 +1709,13 @@ public final class Utility { * @return boolean */ public static boolean contains(T[] values, T value) { - if (values == null) return false; + if (values == null) { + return false; + } for (T v : values) { - if (Objects.equals(v, value)) return true; + if (Objects.equals(v, value)) { + return true; + } } return false; } @@ -1536,9 +1730,13 @@ public final class Utility { * @return boolean */ public static boolean contains(T[] values, Predicate predicate) { - if (values == null) return false; + if (values == null) { + return false; + } for (T v : values) { - if (predicate.test(v)) return true; + if (predicate.test(v)) { + return true; + } } return false; } @@ -1555,14 +1753,24 @@ public final class Utility { * @return 是否完全包含 */ public static boolean containsMatch(final short[] array, final short... items) { - if (array == null) return false; - if (items == null || items.length == 0) return true; - if (array.length == 0 && items.length == 0) return true; - if (array.length < items.length) return false; + if (array == null) { + return false; + } + if (items == null || items.length == 0) { + return true; + } + if (array.length == 0 && items.length == 0) { + return true; + } + if (array.length < items.length) { + return false; + } short[] subs = array; for (short item : items) { - if (!contains(subs, item)) return false; + if (!contains(subs, item)) { + return false; + } short[] newsubs = new short[subs.length - 1]; int k = 0; boolean done = false; @@ -1592,14 +1800,24 @@ public final class Utility { * @return 是否完全包含 */ public static boolean containsMatch(final int[] array, final int... items) { - if (array == null) return false; - if (items == null || items.length == 0) return true; - if (array.length == 0 && items.length == 0) return true; - if (array.length < items.length) return false; + if (array == null) { + return false; + } + if (items == null || items.length == 0) { + return true; + } + if (array.length == 0 && items.length == 0) { + return true; + } + if (array.length < items.length) { + return false; + } int[] subs = array; for (int item : items) { - if (!contains(subs, item)) return false; + if (!contains(subs, item)) { + return false; + } int[] newsubs = new int[subs.length - 1]; int k = 0; boolean done = false; @@ -1629,14 +1847,24 @@ public final class Utility { * @return 是否完全包含 */ public static boolean containsMatch(final long[] array, final long... items) { - if (array == null) return false; - if (items == null || items.length == 0) return true; - if (array.length == 0 && items.length == 0) return true; - if (array.length < items.length) return false; + if (array == null) { + return false; + } + if (items == null || items.length == 0) { + return true; + } + if (array.length == 0 && items.length == 0) { + return true; + } + if (array.length < items.length) { + return false; + } long[] subs = array; for (long item : items) { - if (!contains(subs, item)) return false; + if (!contains(subs, item)) { + return false; + } long[] newsubs = new long[subs.length - 1]; int k = 0; boolean done = false; @@ -1663,7 +1891,9 @@ public final class Utility { * @return 新字符串数组 */ public static String[] exclude(final String[] columns, final String... cols) { - if (columns == null || columns.length == 0 || cols == null || cols.length == 0) return columns; + if (columns == null || columns.length == 0 || cols == null || cols.length == 0) { + return columns; + } int count = 0; for (String column : columns) { boolean flag = false; @@ -1673,10 +1903,16 @@ public final class Utility { break; } } - if (flag) count++; + if (flag) { + count++; + } + } + if (count == 0) { + return columns; + } + if (count == columns.length) { + return new String[0]; } - if (count == 0) return columns; - if (count == columns.length) return new String[0]; final String[] newcols = new String[columns.length - count]; count = 0; for (String column : columns) { @@ -1687,7 +1923,9 @@ public final class Utility { break; } } - if (!flag) newcols[count++] = column; + if (!flag) { + newcols[count++] = column; + } } return newcols; } @@ -1702,9 +1940,13 @@ public final class Utility { * @return 对象 */ public static T find(final T[] array, final Predicate predicate) { - if (array == null) return null; + if (array == null) { + return null; + } for (T item : array) { - if (item != null && predicate.test(item)) return item; + if (item != null && predicate.test(item)) { + return item; + } } return null; } @@ -1719,9 +1961,13 @@ public final class Utility { * @return 对象 */ public static T find(final Collection array, final Predicate predicate) { - if (array == null) return null; + if (array == null) { + return null; + } for (T item : array) { - if (item != null && predicate.test(item)) return item; + if (item != null && predicate.test(item)) { + return item; + } } return null; } @@ -1736,11 +1982,15 @@ public final class Utility { * @return 位置 */ public static int indexOf(final T[] array, final Predicate predicate) { - if (array == null) return -1; + if (array == null) { + return -1; + } int index = -1; for (T item : array) { ++index; - if (item != null && predicate.test(item)) return index; + if (item != null && predicate.test(item)) { + return index; + } } return -1; } @@ -1755,11 +2005,15 @@ public final class Utility { * @return 位置 */ public static int indexOf(final Collection array, final Predicate predicate) { - if (array == null) return -1; + if (array == null) { + return -1; + } int index = -1; for (T item : array) { ++index; - if (item != null && predicate.test(item)) return index; + if (item != null && predicate.test(item)) { + return index; + } } return -1; } @@ -1773,7 +2027,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final byte[] array, final byte element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = 0; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1792,7 +2048,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final byte[] array, int fromIndex, final byte element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1823,7 +2081,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final short[] array, int fromIndex, final short element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1854,7 +2114,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final char[] array, int fromIndex, final char element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1885,7 +2147,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final int[] array, int fromIndex, final int element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1916,7 +2180,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final long[] array, int fromIndex, final long element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1947,7 +2213,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final float[] array, int fromIndex, final float element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1978,7 +2246,9 @@ public final class Utility { * @return 位置 */ public static int indexOf(final double[] array, int fromIndex, final double element) { - if (array == null) return -1; + if (array == null) { + return -1; + } for (int i = fromIndex; i < array.length; ++i) { if (array[i] == element) { return i; @@ -1996,14 +2266,18 @@ public final class Utility { * @return 字符串 */ public static String toString(String string, ByteBuffer buffer) { - if (buffer == null || !buffer.hasRemaining()) return string; + if (buffer == null || !buffer.hasRemaining()) { + return string; + } int pos = buffer.position(); int limit = buffer.limit(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); buffer.position(pos); buffer.limit(limit); - if (string == null) return new String(bytes, UTF_8); + if (string == null) { + return new String(bytes, UTF_8); + } return string + new String(bytes, UTF_8); } @@ -2015,7 +2289,9 @@ public final class Utility { * */ public static void println(String string, ByteBuffer buffer) { - if (buffer == null || !buffer.hasRemaining()) return; + if (buffer == null || !buffer.hasRemaining()) { + return; + } int pos = buffer.position(); int limit = buffer.limit(); byte[] bytes = new byte[buffer.remaining()]; @@ -2033,16 +2309,24 @@ public final class Utility { * */ public static void println(String string, byte... bytes) { - if (bytes == null) return; + if (bytes == null) { + return; + } StringBuilder sb = new StringBuilder(); - if (string != null) sb.append(string); + if (string != null) { + sb.append(string); + } sb.append(bytes.length).append(".["); boolean last = false; for (byte b : bytes) { - if (last) sb.append(','); + if (last) { + sb.append(','); + } int v = b & 0xff; sb.append("0x"); - if (v < 16) sb.append('0'); + if (v < 16) { + sb.append('0'); + } sb.append(Integer.toHexString(v)); last = true; } @@ -2061,12 +2345,18 @@ public final class Utility { Enumeration nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { NetworkInterface nif = nifs.nextElement(); - if (!nif.isUp()) continue; + if (!nif.isUp()) { + continue; + } Enumeration eis = nif.getInetAddresses(); while (eis.hasMoreElements()) { InetAddress ia = eis.nextElement(); - if (ia.isLoopbackAddress() && ia instanceof Inet4Address) back = ia; - if (ia.isSiteLocalAddress() && ia instanceof Inet4Address) return ia; + if (ia.isLoopbackAddress() && ia instanceof Inet4Address) { + back = ia; + } + if (ia.isSiteLocalAddress() && ia instanceof Inet4Address) { + return ia; + } } } } catch (Exception e) { @@ -2089,12 +2379,16 @@ public final class Utility { return new CompletionHandler() { @Override public void completed(V result, A attachment) { - if (success != null) success.accept(result, attachment); + if (success != null) { + success.accept(result, attachment); + } } @Override public void failed(Throwable exc, A attachment) { - if (fail != null) fail.accept(exc, attachment); + if (fail != null) { + fail.accept(exc, attachment); + } } }; } @@ -2112,12 +2406,16 @@ public final class Utility { return new CompletionHandler() { @Override public void completed(Void result, A attachment) { - if (success != null) success.accept(attachment); + if (success != null) { + success.accept(attachment); + } } @Override public void failed(Throwable exc, A attachment) { - if (fail != null) fail.accept(exc, attachment); + if (fail != null) { + fail.accept(exc, attachment); + } } }; } @@ -2135,12 +2433,16 @@ public final class Utility { return new CompletionHandler() { @Override public void completed(V result, Void attachment) { - if (success != null) success.accept(result); + if (success != null) { + success.accept(result); + } } @Override public void failed(Throwable exc, Void attachment) { - if (fail != null) fail.accept(exc); + if (fail != null) { + fail.accept(exc); + } } }; } @@ -2416,19 +2718,37 @@ public final class Utility { int c = 0; if (!format.contains("%1$")) { for (char ch : format.toCharArray()) { - if (ch == '%') c++; + if (ch == '%') { + c++; + } } } size = c; } - if (size <= 1) return String.format(format, time); - if (size == 2) return String.format(format, time, time); - if (size == 3) return String.format(format, time, time, time); - if (size == 4) return String.format(format, time, time, time, time); - if (size == 5) return String.format(format, time, time, time, time, time); - if (size == 6) return String.format(format, time, time, time, time, time, time); - if (size == 7) return String.format(format, time, time, time, time, time, time, time); - if (size == 8) return String.format(format, time, time, time, time, time, time, time); + if (size <= 1) { + return String.format(format, time); + } + if (size == 2) { + return String.format(format, time, time); + } + if (size == 3) { + return String.format(format, time, time, time); + } + if (size == 4) { + return String.format(format, time, time, time, time); + } + if (size == 5) { + return String.format(format, time, time, time, time, time); + } + if (size == 6) { + return String.format(format, time, time, time, time, time, time); + } + if (size == 7) { + return String.format(format, time, time, time, time, time, time, time); + } + if (size == 8) { + return String.format(format, time, time, time, time, time, time, time); + } Object[] args = new Object[size]; for (int i = 0; i < size; i++) { args[i] = time; @@ -2444,7 +2764,9 @@ public final class Utility { * @return byte[] */ public static byte[] intsToBytes(int[] value) { - if (value == null) return null; + if (value == null) { + return null; + } byte[] bs = new byte[value.length]; for (int i = 0; i < bs.length; i++) { bs[i] = (byte) value[i]; @@ -2482,7 +2804,9 @@ public final class Utility { * @return md5值 */ public static byte[] md5(String str) { - if (str == null) return null; + if (str == null) { + return null; + } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); @@ -2500,7 +2824,9 @@ public final class Utility { * @return md5值 */ public static byte[] md5(byte[] input) { - if (input == null) return null; + if (input == null) { + return null; + } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); @@ -2520,7 +2846,9 @@ public final class Utility { * @return md5值 */ public static byte[] md5(byte[] input, int offset, int len) { - if (input == null) return null; + if (input == null) { + return null; + } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); @@ -2598,7 +2926,9 @@ public final class Utility { * @return hash值 */ public static byte[] sha256(String str) { - if (str == null) return null; + if (str == null) { + return null; + } MessageDigest digester; try { digester = MessageDigest.getInstance("SHA-256"); @@ -2616,7 +2946,9 @@ public final class Utility { * @return hash值 */ public static byte[] sha256(byte[] input) { - if (input == null) return null; + if (input == null) { + return null; + } MessageDigest digester; try { digester = MessageDigest.getInstance("SHA-256"); @@ -2636,7 +2968,9 @@ public final class Utility { * @return hash值 */ public static byte[] sha256(byte[] input, int offset, int len) { - if (input == null) return null; + if (input == null) { + return null; + } MessageDigest digester; try { digester = MessageDigest.getInstance("SHA-256"); @@ -2746,7 +3080,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha1(byte[] key, byte[] input) { - if (input == null) return null; + if (input == null) { + return null; + } try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key, "HmacSHA1")); @@ -2767,7 +3103,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha1(byte[] key, byte[] input, int offset, int len) { - if (input == null) return null; + if (input == null) { + return null; + } try { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key, "HmacSHA1")); @@ -2877,7 +3215,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha256(byte[] key, byte[] input) { - if (input == null) return null; + if (input == null) { + return null; + } try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); @@ -2898,7 +3238,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha256(byte[] key, byte[] input, int offset, int len) { - if (input == null) return null; + if (input == null) { + return null; + } try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); @@ -3008,7 +3350,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha512(byte[] key, byte[] input) { - if (input == null) return null; + if (input == null) { + return null; + } try { SecretKey sk = new SecretKeySpec(key, "HmacSHA512"); Mac mac = Mac.getInstance("HmacSHA512"); @@ -3030,7 +3374,9 @@ public final class Utility { * @return hash值 */ public static byte[] hmacSha512(byte[] key, byte[] input, int offset, int len) { - if (input == null) return null; + if (input == null) { + return null; + } try { SecretKey sk = new SecretKeySpec(key, "HmacSHA512"); Mac mac = Mac.getInstance("HmacSHA512"); @@ -3213,13 +3559,21 @@ public final class Utility { String digits = "0123456789abcdef"; for (int i = 0; i < size; i++) { int ch1 = src.charAt(offset + i * 2); - if ('A' <= ch1 && 'F' >= ch1) ch1 = ch1 - 'A' + 'a'; + if ('A' <= ch1 && 'F' >= ch1) { + ch1 = ch1 - 'A' + 'a'; + } int ch2 = src.charAt(offset + i * 2 + 1); - if ('A' <= ch2 && 'F' >= ch2) ch2 = ch2 - 'A' + 'a'; + if ('A' <= ch2 && 'F' >= ch2) { + ch2 = ch2 - 'A' + 'a'; + } int pos1 = digits.indexOf(ch1); - if (pos1 < 0) throw new NumberFormatException(); + if (pos1 < 0) { + throw new NumberFormatException(); + } int pos2 = digits.indexOf(ch2); - if (pos2 < 0) throw new NumberFormatException(); + if (pos2 < 0) { + throw new NumberFormatException(); + } bytes[i] = (byte) (pos1 * 0x10 + pos2); } return bytes; @@ -3268,13 +3622,21 @@ public final class Utility { String digits = "0123456789abcdef"; for (int i = 0; i < size; i++) { int ch1 = src[offset + i * 2]; - if ('A' <= ch1 && 'F' >= ch1) ch1 = ch1 - 'A' + 'a'; + if ('A' <= ch1 && 'F' >= ch1) { + ch1 = ch1 - 'A' + 'a'; + } int ch2 = src[offset + i * 2 + 1]; - if ('A' <= ch2 && 'F' >= ch2) ch2 = ch2 - 'A' + 'a'; + if ('A' <= ch2 && 'F' >= ch2) { + ch2 = ch2 - 'A' + 'a'; + } int pos1 = digits.indexOf(ch1); - if (pos1 < 0) throw new NumberFormatException(); + if (pos1 < 0) { + throw new NumberFormatException(); + } int pos2 = digits.indexOf(ch2); - if (pos2 < 0) throw new NumberFormatException(); + if (pos2 < 0) { + throw new NumberFormatException(); + } bytes[i] = (byte) (pos1 * 0x10 + pos2); } return bytes; @@ -3328,8 +3690,12 @@ public final class Utility { } public static byte[] encodeUTF8(final String value) { - if (value == null) return new byte[0]; - if (strCharFunction == null) return encodeUTF8(value.toCharArray()); + if (value == null) { + return new byte[0]; + } + if (strCharFunction == null) { + return encodeUTF8(value.toCharArray()); + } return encodeUTF8((char[]) strCharFunction.apply(value)); } @@ -3384,40 +3750,60 @@ public final class Utility { } public static boolean isLatin1(String value) { - if (value == null) return true; + if (value == null) { + return true; + } if (strLatin1Function != null) { return strLatin1Function.test(value); //LATIN1:0 UTF16:1 } char[] chs = charArray(value); for (char ch : chs) { - if (ch >= 0x80) return false; + if (ch >= 0x80) { + return false; + } } return true; } public static char[] charArray(String value) { - if (value == null) return null; - if (strCharFunction == null) return value.toCharArray(); + if (value == null) { + return null; + } + if (strCharFunction == null) { + return value.toCharArray(); + } return (char[]) strCharFunction.apply(value); } public static char[] charArray(StringBuilder value) { - if (value == null) return null; - if (sbCharFunction == null) return value.toString().toCharArray(); + if (value == null) { + return null; + } + if (sbCharFunction == null) { + return value.toString().toCharArray(); + } return (char[]) sbCharFunction.apply(value); } //只能是单字节字符串 public static byte[] latin1ByteArray(String latin1Value) { - if (latin1Value == null) return null; - if (strByteFunction == null) return latin1Value.getBytes(); + if (latin1Value == null) { + return null; + } + if (strByteFunction == null) { + return latin1Value.getBytes(); + } return (byte[]) strByteFunction.apply(latin1Value); } //只能是单字节字符串 public static byte[] latin1ByteArray(StringBuilder latin1Value) { - if (latin1Value == null) return null; - if (sbByteFunction == null) return latin1Value.toString().getBytes(); + if (latin1Value == null) { + return null; + } + if (sbByteFunction == null) { + return latin1Value.toString().getBytes(); + } return (byte[]) sbByteFunction.apply(latin1Value); } @@ -3430,8 +3816,12 @@ public final class Utility { } public static int encodeUTF8Length(String value) { - if (value == null) return -1; - if (strCharFunction == null) return encodeUTF8Length(value.toCharArray()); + if (value == null) { + return -1; + } + if (strCharFunction == null) { + return encodeUTF8Length(value.toCharArray()); + } return encodeUTF8Length((char[]) strCharFunction.apply(value)); } @@ -3486,14 +3876,20 @@ public final class Utility { for (int i = start; i < limit; i++) { c = chs[i]; if (c < 0x80) { - if (buf.remaining() < 1) buf = buffer2; + if (buf.remaining() < 1) { + buf = buffer2; + } buf.put((byte) c); } else if (c < 0x800) { - if (buf.remaining() < 2) buf = buffer2; + if (buf.remaining() < 2) { + buf = buffer2; + } buf.put((byte) (0xc0 | (c >> 6))); buf.put((byte) (0x80 | (c & 0x3f))); } else if (Character.isSurrogate(c)) { //连取两个 - if (buf.remaining() < 4) buf = buffer2; + if (buf.remaining() < 4) { + buf = buffer2; + } int uc = Character.toCodePoint(c, chs[i + 1]); buf.put((byte) (0xf0 | ((uc >> 18)))); buf.put((byte) (0x80 | ((uc >> 12) & 0x3f))); @@ -3501,18 +3897,24 @@ public final class Utility { buf.put((byte) (0x80 | (uc & 0x3f))); i++; } else { - if (buf.remaining() < 3) buf = buffer2; + if (buf.remaining() < 3) { + buf = buffer2; + } buf.put((byte) (0xe0 | ((c >> 12)))); buf.put((byte) (0x80 | ((c >> 6) & 0x3f))); buf.put((byte) (0x80 | (c & 0x3f))); } } - if (buffer2 != null) buffer2.flip(); + if (buffer2 != null) { + buffer2.flip(); + } return buffer2; //返回扩展buffer } public static String getTypeDescriptor(java.lang.reflect.Type type) { - if (type == null) return null; + if (type == null) { + return null; + } if (type instanceof Class) { Class d = (Class) type; final StringBuilder sb = new StringBuilder(); @@ -4055,7 +4457,9 @@ public final class Utility { java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest.newBuilder().uri(URI.create(url)) .timeout(Duration.ofMillis(timeoutMs > 0 ? timeoutMs : 6000)) .method(method, body == null ? java.net.http.HttpRequest.BodyPublishers.noBody() : java.net.http.HttpRequest.BodyPublishers.ofString(body)); - if (headers != null) headers.forEach((n, v) -> builder.header(n, v)); + if (headers != null) { + headers.forEach((n, v) -> builder.header(n, v)); + } java.net.http.HttpClient c = client == null ? httpClient : client; if (c == null) { synchronized (clientLock) { @@ -4080,7 +4484,9 @@ public final class Utility { if (rs == 200 || result != null) { if (respHeaders != null) { resp.headers().map().forEach((k, l) -> { - if (!l.isEmpty()) respHeaders.put(k, l.get(0)); + if (!l.isEmpty()) { + respHeaders.put(k, l.get(0)); + } }); } ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -4170,7 +4576,9 @@ public final class Utility { while ((pos = in.read(bytes)) != -1) { out.write(bytes, 0, pos); } - if (close) in.close(); + if (close) { + in.close(); + } return charset == null ? out.toString() : out.toString(charset); } @@ -4189,7 +4597,9 @@ public final class Utility { while ((pos = in.read(bytes)) != -1) { out.write(bytes, 0, pos); } - if (close) in.close(); + if (close) { + in.close(); + } return out; } diff --git a/src/main/java/org/redkale/util/XmlReader.java b/src/main/java/org/redkale/util/XmlReader.java index 428969edd..b423536ee 100644 --- a/src/main/java/org/redkale/util/XmlReader.java +++ b/src/main/java/org/redkale/util/XmlReader.java @@ -93,10 +93,16 @@ public class XmlReader { readXmlDecl(root, array); } else if (ch2 == '/') { //节点结束 String tag = readEndTag(); - if (tags.isEmpty()) throw newException("unexpected end tag " + tag); - if (!tags.getFirst().tag.equals(tag)) throw newException("expected end tag " + tags.getFirst().tag + " but " + tag); + if (tags.isEmpty()) { + throw newException("unexpected end tag " + tag); + } + if (!tags.getFirst().tag.equals(tag)) { + throw newException("expected end tag " + tags.getFirst().tag + " but " + tag); + } tags.removeFirst(); - if (tags.isEmpty()) break; + if (tags.isEmpty()) { + break; + } } else { //节点开始 readStartTag(root); } @@ -126,7 +132,9 @@ public class XmlReader { * @return 空白字符或有效字符 */ protected char nextChar() { - if (this.position == this.limit) throw newException("read EOF"); + if (this.position == this.limit) { + throw newException("read EOF"); + } char ch = this.text[++this.position]; if (ch == '\n') { this.lineNumber++; @@ -143,10 +151,14 @@ public class XmlReader { */ protected char nextGoodChar() { char c = nextChar(); - if (c > ' ') return c; + if (c > ' ') { + return c; + } for (;;) { c = nextChar(); - if (c > ' ') return c; + if (c > ' ') { + return c; + } } } @@ -165,17 +177,23 @@ public class XmlReader { boolean endtag = false; boolean endattr = false; char ch = nextGoodChar(); - if (ch == '/') return true; + if (ch == '/') { + return true; + } int start = this.position; for (;;) { if (ch == '=') { break; } else if (ch >= '0' && ch <= '9') { - if (first) throw newException("illegal character " + ch); + if (first) { + throw newException("illegal character " + ch); + } } else if (ch >= 'a' && ch <= 'z') { } else if (ch >= 'A' && ch <= 'Z') { } else if (ch == '.' || ch == '-' || ch == '_' || ch == ':') { - if (first) throw newException("illegal character " + ch); + if (first) { + throw newException("illegal character " + ch); + } } else { throw newException("illegal character " + ch); } @@ -190,7 +208,9 @@ public class XmlReader { start = this.position + 1; for (;;) { ch = nextChar(); - if (ch == quote) break; + if (ch == quote) { + break; + } } attrValue = escape(new String(this.text, start, this.position - start)); } else { @@ -211,13 +231,23 @@ public class XmlReader { } attrValue = escape(new String(this.text, start, this.position - start)); } - if (attrFunc != null) attrValue = attrFunc.apply(attrName, attrValue); + if (attrFunc != null) { + attrValue = attrFunc.apply(attrName, attrValue); + } config.addValue(attrName, attrValue); - if (endtag) return endtag; - if (endattr) return false; + if (endtag) { + return endtag; + } + if (endattr) { + return false; + } ch = nextGoodChar(); - if (ch == '>') return false; - if (ch == '/') return true; + if (ch == '>') { + return false; + } + if (ch == '/') { + return true; + } backChar(ch); return readTagAttribute(tag, config); } @@ -248,9 +278,13 @@ public class XmlReader { } else { tags.getFirst().config.addValue(tag, tagNode.config); } - if (hasattr) endtag = readTagAttribute(tag, config); + if (hasattr) { + endtag = readTagAttribute(tag, config); + } if (endtag) { - if (nextChar() != '>') throw newException("expected /> for tag end"); + if (nextChar() != '>') { + throw newException("expected /> for tag end"); + } return; } tags.addFirst(tagNode); @@ -261,14 +295,18 @@ public class XmlReader { char ch; for (;;) { ch = nextChar(); - if (ch == '>') break; + if (ch == '>') { + break; + } } return new String(this.text, start, this.position - start).trim(); } protected void readComment() { //读取到 ' - if (nextChar() != 'O') throw newException("expected ' Char*)) ]]>' - if (nextChar() != 'C') throw newException("expected