UTF-8
diff --git a/root/readme.txt b/root/readme.txt
index e69de29bb..0519ecba6 100644
--- a/root/readme.txt
+++ b/root/readme.txt
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/src/main/java/javax/annotation/Priority.java b/src/main/java/javax/annotation/Priority.java
index a23830532..30f376277 100644
--- a/src/main/java/javax/annotation/Priority.java
+++ b/src/main/java/javax/annotation/Priority.java
@@ -1,39 +1,39 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package javax.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * 鍊艰秺澶э紝浼樺厛绾ц秺楂
- *
- * @since Common Annotations 1.2
- */
-@Target({ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface Priority {
-
- /**
- * 浼樺厛绾у
- *
- * @return int
- */
- int value();
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package javax.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * 鍊艰秺澶э紝浼樺厛绾ц秺楂
+ *
+ * @since Common Annotations 1.2
+ */
+@Target({ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Priority {
+
+ /**
+ * 浼樺厛绾у
+ *
+ * @return int
+ */
+ int value();
+}
diff --git a/src/main/java/javax/annotation/Resource.java b/src/main/java/javax/annotation/Resource.java
index 2be9de072..7105c2e4c 100644
--- a/src/main/java/javax/annotation/Resource.java
+++ b/src/main/java/javax/annotation/Resource.java
@@ -1,83 +1,83 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package javax.annotation;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * @since Common Annotations 1.0
- */
-@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
-@Retention(RetentionPolicy.RUNTIME)
-public @interface Resource {
-
- /**
- * AuthenticationType
- */
- @Deprecated
- public enum AuthenticationType {
- /**
- * @deprecated
- */
- CONTAINER,
- /**
- * @deprecated
- */
- APPLICATION
- }
-
- /**
- * 璧勬簮鍚嶇О
- *
- * @return String
- */
- public String name() default "";
-
- /**
- * 渚濊禆娉ㄥ叆鐨勭被鍨
- *
- * @return Class
- */
- public Class> type() default Object.class;
-
- /**
- *
- * @return AuthenticationType
- */
- @Deprecated
- public AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
-
- /**
- *
- * @return boolean
- */
- @Deprecated
- public boolean shareable() default true;
-
- /**
- *
- * @return String
- */
- @Deprecated
- public String description() default "";
-
- /**
- *
- * @return String
- */
- @Deprecated
- public String mappedName() default "";
-
- /**
- *
- * @return String
- */
- @Deprecated
- public String lookup() default "";
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package javax.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * @since Common Annotations 1.0
+ */
+@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Resource {
+
+ /**
+ * AuthenticationType
+ */
+ @Deprecated
+ public enum AuthenticationType {
+ /**
+ * @deprecated
+ */
+ CONTAINER,
+ /**
+ * @deprecated
+ */
+ APPLICATION
+ }
+
+ /**
+ * 璧勬簮鍚嶇О
+ *
+ * @return String
+ */
+ public String name() default "";
+
+ /**
+ * 渚濊禆娉ㄥ叆鐨勭被鍨
+ *
+ * @return Class
+ */
+ public Class> type() default Object.class;
+
+ /**
+ *
+ * @return AuthenticationType
+ */
+ @Deprecated
+ public AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
+
+ /**
+ *
+ * @return boolean
+ */
+ @Deprecated
+ public boolean shareable() default true;
+
+ /**
+ *
+ * @return String
+ */
+ @Deprecated
+ public String description() default "";
+
+ /**
+ *
+ * @return String
+ */
+ @Deprecated
+ public String mappedName() default "";
+
+ /**
+ *
+ * @return String
+ */
+ @Deprecated
+ public String lookup() default "";
+}
diff --git a/src/main/java/javax/persistence/Cacheable.java b/src/main/java/javax/persistence/Cacheable.java
index fd6f6b181..45238dd98 100644
--- a/src/main/java/javax/persistence/Cacheable.java
+++ b/src/main/java/javax/persistence/Cacheable.java
@@ -1,62 +1,62 @@
-/** *****************************************************************************
- * Copyright (c) 2008 - 2013 Oracle Corporation. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
- * which accompanies this distribution.
- * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
- * and the Eclipse Distribution License is available at
- * http://www.eclipse.org/org/documents/edl-v10.php.
- *
- * Contributors:
- * Linda DeMichiel - Java Persistence 2.1
- * Linda DeMichiel - Java Persistence 2.0
- *
- ***************************************************************************** */
-package javax.persistence;
-
-import static java.lang.annotation.ElementType.TYPE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Specifies whether an entity should be cached if caching is enabled
- * when the value of the persistence.xml caching element
- * is ENABLE_SELECTIVE or DISABLE_SELECTIVE.
- * The value of the Cacheable annotation is inherited by
- * subclasses; it can be overridden by specifying
- * Cacheable on a subclass.
- *
- *
- * Cacheable(false) means that the entity and its state must
- * not be cached by the provider.
- *
- * @since Java Persistence 2.0
- */
-@Target({TYPE})
-@Retention(RUNTIME)
-public @interface Cacheable {
-
- /**
- * (Optional) Whether or not the entity should be cached.
- *
- * @return boolean
- */
- boolean value() default true;
-
- /**
- * (Optional) 瀹氭椂鑷姩鏇存柊缂撳瓨鐨勫懆鏈熺鏁帮紝涓0琛ㄧず涓嶅仛瀹氭椂鏇存柊锛 澶т簬0琛ㄧず姣忕粡杩噄nterval绉掑悗浼氳嚜鍔ㄤ粠鏁版嵁搴撲腑鎷夊彇鏁版嵁鏇存柊Cache
- *
- * @return int
- */
- int interval() default 0;
-
- /**
- * DataSource鏄惁鐩存帴杩斿洖瀵硅薄鐨勭湡瀹炲紩鐢紝 鑰屼笉鏄痗opy涓浠
- *
- * @return boolean
- */
- boolean direct() default false;
-
-}
+/** *****************************************************************************
+ * Copyright (c) 2008 - 2013 Oracle Corporation. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Linda DeMichiel - Java Persistence 2.1
+ * Linda DeMichiel - Java Persistence 2.0
+ *
+ ***************************************************************************** */
+package javax.persistence;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+/**
+ * Specifies whether an entity should be cached if caching is enabled
+ * when the value of the persistence.xml caching element
+ * is ENABLE_SELECTIVE or DISABLE_SELECTIVE.
+ * The value of the Cacheable annotation is inherited by
+ * subclasses; it can be overridden by specifying
+ * Cacheable on a subclass.
+ *
+ *
+ * Cacheable(false) means that the entity and its state must
+ * not be cached by the provider.
+ *
+ * @since Java Persistence 2.0
+ */
+@Target({TYPE})
+@Retention(RUNTIME)
+public @interface Cacheable {
+
+ /**
+ * (Optional) Whether or not the entity should be cached.
+ *
+ * @return boolean
+ */
+ boolean value() default true;
+
+ /**
+ * (Optional) 瀹氭椂鑷姩鏇存柊缂撳瓨鐨勫懆鏈熺鏁帮紝涓0琛ㄧず涓嶅仛瀹氭椂鏇存柊锛 澶т簬0琛ㄧず姣忕粡杩噄nterval绉掑悗浼氳嚜鍔ㄤ粠鏁版嵁搴撲腑鎷夊彇鏁版嵁鏇存柊Cache
+ *
+ * @return int
+ */
+ int interval() default 0;
+
+ /**
+ * DataSource鏄惁鐩存帴杩斿洖瀵硅薄鐨勭湡瀹炲紩鐢紝 鑰屼笉鏄痗opy涓浠
+ *
+ * @return boolean
+ */
+ boolean direct() default false;
+
+}
diff --git a/src/main/java/org/redkale/asm/MethodDebugVisitor.java b/src/main/java/org/redkale/asm/MethodDebugVisitor.java
index 3045c4b8d..f7223642e 100644
--- a/src/main/java/org/redkale/asm/MethodDebugVisitor.java
+++ b/src/main/java/org/redkale/asm/MethodDebugVisitor.java
@@ -1,274 +1,274 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.asm;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.*;
-import static org.redkale.asm.Opcodes.*;
-
-/**
- * MethodVisitor 鐨勮皟璇曠被
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-public class MethodDebugVisitor {
-
- private final MethodVisitor visitor;
-
- private boolean debug = false;
-
- public MethodDebugVisitor setDebug(boolean d) {
- debug = d;
- return this;
- }
-
- public void debugLine() {
- if (!debug) return;
- System.out.println();
- System.out.println();
- System.out.println();
- }
-
- private final Map labels = new LinkedHashMap<>();
-
- private static final String[] opcodes = new String[200]; //0 -18
-
- static {
- try {
- for (java.lang.reflect.Field field : Opcodes.class.getFields()) {
- String name = field.getName();
- if (name.startsWith("ASM")) continue;
- if (name.startsWith("V1_")) continue;
- if (name.startsWith("ACC_")) continue;
- if (name.startsWith("T_")) continue;
- if (name.startsWith("H_")) continue;
- if (name.startsWith("F_")) continue;
- if (field.getType() != int.class) continue;
- opcodes[(int) (Integer) field.get(null)] = name;
- }
- } catch (Exception ex) {
- throw new RuntimeException(ex); //涓嶅彲鑳戒細鍙戠敓
- }
- }
-
- /**
- *
- * @param visitor MethodVisitor
- */
- public MethodDebugVisitor(MethodVisitor visitor) {
- //super(Opcodes.ASM5, visitor);
- this.visitor = visitor;
- }
-
- public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
- visitor.visitTryCatchBlock(start, end, handler, type);
- if (debug) System.out.println("mv.visitTryCatchBlock(label0, label1, label2, \"" + type + "\");");
- }
-
- public AnnotationVisitor visitParameterAnnotation(int i, String string, boolean bln) {
- AnnotationVisitor av = visitor.visitParameterAnnotation(i, string, bln);
- if (debug) System.out.println("mv.visitParameterAnnotation(" + i + ", \"" + string + "\", " + bln + ");");
- return av;
- }
-
- public AnnotationVisitor visitAnnotation(String desc, boolean flag) {
- AnnotationVisitor av = visitor.visitAnnotation(desc, flag);
- if (debug) System.out.println("mv.visitAnnotation(\"" + desc + "\", " + flag + ");");
- return av;
- }
-
- public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
- AnnotationVisitor av = visitor.visitTypeAnnotation(typeRef, typePath, desc, visible);
- if (debug) System.out.println("mv.visitTypeAnnotation(" + typeRef + ", " + typePath + ", \"" + desc + "\", " + visible + ");");
- return av;
- }
-
- public void visitParameter(String name, int access) {
- visitor.visitParameter(name, access);
- if (debug) System.out.println("mv.visitParameter(" + name + ", " + access + ");");
- }
-
- public void visitVarInsn(int opcode, int var) {
- visitor.visitVarInsn(opcode, var);
- if (debug) System.out.println("mv.visitVarInsn(" + opcodes[opcode] + ", " + var + ");");
- }
-
- public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
- visitor.visitFrame(type, nLocal, local, nStack, stack);
- if (debug) {
- String typestr = "" + type;
- if (type == -1) {
- typestr = "Opcodes.F_NEW";
- } else if (type == 1) {
- typestr = "Opcodes.F_APPEND";
- } else if (type == 2) {
- typestr = "Opcodes.F_CHOP";
- } else if (type == 3) {
- typestr = "Opcodes.F_SAME";
- } else if (type == 4) {
- typestr = "Opcodes.F_SAME1";
- }
- System.out.println("mv.visitFrame(" + typestr + ", " + nLocal + ", " + Arrays.toString(local) + ", " + nStack + ", " + Arrays.toString(stack) + ");");
- }
- }
-
- public void visitJumpInsn(int opcode, Label var) { //璋冪敤姝ゆ柟娉曠殑 ClassWriter 蹇呴』鐢 COMPUTE_FRAMES 鏋勫缓
- visitor.visitJumpInsn(opcode, var);
- if (debug) {
- Integer index = labels.get(var);
- if (index == null) {
- index = labels.size();
- labels.put(var, index);
- System.out.println("Label l" + index + " = new Label();");
- }
- System.out.println("mv.visitJumpInsn(" + opcodes[opcode] + ", l" + index + ");");
- }
- }
-
- public void visitCode() {
- visitor.visitCode();
- if (debug) System.out.println("mv.visitCode();");
- }
-
- public void visitLabel(Label var) {
- visitor.visitLabel(var);
- if (debug) {
- Integer index = labels.get(var);
- if (index == null) {
- index = labels.size();
- labels.put(var, index);
- System.out.println("Label l" + index + " = new Label();");
- }
- System.out.println("mv.visitLabel(l" + index + ");");
- }
- }
-
- public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
- visitor.visitMethodInsn(opcode, owner, name, desc, itf);
- if (debug) System.out.println("mv.visitMethodInsn(" + opcodes[opcode] + ", \"" + owner + "\", \"" + name + "\", \"" + desc + "\", " + itf + ");");
- }
-
- public void visitFieldInsn(int opcode, String owner, String name, String desc) {
- visitor.visitFieldInsn(opcode, owner, name, desc);
- if (debug) System.out.println("mv.visitFieldInsn(" + opcodes[opcode] + ", \"" + owner + "\", \"" + name + "\", \"" + desc + "\");");
- }
-
- public void visitTypeInsn(int opcode, String type) {
- visitor.visitTypeInsn(opcode, type);
- if (debug) System.out.println("mv.visitTypeInsn(" + opcodes[opcode] + ", \"" + type + "\");");
- }
-
- public void visitInsn(int opcode) {
- visitor.visitInsn(opcode);
- if (debug) System.out.println("mv.visitInsn(" + opcodes[opcode] + ");");
- }
-
- public void visitIntInsn(int opcode, int value) {
- visitor.visitIntInsn(opcode, value);
- if (debug) System.out.println("mv.visitIntInsn(" + opcodes[opcode] + ", " + value + ");");
- }
-
- public void visitIincInsn(int opcode, int value) {
- visitor.visitIincInsn(opcode, value);
- if (debug) System.out.println("mv.visitIincInsn(" + opcode + ", " + value + ");");
- }
-
- public void visitLdcInsn(Object o) {
- visitor.visitLdcInsn(o);
- if (debug) {
- if (o instanceof CharSequence) {
- System.out.println("mv.visitLdcInsn(\"" + o + "\");");
- } else if (o instanceof org.redkale.asm.Type) {
- System.out.println("mv.visitLdcInsn(Type.getType(\"" + o + "\"));");
- } else {
- System.out.println("mv.visitLdcInsn(" + o + ");");
- }
- }
- }
-
- public void visitMaxs(int maxStack, int maxLocals) {
- visitor.visitMaxs(maxStack, maxLocals);
- if (debug) System.out.println("mv.visitMaxs(" + maxStack + ", " + maxLocals + ");");
- }
-
- public void visitEnd() {
- visitor.visitEnd();
- if (debug) System.out.println("mv.visitEnd();\r\n\r\n\r\n");
- }
-
- public static void pushInt(MethodDebugVisitor mv, int num) {
- if (num < 6) {
- mv.visitInsn(ICONST_0 + num);
- } else if (num <= Byte.MAX_VALUE) {
- mv.visitIntInsn(BIPUSH, num);
- } else if (num <= Short.MAX_VALUE) {
- mv.visitIntInsn(SIPUSH, num);
- } else {
- mv.visitLdcInsn(num);
- }
- }
-
- public static void pushInt(MethodVisitor mv, int num) {
- if (num < 6) {
- mv.visitInsn(ICONST_0 + num);
- } else if (num <= Byte.MAX_VALUE) {
- mv.visitIntInsn(BIPUSH, num);
- } else if (num <= Short.MAX_VALUE) {
- mv.visitIntInsn(SIPUSH, num);
- } else {
- mv.visitLdcInsn(num);
- }
- }
-
- public static void visitAnnotation(final AnnotationVisitor av, final Annotation ann) {
- try {
- for (Method anm : ann.annotationType().getMethods()) {
- final String mname = anm.getName();
- if ("equals".equals(mname) || "hashCode".equals(mname) || "toString".equals(mname) || "annotationType".equals(mname)) continue;
- final Object r = anm.invoke(ann);
- if (r instanceof String[]) {
- AnnotationVisitor av1 = av.visitArray(mname);
- for (String item : (String[]) r) {
- av1.visit(null, item);
- }
- av1.visitEnd();
- } else if (r instanceof Class[]) {
- AnnotationVisitor av1 = av.visitArray(mname);
- for (Class item : (Class[]) r) {
- av1.visit(null, Type.getType(item));
- }
- av1.visitEnd();
- } else if (r instanceof Enum[]) {
- AnnotationVisitor av1 = av.visitArray(mname);
- for (Enum item : (Enum[]) r) {
- av1.visitEnum(null, Type.getDescriptor(item.getClass()), ((Enum) item).name());
- }
- av1.visitEnd();
- } else if (r instanceof Annotation[]) {
- AnnotationVisitor av1 = av.visitArray(mname);
- for (Annotation item : (Annotation[]) r) {
- visitAnnotation(av1.visitAnnotation(null, Type.getDescriptor(((Annotation) item).annotationType())), item);
- }
- av1.visitEnd();
- } else if (r instanceof Class) {
- av.visit(mname, Type.getType((Class) r));
- } else if (r instanceof Enum) {
- av.visitEnum(mname, Type.getDescriptor(r.getClass()), ((Enum) r).name());
- } else if (r instanceof Annotation) {
- visitAnnotation(av.visitAnnotation(null, Type.getDescriptor(((Annotation) r).annotationType())), (Annotation) r);
- } else {
- av.visit(mname, r);
- }
- }
- av.visitEnd();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.asm;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Method;
+import java.util.*;
+import static org.redkale.asm.Opcodes.*;
+
+/**
+ * MethodVisitor 鐨勮皟璇曠被
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+public class MethodDebugVisitor {
+
+ private final MethodVisitor visitor;
+
+ private boolean debug = false;
+
+ public MethodDebugVisitor setDebug(boolean d) {
+ debug = d;
+ return this;
+ }
+
+ public void debugLine() {
+ if (!debug) return;
+ System.out.println();
+ System.out.println();
+ System.out.println();
+ }
+
+ private final Map labels = new LinkedHashMap<>();
+
+ private static final String[] opcodes = new String[200]; //0 -18
+
+ static {
+ try {
+ for (java.lang.reflect.Field field : Opcodes.class.getFields()) {
+ String name = field.getName();
+ if (name.startsWith("ASM")) continue;
+ if (name.startsWith("V1_")) continue;
+ if (name.startsWith("ACC_")) continue;
+ if (name.startsWith("T_")) continue;
+ if (name.startsWith("H_")) continue;
+ if (name.startsWith("F_")) continue;
+ if (field.getType() != int.class) continue;
+ opcodes[(int) (Integer) field.get(null)] = name;
+ }
+ } catch (Exception ex) {
+ throw new RuntimeException(ex); //涓嶅彲鑳戒細鍙戠敓
+ }
+ }
+
+ /**
+ *
+ * @param visitor MethodVisitor
+ */
+ public MethodDebugVisitor(MethodVisitor visitor) {
+ //super(Opcodes.ASM5, visitor);
+ this.visitor = visitor;
+ }
+
+ public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
+ visitor.visitTryCatchBlock(start, end, handler, type);
+ if (debug) System.out.println("mv.visitTryCatchBlock(label0, label1, label2, \"" + type + "\");");
+ }
+
+ public AnnotationVisitor visitParameterAnnotation(int i, String string, boolean bln) {
+ AnnotationVisitor av = visitor.visitParameterAnnotation(i, string, bln);
+ if (debug) System.out.println("mv.visitParameterAnnotation(" + i + ", \"" + string + "\", " + bln + ");");
+ return av;
+ }
+
+ public AnnotationVisitor visitAnnotation(String desc, boolean flag) {
+ AnnotationVisitor av = visitor.visitAnnotation(desc, flag);
+ if (debug) System.out.println("mv.visitAnnotation(\"" + desc + "\", " + flag + ");");
+ return av;
+ }
+
+ public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
+ AnnotationVisitor av = visitor.visitTypeAnnotation(typeRef, typePath, desc, visible);
+ if (debug) System.out.println("mv.visitTypeAnnotation(" + typeRef + ", " + typePath + ", \"" + desc + "\", " + visible + ");");
+ return av;
+ }
+
+ public void visitParameter(String name, int access) {
+ visitor.visitParameter(name, access);
+ if (debug) System.out.println("mv.visitParameter(" + name + ", " + access + ");");
+ }
+
+ public void visitVarInsn(int opcode, int var) {
+ visitor.visitVarInsn(opcode, var);
+ if (debug) System.out.println("mv.visitVarInsn(" + opcodes[opcode] + ", " + var + ");");
+ }
+
+ public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
+ visitor.visitFrame(type, nLocal, local, nStack, stack);
+ if (debug) {
+ String typestr = "" + type;
+ if (type == -1) {
+ typestr = "Opcodes.F_NEW";
+ } else if (type == 1) {
+ typestr = "Opcodes.F_APPEND";
+ } else if (type == 2) {
+ typestr = "Opcodes.F_CHOP";
+ } else if (type == 3) {
+ typestr = "Opcodes.F_SAME";
+ } else if (type == 4) {
+ typestr = "Opcodes.F_SAME1";
+ }
+ System.out.println("mv.visitFrame(" + typestr + ", " + nLocal + ", " + Arrays.toString(local) + ", " + nStack + ", " + Arrays.toString(stack) + ");");
+ }
+ }
+
+ public void visitJumpInsn(int opcode, Label var) { //璋冪敤姝ゆ柟娉曠殑 ClassWriter 蹇呴』鐢 COMPUTE_FRAMES 鏋勫缓
+ visitor.visitJumpInsn(opcode, var);
+ if (debug) {
+ Integer index = labels.get(var);
+ if (index == null) {
+ index = labels.size();
+ labels.put(var, index);
+ System.out.println("Label l" + index + " = new Label();");
+ }
+ System.out.println("mv.visitJumpInsn(" + opcodes[opcode] + ", l" + index + ");");
+ }
+ }
+
+ public void visitCode() {
+ visitor.visitCode();
+ if (debug) System.out.println("mv.visitCode();");
+ }
+
+ public void visitLabel(Label var) {
+ visitor.visitLabel(var);
+ if (debug) {
+ Integer index = labels.get(var);
+ if (index == null) {
+ index = labels.size();
+ labels.put(var, index);
+ System.out.println("Label l" + index + " = new Label();");
+ }
+ System.out.println("mv.visitLabel(l" + index + ");");
+ }
+ }
+
+ public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
+ visitor.visitMethodInsn(opcode, owner, name, desc, itf);
+ if (debug) System.out.println("mv.visitMethodInsn(" + opcodes[opcode] + ", \"" + owner + "\", \"" + name + "\", \"" + desc + "\", " + itf + ");");
+ }
+
+ public void visitFieldInsn(int opcode, String owner, String name, String desc) {
+ visitor.visitFieldInsn(opcode, owner, name, desc);
+ if (debug) System.out.println("mv.visitFieldInsn(" + opcodes[opcode] + ", \"" + owner + "\", \"" + name + "\", \"" + desc + "\");");
+ }
+
+ public void visitTypeInsn(int opcode, String type) {
+ visitor.visitTypeInsn(opcode, type);
+ if (debug) System.out.println("mv.visitTypeInsn(" + opcodes[opcode] + ", \"" + type + "\");");
+ }
+
+ public void visitInsn(int opcode) {
+ visitor.visitInsn(opcode);
+ if (debug) System.out.println("mv.visitInsn(" + opcodes[opcode] + ");");
+ }
+
+ public void visitIntInsn(int opcode, int value) {
+ visitor.visitIntInsn(opcode, value);
+ if (debug) System.out.println("mv.visitIntInsn(" + opcodes[opcode] + ", " + value + ");");
+ }
+
+ public void visitIincInsn(int opcode, int value) {
+ visitor.visitIincInsn(opcode, value);
+ if (debug) System.out.println("mv.visitIincInsn(" + opcode + ", " + value + ");");
+ }
+
+ public void visitLdcInsn(Object o) {
+ visitor.visitLdcInsn(o);
+ if (debug) {
+ if (o instanceof CharSequence) {
+ System.out.println("mv.visitLdcInsn(\"" + o + "\");");
+ } else if (o instanceof org.redkale.asm.Type) {
+ System.out.println("mv.visitLdcInsn(Type.getType(\"" + o + "\"));");
+ } else {
+ System.out.println("mv.visitLdcInsn(" + o + ");");
+ }
+ }
+ }
+
+ public void visitMaxs(int maxStack, int maxLocals) {
+ visitor.visitMaxs(maxStack, maxLocals);
+ if (debug) System.out.println("mv.visitMaxs(" + maxStack + ", " + maxLocals + ");");
+ }
+
+ public void visitEnd() {
+ visitor.visitEnd();
+ if (debug) System.out.println("mv.visitEnd();\r\n\r\n\r\n");
+ }
+
+ public static void pushInt(MethodDebugVisitor mv, int num) {
+ if (num < 6) {
+ mv.visitInsn(ICONST_0 + num);
+ } else if (num <= Byte.MAX_VALUE) {
+ mv.visitIntInsn(BIPUSH, num);
+ } else if (num <= Short.MAX_VALUE) {
+ mv.visitIntInsn(SIPUSH, num);
+ } else {
+ mv.visitLdcInsn(num);
+ }
+ }
+
+ public static void pushInt(MethodVisitor mv, int num) {
+ if (num < 6) {
+ mv.visitInsn(ICONST_0 + num);
+ } else if (num <= Byte.MAX_VALUE) {
+ mv.visitIntInsn(BIPUSH, num);
+ } else if (num <= Short.MAX_VALUE) {
+ mv.visitIntInsn(SIPUSH, num);
+ } else {
+ mv.visitLdcInsn(num);
+ }
+ }
+
+ public static void visitAnnotation(final AnnotationVisitor av, final Annotation ann) {
+ try {
+ for (Method anm : ann.annotationType().getMethods()) {
+ final String mname = anm.getName();
+ if ("equals".equals(mname) || "hashCode".equals(mname) || "toString".equals(mname) || "annotationType".equals(mname)) continue;
+ final Object r = anm.invoke(ann);
+ if (r instanceof String[]) {
+ AnnotationVisitor av1 = av.visitArray(mname);
+ for (String item : (String[]) r) {
+ av1.visit(null, item);
+ }
+ av1.visitEnd();
+ } else if (r instanceof Class[]) {
+ AnnotationVisitor av1 = av.visitArray(mname);
+ for (Class item : (Class[]) r) {
+ av1.visit(null, Type.getType(item));
+ }
+ av1.visitEnd();
+ } else if (r instanceof Enum[]) {
+ AnnotationVisitor av1 = av.visitArray(mname);
+ for (Enum item : (Enum[]) r) {
+ av1.visitEnum(null, Type.getDescriptor(item.getClass()), ((Enum) item).name());
+ }
+ av1.visitEnd();
+ } else if (r instanceof Annotation[]) {
+ AnnotationVisitor av1 = av.visitArray(mname);
+ for (Annotation item : (Annotation[]) r) {
+ visitAnnotation(av1.visitAnnotation(null, Type.getDescriptor(((Annotation) item).annotationType())), item);
+ }
+ av1.visitEnd();
+ } else if (r instanceof Class) {
+ av.visit(mname, Type.getType((Class) r));
+ } else if (r instanceof Enum) {
+ av.visitEnum(mname, Type.getDescriptor(r.getClass()), ((Enum) r).name());
+ } else if (r instanceof Annotation) {
+ visitAnnotation(av.visitAnnotation(null, Type.getDescriptor(((Annotation) r).annotationType())), (Annotation) r);
+ } else {
+ av.visit(mname, r);
+ }
+ }
+ av.visitEnd();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+}
diff --git a/src/main/java/org/redkale/asm/asm.txt b/src/main/java/org/redkale/asm/asm.txt
index f3f74d9ab..7719a4d13 100644
--- a/src/main/java/org/redkale/asm/asm.txt
+++ b/src/main/java/org/redkale/asm/asm.txt
@@ -1,27 +1,27 @@
-need copy classes:
-
-AnnotationVisitor.java
-AnnotationWriter.java
-Attribute.java
-ByteVector.java
-ClassReader.java
-ClassVisitor.java
-ClassWriter.java
-Context.java
-CurrentFrame.java
-Edge.java
-FieldVisitor.java
-FieldWriter.java
-Frame.java
-Handle.java
-Handler.java
-Item.java
-Label.java
-MethodVisitor.java
-MethodWriter.java
-ModuleVisitor.java
-ModuleWriter.java
-Opcodes.java
-Type.java
-TypePath.java
-TypeReference.java
+need copy classes:
+
+AnnotationVisitor.java
+AnnotationWriter.java
+Attribute.java
+ByteVector.java
+ClassReader.java
+ClassVisitor.java
+ClassWriter.java
+Context.java
+CurrentFrame.java
+Edge.java
+FieldVisitor.java
+FieldWriter.java
+Frame.java
+Handle.java
+Handler.java
+Item.java
+Label.java
+MethodVisitor.java
+MethodWriter.java
+ModuleVisitor.java
+ModuleWriter.java
+Opcodes.java
+Type.java
+TypePath.java
+TypeReference.java
diff --git a/src/main/java/org/redkale/asm/package-info.java b/src/main/java/org/redkale/asm/package-info.java
index a0d8621f7..f91083ffa 100644
--- a/src/main/java/org/redkale/asm/package-info.java
+++ b/src/main/java/org/redkale/asm/package-info.java
@@ -1,4 +1,4 @@
-/**
- * 鏈寘涓嬫墍鏈変唬鐮佸潎鏄粠/java.base/jdk/internal/org/objectweb/asm 鎷疯礉杩囨潵鐨
- */
-package org.redkale.asm;
+/**
+ * 鏈寘涓嬫墍鏈変唬鐮佸潎鏄粠/java.base/jdk/internal/org/objectweb/asm 鎷疯礉杩囨潵鐨
+ */
+package org.redkale.asm;
diff --git a/src/main/java/org/redkale/boot/ApiDocsService.java b/src/main/java/org/redkale/boot/ApiDocsService.java
index 7ad9f0782..12a65df87 100644
--- a/src/main/java/org/redkale/boot/ApiDocsService.java
+++ b/src/main/java/org/redkale/boot/ApiDocsService.java
@@ -1,535 +1,535 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.io.*;
-import java.lang.reflect.*;
-import java.math.*;
-import java.nio.charset.StandardCharsets;
-import java.util.*;
-import java.util.concurrent.atomic.*;
-import java.util.logging.*;
-import javax.persistence.*;
-import org.redkale.convert.*;
-import org.redkale.convert.json.*;
-import org.redkale.mq.MessageMultiConsumer;
-import org.redkale.net.http.*;
-import org.redkale.service.RetResult;
-import org.redkale.source.*;
-import org.redkale.util.*;
-
-/**
- * API鎺ュ彛鏂囨。鐢熸垚绫伙紝浣滅敤锛氱敓鎴怉pplication瀹炰緥涓墍鏈塇ttpServer鐨勫彲鐢℉ttpServlet鐨凙PI鎺ュ彛鏂规硶
- * 缁ф壙 HttpBaseServlet 鏄负浜嗚幏鍙 HttpMapping 淇℃伅
- * https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-public final class ApiDocsService {
-
- private static final java.lang.reflect.Type TYPE_RETRESULT_OBJECT = new TypeToken>() {
- }.getType();
-
- private static final java.lang.reflect.Type TYPE_RETRESULT_STRING = new TypeToken>() {
- }.getType();
-
- private static final java.lang.reflect.Type TYPE_RETRESULT_INTEGER = new TypeToken>() {
- }.getType();
-
- private static final java.lang.reflect.Type TYPE_RETRESULT_LONG = new TypeToken>() {
- }.getType();
-
- private final Application app; //Application鍏ㄥ眬瀵硅薄
-
- public ApiDocsService(Application app) {
- this.app = app;
- }
-
- public void run(String[] args) throws Exception {
- //鏄惁璺宠繃RPC鎺ュ彛
- final boolean skipRPC = Arrays.toString(args).toLowerCase().contains("skip-rpc") && !Arrays.toString(args).toLowerCase().contains("skip-rpc=false");
-
- List serverList = new ArrayList<>();
- Field __prefix = HttpServlet.class.getDeclaredField("_prefix");
- __prefix.setAccessible(true);
- Map>> typesMap = new LinkedHashMap<>();
- //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
- Map swaggerPathsMap = new LinkedHashMap<>();
- List swaggerServers = new ArrayList<>();
- List swaggerTags = new ArrayList<>();
- Map> swaggerComponentsMap = new LinkedHashMap<>();
- for (NodeServer node : app.servers) {
- if (!(node instanceof NodeHttpServer)) continue;
- final Map map = new LinkedHashMap<>();
- serverList.add(map);
- HttpServer server = node.getServer();
- map.put("address", server.getSocketAddress());
- swaggerServers.add(Utility.ofMap("url", "http://localhost:" + server.getSocketAddress().getPort()));
- List> servletsList = new ArrayList<>();
- map.put("servlets", servletsList);
- String plainContentType = server.getResponseConfig() == null ? "application/json" : server.getResponseConfig().plainContentType;
- if (plainContentType == null || plainContentType.isEmpty()) plainContentType = "application/json";
- if (plainContentType.indexOf(';') > 0) plainContentType = plainContentType.substring(0, plainContentType.indexOf(';'));
-
- for (HttpServlet servlet : server.getPrepareServlet().getServlets()) {
- if (!(servlet instanceof HttpServlet)) continue;
- if (servlet instanceof WebSocketServlet) continue;
- if (servlet.getClass().getAnnotation(MessageMultiConsumer.class) != null) {
- node.logger.log(Level.INFO, servlet + " be skipped because has @MessageMultiConsumer");
- continue;
- }
- WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class);
- if (ws == null) {
- node.logger.log(Level.WARNING, servlet + " not found @WebServlet");
- continue;
- }
- if (ws.name().isEmpty()) {
- node.logger.log(Level.INFO, servlet + " be skipped because @WebServlet.name is empty");
- continue;
- }
- final String tag = ws.name().isEmpty() ? servlet.getClass().getSimpleName().replace("Servlet", "").toLowerCase() : ws.name();
- final Map servletMap = new LinkedHashMap<>();
- String prefix = (String) __prefix.get(servlet);
- String[] urlregs = ws.value();
- if (prefix != null && !prefix.isEmpty()) {
- for (int i = 0; i < urlregs.length; i++) {
- urlregs[i] = prefix + urlregs[i];
- }
- }
- servletMap.put("urlregs", urlregs);
- servletMap.put("moduleid", ws.moduleid());
- servletMap.put("name", ws.name());
- servletMap.put("comment", ws.comment());
-
- List mappingsList = new ArrayList<>();
- servletMap.put("mappings", mappingsList);
- final Class selfClz = servlet.getClass();
- Class clz = servlet.getClass();
- HashSet actionUrls = new HashSet<>();
- do {
- if (Modifier.isAbstract(clz.getModifiers())) break;
- for (Method method : clz.getMethods()) {
- if (method.getParameterCount() != 2) continue;
- HttpMapping action = method.getAnnotation(HttpMapping.class);
- if (action == null) continue;
- if (!action.inherited() && selfClz != clz) continue; //蹇界暐涓嶈缁ф壙鐨勬柟娉
- if (actionUrls.contains(action.url())) continue;
- if (HttpScope.class.isAssignableFrom(action.result())) continue; //蹇界暐妯℃澘寮曟搸鐨勬柟娉
- if (action.rpconly() && skipRPC) continue; //涓嶇敓鎴怰PC鎺ュ彛
-
- final List> swaggerParamsList = new ArrayList<>();
-
- final Map mappingMap = new LinkedHashMap<>();
- mappingMap.put("url", prefix + action.url());
- actionUrls.add(action.url());
- mappingMap.put("auth", action.auth());
- mappingMap.put("actionid", action.actionid());
- mappingMap.put("comment", action.comment());
- List paramsList = new ArrayList<>();
- mappingMap.put("params", paramsList);
- List results = new ArrayList<>();
- Type resultType = action.result();
- if (!action.resultref().isEmpty()) {
- Field f = servlet.getClass().getDeclaredField(action.resultref());
- f.setAccessible(true);
- resultType = (Type) f.get(servlet);
- }
-// for (final Class rtype : action.results()) {
-// results.add(rtype.getName());
-// if (typesMap.containsKey(rtype.getName())) continue;
-// if (rtype.getName().startsWith("java.")) continue;
-// if (rtype.getName().startsWith("javax.")) continue;
-// final boolean filter = FilterBean.class.isAssignableFrom(rtype);
-// final Map> typeMap = new LinkedHashMap<>();
-// Class loop = rtype;
-// do {
-// if (loop == null || loop.isInterface()) break;
-// for (Field field : loop.getDeclaredFields()) {
-// if (Modifier.isFinal(field.getModifiers())) continue;
-// if (Modifier.isStatic(field.getModifiers())) continue;
-//
-// Map fieldmap = new LinkedHashMap<>();
-// fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());
-//
-// Comment comment = field.getAnnotation(Comment.class);
-// Column col = field.getAnnotation(Column.class);
-// FilterColumn fc = field.getAnnotation(FilterColumn.class);
-// if (comment != null) {
-// fieldmap.put("comment", comment.value());
-// } else if (col != null) {
-// fieldmap.put("comment", col.comment());
-// } else if (fc != null) {
-// fieldmap.put("comment", fc.comment());
-// }
-// fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
-// fieldmap.put("updatable", (filter || col == null || col.updatable()));
-// if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
-// if (field.getAnnotation(RestAddress.class) != null) continue;
-// }
-//
-// typeMap.put(field.getName(), fieldmap);
-// }
-// } while ((loop = loop.getSuperclass()) != Object.class);
-// typesMap.put(rtype.getName(), typeMap);
-// }
- mappingMap.put("results", results);
- boolean hasbodyparam = false;
- Map swaggerRequestBody = new LinkedHashMap<>();
- for (HttpParam param : method.getAnnotationsByType(HttpParam.class)) {
- final Map oldapisParamMap = new LinkedHashMap<>();
- final boolean isarray = param.type().isArray();
- final Class ptype = isarray ? param.type().getComponentType() : param.type();
- oldapisParamMap.put("name", param.name());
- oldapisParamMap.put("radix", param.radix());
- oldapisParamMap.put("type", ptype.getName() + (isarray ? "[]" : ""));
- oldapisParamMap.put("style", param.style());
- oldapisParamMap.put("comment", param.comment());
- oldapisParamMap.put("required", param.required());
- paramsList.add(oldapisParamMap);
- {
- final Map paramSchemaMap = new LinkedHashMap<>();
- Type paramGenericType = param.type();
- if (!param.typeref().isEmpty()) {
- Field f = servlet.getClass().getDeclaredField(param.typeref());
- f.setAccessible(true);
- paramGenericType = (Type) f.get(servlet);
- }
- simpleSchemaType(node.getLogger(), swaggerComponentsMap, param.type(), paramGenericType, paramSchemaMap, true);
- if (param.style() == HttpParam.HttpParameterStyle.BODY) {
- swaggerRequestBody.put("description", param.comment());
- swaggerRequestBody.put("content", Utility.ofMap(plainContentType, Utility.ofMap("schema", paramSchemaMap)));
- } else {
- final Map swaggerParamMap = new LinkedHashMap<>();
- swaggerParamMap.put("name", param.name());
- swaggerParamMap.put("in", param.style().name().toLowerCase());
- swaggerParamMap.put("description", param.comment());
- swaggerParamMap.put("required", param.required());
- if (param.deprecated()) {
- swaggerParamMap.put("deprecated", param.deprecated());
- }
- //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle
- swaggerParamMap.put("style", param.style() == HttpParam.HttpParameterStyle.HEADER || param.name().indexOf('#') == 0 ? "simple" : "form");
- swaggerParamMap.put("explode", true);
- swaggerParamMap.put("schema", paramSchemaMap);
- Object example = formatExample(param.example(), param.type(), paramGenericType);
- if (example != null) swaggerParamMap.put("example", example);
- if (!param.example().isEmpty()) {
- swaggerParamMap.put("example", param.example());
- }
- swaggerParamsList.add(swaggerParamMap);
- }
- }
- if (param.style() == HttpParam.HttpParameterStyle.BODY) hasbodyparam = true;
- if (ptype.isPrimitive() || ptype == String.class) continue;
- if (typesMap.containsKey(ptype.getName())) continue;
- if (ptype.getName().startsWith("java.")) continue;
- if (ptype.getName().startsWith("javax.")) continue;
-
- final Map> typeMap = new LinkedHashMap<>();
- Class loop = ptype;
- final boolean filter = FilterBean.class.isAssignableFrom(loop);
- do {
- if (loop == null || loop.isInterface()) break;
- for (Field field : loop.getDeclaredFields()) {
- if (Modifier.isFinal(field.getModifiers())) continue;
- if (Modifier.isStatic(field.getModifiers())) continue;
-
- Map fieldmap = new LinkedHashMap<>();
- fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());
-
- Column col = field.getAnnotation(Column.class);
- FilterColumn fc = field.getAnnotation(FilterColumn.class);
- Comment comment = field.getAnnotation(Comment.class);
- if (comment != null) {
- fieldmap.put("comment", comment.value());
- } else if (col != null) {
- fieldmap.put("comment", col.comment());
- } else if (fc != null) {
- fieldmap.put("comment", fc.comment());
- }
- fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
- fieldmap.put("updatable", (filter || col == null || col.updatable()));
-
- if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
- if (field.getAnnotation(RestAddress.class) != null) continue;
- }
-
- typeMap.put(field.getName(), fieldmap);
- }
- } while ((loop = loop.getSuperclass()) != Object.class);
-
- typesMap.put(ptype.getName(), typeMap);
- }
- mappingMap.put("result", action.result().getSimpleName().replace("void", "Object"));
- mappingsList.add(mappingMap);
-
- final Map swaggerOperatMap = new LinkedHashMap<>();
- swaggerOperatMap.put("tags", new String[]{tag});
- swaggerOperatMap.put("operationId", action.name());
- if (method.getAnnotation(Deprecated.class) != null) {
- swaggerOperatMap.put("deprecated", true);
- }
- Map respSchemaMap = new LinkedHashMap<>();
- simpleSchemaType(node.getLogger(), swaggerComponentsMap, action.result(), resultType, respSchemaMap, true);
-
- Map respMap = new LinkedHashMap<>();
- respMap.put("schema", respSchemaMap);
- Object example = formatExample(action.example(), action.result(), resultType);
- if (example != null) swaggerOperatMap.put("example", example);
- if (!swaggerRequestBody.isEmpty()) swaggerOperatMap.put("requestBody", swaggerRequestBody);
- swaggerOperatMap.put("parameters", swaggerParamsList);
- String actiondesc = action.comment();
- if (action.rpconly()) actiondesc = "[Only for RPC API] " + actiondesc;
- swaggerOperatMap.put("responses", Utility.ofMap("200", Utility.ofMap("description", actiondesc, "content", Utility.ofMap("application/json", respMap))));
-
- String m = action.methods() == null || action.methods().length == 0 ? null : action.methods()[0].toLowerCase();
- if (m == null) {
- m = hasbodyparam || TYPE_RETRESULT_STRING.equals(resultType) || TYPE_RETRESULT_INTEGER.equals(resultType)
- || TYPE_RETRESULT_LONG.equals(resultType) || action.name().contains("create") || action.name().contains("insert")
- || action.name().contains("update") || action.name().contains("delete") || action.name().contains("send") ? "post" : "get";
- }
- swaggerPathsMap.put(prefix + action.url(), Utility.ofMap("description", action.comment(), m, swaggerOperatMap));
- }
- } while ((clz = clz.getSuperclass()) != HttpServlet.class);
- mappingsList.sort((o1, o2) -> ((String) o1.get("url")).compareTo((String) o2.get("url")));
- servletsList.add(servletMap);
- if (!actionUrls.isEmpty()) swaggerTags.add(Utility.ofMap("name", tag, "description", ws.comment()));
- }
- servletsList.sort((o1, o2) -> {
- String[] urlregs1 = (String[]) o1.get("urlregs");
- String[] urlregs2 = (String[]) o2.get("urlregs");
- return urlregs1.length > 0 ? (urlregs2.length > 0 ? urlregs1[0].compareTo(urlregs2[0]) : 1) : -1;
- });
- }
- { // https://github.com/OAI/OpenAPI-Specification
- Map swaggerResultMap = new LinkedHashMap<>();
- swaggerResultMap.put("openapi", "3.0.0");
- Map infomap = new LinkedHashMap<>();
- infomap.put("title", "Redkale generate apidoc");
- infomap.put("version", "1.0.0");
- swaggerResultMap.put("info", infomap);
- swaggerResultMap.put("servers", swaggerServers);
- swaggerResultMap.put("paths", swaggerPathsMap);
- swaggerResultMap.put("tags", swaggerTags);
- if (!swaggerComponentsMap.isEmpty()) swaggerResultMap.put("components", Utility.ofMap("schemas", swaggerComponentsMap));
- final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "openapi-doc.json"));
- out.write(JsonConvert.root().convertTo(swaggerResultMap).getBytes(StandardCharsets.UTF_8));
- out.close();
- }
- {
- Map oldapisResultMap = new LinkedHashMap<>();
- oldapisResultMap.put("servers", serverList);
- oldapisResultMap.put("types", typesMap);
- final String json = JsonConvert.root().convertTo(oldapisResultMap);
- final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "apidoc.json"));
- out.write(json.getBytes(StandardCharsets.UTF_8));
- out.close();
- File doctemplate = new File(app.getConfPath().toString(), "apidoc-template.html");
- InputStream in = null;
- if (doctemplate.isFile() && doctemplate.canRead()) {
- in = new FileInputStream(doctemplate);
- }
- if (in == null) in = ApiDocsService.class.getResourceAsStream("apidoc-template.html");
- String content = Utility.read(in).replace("'${content}'", json);
- in.close();
- FileOutputStream outhtml = new FileOutputStream(new File(app.getHome(), "apidoc.html"));
- outhtml.write(content.getBytes(StandardCharsets.UTF_8));
- outhtml.close();
- }
- }
-
- private static void simpleSchemaType(Logger logger, Map> componentsMap, Class type, Type genericType, Map schemaMap, boolean recursive) {
- if (type == int.class || type == Integer.class || type == AtomicInteger.class) {
- schemaMap.put("type", "integer");
- schemaMap.put("format", "int32");
- } else if (type == long.class || type == Long.class
- || type == AtomicLong.class || type == LongAdder.class || type == BigInteger.class) {
- schemaMap.put("type", "integer");
- schemaMap.put("format", "int64");
- } else if (type == float.class || type == Float.class) {
- schemaMap.put("type", "number");
- schemaMap.put("format", "float");
- } else if (type == double.class || type == Double.class || type == BigDecimal.class) {
- schemaMap.put("type", "number");
- schemaMap.put("format", "double");
- } else if (type == boolean.class || type == Boolean.class || type == AtomicBoolean.class) {
- schemaMap.put("type", "boolean");
- } else if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
- schemaMap.put("type", "number");
- } else if (type == String.class || CharSequence.class.isAssignableFrom(type)) {
- schemaMap.put("type", "string");
- } else if (recursive && (type.isArray() || Collection.class.isAssignableFrom(type))) {
- schemaMap.put("type", "array");
- Map sbumap = new LinkedHashMap<>();
- if (type.isArray()) {
- simpleSchemaType(logger, componentsMap, type.getComponentType(), type.getComponentType(), sbumap, false);
- } else if (genericType instanceof ParameterizedType) {
- Type subpt = ((ParameterizedType) genericType).getActualTypeArguments()[0];
- if (subpt instanceof Class) {
- simpleSchemaType(logger, componentsMap, (Class) subpt, subpt, sbumap, false);
- } else if (subpt instanceof ParameterizedType && ((ParameterizedType) subpt).getOwnerType() instanceof Class) {
- simpleSchemaType(logger, componentsMap, (Class) ((ParameterizedType) subpt).getOwnerType(), subpt, sbumap, false);
- } else {
- sbumap.put("type", "object");
- }
- } else {
- sbumap.put("type", "object");
- }
- schemaMap.put("items", sbumap);
- } else if (!type.getName().startsWith("java.") && !type.getName().startsWith("javax.")) {
- String ct = simpleComponentType(logger, componentsMap, type, genericType);
- if (ct == null) {
- schemaMap.put("type", "object");
- } else {
- schemaMap.put("$ref", "#/components/schemas/" + ct);
- }
- } else {
- schemaMap.put("type", "object");
- }
- }
-
- private static String simpleComponentType(Logger logger, Map> componentsMap, Class type, Type genericType) {
- try {
- Encodeable encodeable = JsonFactory.root().loadEncoder(genericType);
- String ct = componentKey(logger, componentsMap, null, encodeable, true);
- if (ct == null || ct.length() == 0) return null;
- if (componentsMap.containsKey(ct)) return ct;
- Map cmap = new LinkedHashMap<>();
- componentsMap.put(ct, cmap); //蹇呴』鍦ㄨ皟鐢╯impleSchemaType涔嬪墠put锛屼笉鐒跺祵濂楁儏鍐典笅姝诲惊鐜
-
- cmap.put("type", "object");
- List requireds = new ArrayList<>();
- Map properties = new LinkedHashMap<>();
- if (encodeable instanceof ObjectEncoder) {
- for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
- Map schemaMap = new LinkedHashMap<>();
- simpleSchemaType(logger, componentsMap, TypeToken.typeToClassOrElse(member.getEncoder().getType(), Object.class), member.getEncoder().getType(), schemaMap, true);
- String desc = "";
- if (member.getField() != null) {
- Column col = member.getField().getAnnotation(Column.class);
- if (col == null) {
- FilterColumn fcol = member.getField().getAnnotation(FilterColumn.class);
- if (fcol != null) {
- desc = fcol.comment();
- if (fcol.required()) requireds.add(member.getAttribute().field());
- }
- } else {
- desc = col.comment();
- if (!col.nullable()) requireds.add(member.getAttribute().field());
- }
- if (desc.isEmpty() && member.getField().getAnnotation(Comment.class) != null) {
- desc = member.getField().getAnnotation(Comment.class).value();
- }
- } else if (member.getMethod() != null) {
- Column col = member.getMethod().getAnnotation(Column.class);
- if (col == null) {
- FilterColumn fcol = member.getMethod().getAnnotation(FilterColumn.class);
- if (fcol != null) {
- desc = fcol.comment();
- if (fcol.required()) requireds.add(member.getAttribute().field());
- }
- } else {
- desc = col.comment();
- if (!col.nullable()) requireds.add(member.getAttribute().field());
- }
- if (desc.isEmpty() && member.getMethod().getAnnotation(Comment.class) != null) {
- desc = member.getMethod().getAnnotation(Comment.class).value();
- }
- }
- if (!desc.isEmpty()) schemaMap.put("description", desc);
- properties.put(member.getAttribute().field(), schemaMap);
- }
- }
- if (!requireds.isEmpty()) cmap.put("required", requireds);
- cmap.put("properties", properties);
- return ct;
- } catch (Exception e) {
- logger.log(Level.WARNING, genericType + " generate component info error", e);
- return null;
- }
- }
-
- private static String componentKey(Logger logger, Map> componentsMap, EnMember field, Encodeable encodeable, boolean first) {
- if (encodeable instanceof ObjectEncoder) {
- StringBuilder sb = new StringBuilder();
- sb.append(((ObjectEncoder) encodeable).getTypeClass().getSimpleName());
- for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
- if (member.getEncoder() instanceof ArrayEncoder
- || member.getEncoder() instanceof CollectionEncoder) {
- String subsb = componentKey(logger, componentsMap, member, member.getEncoder(), false);
- if (subsb == null) return null;
- AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
- if (real == null) continue;
- Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
- Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
- if (cz == ct) continue;
- if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
- sb.append(subsb);
- } else if (member.getEncoder() instanceof ObjectEncoder || member.getEncoder() instanceof SimpledCoder) {
- AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
- if (real == null) continue;
- if (member.getEncoder() instanceof SimpledCoder) {
- simpleSchemaType(logger, componentsMap, ((SimpledCoder) member.getEncoder()).getType(), ((SimpledCoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
- } else {
- simpleSchemaType(logger, componentsMap, ((ObjectEncoder) member.getEncoder()).getTypeClass(), ((ObjectEncoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
- }
- Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
- Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
- if (cz == ct) continue;
- String subsb = componentKey(logger, componentsMap, member, member.getEncoder(), false);
- if (subsb == null) return null;
- if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
- sb.append(subsb);
- } else if (member.getEncoder() instanceof MapEncoder) {
- continue;
- } else {
- return null;
- }
- }
- return sb.toString();
- } else if (encodeable instanceof ArrayEncoder || encodeable instanceof CollectionEncoder) {
- final boolean array = (encodeable instanceof ArrayEncoder);
- Encodeable subEncodeable = array ? ((ArrayEncoder) encodeable).getComponentEncoder() : ((CollectionEncoder) encodeable).getComponentEncoder();
- if (subEncodeable instanceof SimpledCoder && field != null) return "";
- final String sb = componentKey(logger, componentsMap, null, subEncodeable, false);
- if (sb == null || sb.isEmpty()) return sb;
- if (field != null && field.getField() != null && field.getField().getDeclaringClass() == Sheet.class) {
- return sb;
- }
- return sb + (array ? "_Array" : "_Collection");
- } else if (encodeable instanceof SimpledCoder) {
- Class stype = ((SimpledCoder) encodeable).getType();
- if (stype.isPrimitive() || stype == Boolean.class || Number.class.isAssignableFrom(stype) || CharSequence.class.isAssignableFrom(stype)) {
- return stype.getSimpleName();
- }
- return "";
- } else if (encodeable instanceof MapEncoder) {
- return first ? null : "";
- } else {
- return null;
- }
- }
-
- private static Object formatExample(String example, Class type, Type genericType) {
- if (example == null || example.isEmpty()) return null;
- if (type == Flipper.class) {
- return new Flipper();
- } else if (TYPE_RETRESULT_OBJECT.equals(genericType)) {
- return RetResult.success();
- } else if (TYPE_RETRESULT_STRING.equals(genericType)) {
- return RetResult.success();
- } else if (TYPE_RETRESULT_INTEGER.equals(genericType)) {
- return RetResult.success(0);
- } else if (TYPE_RETRESULT_LONG.equals(genericType)) {
- return RetResult.success(0L);
- }
- return example;
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.math.*;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.atomic.*;
+import java.util.logging.*;
+import javax.persistence.*;
+import org.redkale.convert.*;
+import org.redkale.convert.json.*;
+import org.redkale.mq.MessageMultiConsumer;
+import org.redkale.net.http.*;
+import org.redkale.service.RetResult;
+import org.redkale.source.*;
+import org.redkale.util.*;
+
+/**
+ * API鎺ュ彛鏂囨。鐢熸垚绫伙紝浣滅敤锛氱敓鎴怉pplication瀹炰緥涓墍鏈塇ttpServer鐨勫彲鐢℉ttpServlet鐨凙PI鎺ュ彛鏂规硶
+ * 缁ф壙 HttpBaseServlet 鏄负浜嗚幏鍙 HttpMapping 淇℃伅
+ * https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+public final class ApiDocsService {
+
+ private static final java.lang.reflect.Type TYPE_RETRESULT_OBJECT = new TypeToken>() {
+ }.getType();
+
+ private static final java.lang.reflect.Type TYPE_RETRESULT_STRING = new TypeToken>() {
+ }.getType();
+
+ private static final java.lang.reflect.Type TYPE_RETRESULT_INTEGER = new TypeToken>() {
+ }.getType();
+
+ private static final java.lang.reflect.Type TYPE_RETRESULT_LONG = new TypeToken>() {
+ }.getType();
+
+ private final Application app; //Application鍏ㄥ眬瀵硅薄
+
+ public ApiDocsService(Application app) {
+ this.app = app;
+ }
+
+ public void run(String[] args) throws Exception {
+ //鏄惁璺宠繃RPC鎺ュ彛
+ final boolean skipRPC = Arrays.toString(args).toLowerCase().contains("skip-rpc") && !Arrays.toString(args).toLowerCase().contains("skip-rpc=false");
+
+ List serverList = new ArrayList<>();
+ Field __prefix = HttpServlet.class.getDeclaredField("_prefix");
+ __prefix.setAccessible(true);
+ Map>> typesMap = new LinkedHashMap<>();
+ //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
+ Map swaggerPathsMap = new LinkedHashMap<>();
+ List swaggerServers = new ArrayList<>();
+ List swaggerTags = new ArrayList<>();
+ Map> swaggerComponentsMap = new LinkedHashMap<>();
+ for (NodeServer node : app.servers) {
+ if (!(node instanceof NodeHttpServer)) continue;
+ final Map map = new LinkedHashMap<>();
+ serverList.add(map);
+ HttpServer server = node.getServer();
+ map.put("address", server.getSocketAddress());
+ swaggerServers.add(Utility.ofMap("url", "http://localhost:" + server.getSocketAddress().getPort()));
+ List> servletsList = new ArrayList<>();
+ map.put("servlets", servletsList);
+ String plainContentType = server.getResponseConfig() == null ? "application/json" : server.getResponseConfig().plainContentType;
+ if (plainContentType == null || plainContentType.isEmpty()) plainContentType = "application/json";
+ if (plainContentType.indexOf(';') > 0) plainContentType = plainContentType.substring(0, plainContentType.indexOf(';'));
+
+ for (HttpServlet servlet : server.getPrepareServlet().getServlets()) {
+ if (!(servlet instanceof HttpServlet)) continue;
+ if (servlet instanceof WebSocketServlet) continue;
+ if (servlet.getClass().getAnnotation(MessageMultiConsumer.class) != null) {
+ node.logger.log(Level.INFO, servlet + " be skipped because has @MessageMultiConsumer");
+ continue;
+ }
+ WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class);
+ if (ws == null) {
+ node.logger.log(Level.WARNING, servlet + " not found @WebServlet");
+ continue;
+ }
+ if (ws.name().isEmpty()) {
+ node.logger.log(Level.INFO, servlet + " be skipped because @WebServlet.name is empty");
+ continue;
+ }
+ final String tag = ws.name().isEmpty() ? servlet.getClass().getSimpleName().replace("Servlet", "").toLowerCase() : ws.name();
+ final Map servletMap = new LinkedHashMap<>();
+ String prefix = (String) __prefix.get(servlet);
+ String[] urlregs = ws.value();
+ if (prefix != null && !prefix.isEmpty()) {
+ for (int i = 0; i < urlregs.length; i++) {
+ urlregs[i] = prefix + urlregs[i];
+ }
+ }
+ servletMap.put("urlregs", urlregs);
+ servletMap.put("moduleid", ws.moduleid());
+ servletMap.put("name", ws.name());
+ servletMap.put("comment", ws.comment());
+
+ List mappingsList = new ArrayList<>();
+ servletMap.put("mappings", mappingsList);
+ final Class selfClz = servlet.getClass();
+ Class clz = servlet.getClass();
+ HashSet actionUrls = new HashSet<>();
+ do {
+ if (Modifier.isAbstract(clz.getModifiers())) break;
+ for (Method method : clz.getMethods()) {
+ if (method.getParameterCount() != 2) continue;
+ HttpMapping action = method.getAnnotation(HttpMapping.class);
+ if (action == null) continue;
+ if (!action.inherited() && selfClz != clz) continue; //蹇界暐涓嶈缁ф壙鐨勬柟娉
+ if (actionUrls.contains(action.url())) continue;
+ if (HttpScope.class.isAssignableFrom(action.result())) continue; //蹇界暐妯℃澘寮曟搸鐨勬柟娉
+ if (action.rpconly() && skipRPC) continue; //涓嶇敓鎴怰PC鎺ュ彛
+
+ final List> swaggerParamsList = new ArrayList<>();
+
+ final Map mappingMap = new LinkedHashMap<>();
+ mappingMap.put("url", prefix + action.url());
+ actionUrls.add(action.url());
+ mappingMap.put("auth", action.auth());
+ mappingMap.put("actionid", action.actionid());
+ mappingMap.put("comment", action.comment());
+ List paramsList = new ArrayList<>();
+ mappingMap.put("params", paramsList);
+ List results = new ArrayList<>();
+ Type resultType = action.result();
+ if (!action.resultref().isEmpty()) {
+ Field f = servlet.getClass().getDeclaredField(action.resultref());
+ f.setAccessible(true);
+ resultType = (Type) f.get(servlet);
+ }
+// for (final Class rtype : action.results()) {
+// results.add(rtype.getName());
+// if (typesMap.containsKey(rtype.getName())) continue;
+// if (rtype.getName().startsWith("java.")) continue;
+// if (rtype.getName().startsWith("javax.")) continue;
+// final boolean filter = FilterBean.class.isAssignableFrom(rtype);
+// final Map> typeMap = new LinkedHashMap<>();
+// Class loop = rtype;
+// do {
+// if (loop == null || loop.isInterface()) break;
+// for (Field field : loop.getDeclaredFields()) {
+// if (Modifier.isFinal(field.getModifiers())) continue;
+// if (Modifier.isStatic(field.getModifiers())) continue;
+//
+// Map fieldmap = new LinkedHashMap<>();
+// fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());
+//
+// Comment comment = field.getAnnotation(Comment.class);
+// Column col = field.getAnnotation(Column.class);
+// FilterColumn fc = field.getAnnotation(FilterColumn.class);
+// if (comment != null) {
+// fieldmap.put("comment", comment.value());
+// } else if (col != null) {
+// fieldmap.put("comment", col.comment());
+// } else if (fc != null) {
+// fieldmap.put("comment", fc.comment());
+// }
+// fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
+// fieldmap.put("updatable", (filter || col == null || col.updatable()));
+// if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
+// if (field.getAnnotation(RestAddress.class) != null) continue;
+// }
+//
+// typeMap.put(field.getName(), fieldmap);
+// }
+// } while ((loop = loop.getSuperclass()) != Object.class);
+// typesMap.put(rtype.getName(), typeMap);
+// }
+ mappingMap.put("results", results);
+ boolean hasbodyparam = false;
+ Map swaggerRequestBody = new LinkedHashMap<>();
+ for (HttpParam param : method.getAnnotationsByType(HttpParam.class)) {
+ final Map oldapisParamMap = new LinkedHashMap<>();
+ final boolean isarray = param.type().isArray();
+ final Class ptype = isarray ? param.type().getComponentType() : param.type();
+ oldapisParamMap.put("name", param.name());
+ oldapisParamMap.put("radix", param.radix());
+ oldapisParamMap.put("type", ptype.getName() + (isarray ? "[]" : ""));
+ oldapisParamMap.put("style", param.style());
+ oldapisParamMap.put("comment", param.comment());
+ oldapisParamMap.put("required", param.required());
+ paramsList.add(oldapisParamMap);
+ {
+ final Map paramSchemaMap = new LinkedHashMap<>();
+ Type paramGenericType = param.type();
+ if (!param.typeref().isEmpty()) {
+ Field f = servlet.getClass().getDeclaredField(param.typeref());
+ f.setAccessible(true);
+ paramGenericType = (Type) f.get(servlet);
+ }
+ simpleSchemaType(node.getLogger(), swaggerComponentsMap, param.type(), paramGenericType, paramSchemaMap, true);
+ if (param.style() == HttpParam.HttpParameterStyle.BODY) {
+ swaggerRequestBody.put("description", param.comment());
+ swaggerRequestBody.put("content", Utility.ofMap(plainContentType, Utility.ofMap("schema", paramSchemaMap)));
+ } else {
+ final Map swaggerParamMap = new LinkedHashMap<>();
+ swaggerParamMap.put("name", param.name());
+ swaggerParamMap.put("in", param.style().name().toLowerCase());
+ swaggerParamMap.put("description", param.comment());
+ swaggerParamMap.put("required", param.required());
+ if (param.deprecated()) {
+ swaggerParamMap.put("deprecated", param.deprecated());
+ }
+ //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle
+ swaggerParamMap.put("style", param.style() == HttpParam.HttpParameterStyle.HEADER || param.name().indexOf('#') == 0 ? "simple" : "form");
+ swaggerParamMap.put("explode", true);
+ swaggerParamMap.put("schema", paramSchemaMap);
+ Object example = formatExample(param.example(), param.type(), paramGenericType);
+ if (example != null) swaggerParamMap.put("example", example);
+ if (!param.example().isEmpty()) {
+ swaggerParamMap.put("example", param.example());
+ }
+ swaggerParamsList.add(swaggerParamMap);
+ }
+ }
+ if (param.style() == HttpParam.HttpParameterStyle.BODY) hasbodyparam = true;
+ if (ptype.isPrimitive() || ptype == String.class) continue;
+ if (typesMap.containsKey(ptype.getName())) continue;
+ if (ptype.getName().startsWith("java.")) continue;
+ if (ptype.getName().startsWith("javax.")) continue;
+
+ final Map> typeMap = new LinkedHashMap<>();
+ Class loop = ptype;
+ final boolean filter = FilterBean.class.isAssignableFrom(loop);
+ do {
+ if (loop == null || loop.isInterface()) break;
+ for (Field field : loop.getDeclaredFields()) {
+ if (Modifier.isFinal(field.getModifiers())) continue;
+ if (Modifier.isStatic(field.getModifiers())) continue;
+
+ Map fieldmap = new LinkedHashMap<>();
+ fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());
+
+ Column col = field.getAnnotation(Column.class);
+ FilterColumn fc = field.getAnnotation(FilterColumn.class);
+ Comment comment = field.getAnnotation(Comment.class);
+ if (comment != null) {
+ fieldmap.put("comment", comment.value());
+ } else if (col != null) {
+ fieldmap.put("comment", col.comment());
+ } else if (fc != null) {
+ fieldmap.put("comment", fc.comment());
+ }
+ fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
+ fieldmap.put("updatable", (filter || col == null || col.updatable()));
+
+ if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
+ if (field.getAnnotation(RestAddress.class) != null) continue;
+ }
+
+ typeMap.put(field.getName(), fieldmap);
+ }
+ } while ((loop = loop.getSuperclass()) != Object.class);
+
+ typesMap.put(ptype.getName(), typeMap);
+ }
+ mappingMap.put("result", action.result().getSimpleName().replace("void", "Object"));
+ mappingsList.add(mappingMap);
+
+ final Map swaggerOperatMap = new LinkedHashMap<>();
+ swaggerOperatMap.put("tags", new String[]{tag});
+ swaggerOperatMap.put("operationId", action.name());
+ if (method.getAnnotation(Deprecated.class) != null) {
+ swaggerOperatMap.put("deprecated", true);
+ }
+ Map respSchemaMap = new LinkedHashMap<>();
+ simpleSchemaType(node.getLogger(), swaggerComponentsMap, action.result(), resultType, respSchemaMap, true);
+
+ Map respMap = new LinkedHashMap<>();
+ respMap.put("schema", respSchemaMap);
+ Object example = formatExample(action.example(), action.result(), resultType);
+ if (example != null) swaggerOperatMap.put("example", example);
+ if (!swaggerRequestBody.isEmpty()) swaggerOperatMap.put("requestBody", swaggerRequestBody);
+ swaggerOperatMap.put("parameters", swaggerParamsList);
+ String actiondesc = action.comment();
+ if (action.rpconly()) actiondesc = "[Only for RPC API] " + actiondesc;
+ swaggerOperatMap.put("responses", Utility.ofMap("200", Utility.ofMap("description", actiondesc, "content", Utility.ofMap("application/json", respMap))));
+
+ String m = action.methods() == null || action.methods().length == 0 ? null : action.methods()[0].toLowerCase();
+ if (m == null) {
+ m = hasbodyparam || TYPE_RETRESULT_STRING.equals(resultType) || TYPE_RETRESULT_INTEGER.equals(resultType)
+ || TYPE_RETRESULT_LONG.equals(resultType) || action.name().contains("create") || action.name().contains("insert")
+ || action.name().contains("update") || action.name().contains("delete") || action.name().contains("send") ? "post" : "get";
+ }
+ swaggerPathsMap.put(prefix + action.url(), Utility.ofMap("description", action.comment(), m, swaggerOperatMap));
+ }
+ } while ((clz = clz.getSuperclass()) != HttpServlet.class);
+ mappingsList.sort((o1, o2) -> ((String) o1.get("url")).compareTo((String) o2.get("url")));
+ servletsList.add(servletMap);
+ if (!actionUrls.isEmpty()) swaggerTags.add(Utility.ofMap("name", tag, "description", ws.comment()));
+ }
+ servletsList.sort((o1, o2) -> {
+ String[] urlregs1 = (String[]) o1.get("urlregs");
+ String[] urlregs2 = (String[]) o2.get("urlregs");
+ return urlregs1.length > 0 ? (urlregs2.length > 0 ? urlregs1[0].compareTo(urlregs2[0]) : 1) : -1;
+ });
+ }
+ { // https://github.com/OAI/OpenAPI-Specification
+ Map swaggerResultMap = new LinkedHashMap<>();
+ swaggerResultMap.put("openapi", "3.0.0");
+ Map infomap = new LinkedHashMap<>();
+ infomap.put("title", "Redkale generate apidoc");
+ infomap.put("version", "1.0.0");
+ swaggerResultMap.put("info", infomap);
+ swaggerResultMap.put("servers", swaggerServers);
+ swaggerResultMap.put("paths", swaggerPathsMap);
+ swaggerResultMap.put("tags", swaggerTags);
+ if (!swaggerComponentsMap.isEmpty()) swaggerResultMap.put("components", Utility.ofMap("schemas", swaggerComponentsMap));
+ final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "openapi-doc.json"));
+ out.write(JsonConvert.root().convertTo(swaggerResultMap).getBytes(StandardCharsets.UTF_8));
+ out.close();
+ }
+ {
+ Map oldapisResultMap = new LinkedHashMap<>();
+ oldapisResultMap.put("servers", serverList);
+ oldapisResultMap.put("types", typesMap);
+ final String json = JsonConvert.root().convertTo(oldapisResultMap);
+ final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "apidoc.json"));
+ out.write(json.getBytes(StandardCharsets.UTF_8));
+ out.close();
+ File doctemplate = new File(app.getConfPath().toString(), "apidoc-template.html");
+ InputStream in = null;
+ if (doctemplate.isFile() && doctemplate.canRead()) {
+ in = new FileInputStream(doctemplate);
+ }
+ if (in == null) in = ApiDocsService.class.getResourceAsStream("apidoc-template.html");
+ String content = Utility.read(in).replace("'${content}'", json);
+ in.close();
+ FileOutputStream outhtml = new FileOutputStream(new File(app.getHome(), "apidoc.html"));
+ outhtml.write(content.getBytes(StandardCharsets.UTF_8));
+ outhtml.close();
+ }
+ }
+
+ private static void simpleSchemaType(Logger logger, Map> componentsMap, Class type, Type genericType, Map schemaMap, boolean recursive) {
+ if (type == int.class || type == Integer.class || type == AtomicInteger.class) {
+ schemaMap.put("type", "integer");
+ schemaMap.put("format", "int32");
+ } else if (type == long.class || type == Long.class
+ || type == AtomicLong.class || type == LongAdder.class || type == BigInteger.class) {
+ schemaMap.put("type", "integer");
+ schemaMap.put("format", "int64");
+ } else if (type == float.class || type == Float.class) {
+ schemaMap.put("type", "number");
+ schemaMap.put("format", "float");
+ } else if (type == double.class || type == Double.class || type == BigDecimal.class) {
+ schemaMap.put("type", "number");
+ schemaMap.put("format", "double");
+ } else if (type == boolean.class || type == Boolean.class || type == AtomicBoolean.class) {
+ schemaMap.put("type", "boolean");
+ } else if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
+ schemaMap.put("type", "number");
+ } else if (type == String.class || CharSequence.class.isAssignableFrom(type)) {
+ schemaMap.put("type", "string");
+ } else if (recursive && (type.isArray() || Collection.class.isAssignableFrom(type))) {
+ schemaMap.put("type", "array");
+ Map sbumap = new LinkedHashMap<>();
+ if (type.isArray()) {
+ simpleSchemaType(logger, componentsMap, type.getComponentType(), type.getComponentType(), sbumap, false);
+ } else if (genericType instanceof ParameterizedType) {
+ Type subpt = ((ParameterizedType) genericType).getActualTypeArguments()[0];
+ if (subpt instanceof Class) {
+ simpleSchemaType(logger, componentsMap, (Class) subpt, subpt, sbumap, false);
+ } else if (subpt instanceof ParameterizedType && ((ParameterizedType) subpt).getOwnerType() instanceof Class) {
+ simpleSchemaType(logger, componentsMap, (Class) ((ParameterizedType) subpt).getOwnerType(), subpt, sbumap, false);
+ } else {
+ sbumap.put("type", "object");
+ }
+ } else {
+ sbumap.put("type", "object");
+ }
+ schemaMap.put("items", sbumap);
+ } else if (!type.getName().startsWith("java.") && !type.getName().startsWith("javax.")) {
+ String ct = simpleComponentType(logger, componentsMap, type, genericType);
+ if (ct == null) {
+ schemaMap.put("type", "object");
+ } else {
+ schemaMap.put("$ref", "#/components/schemas/" + ct);
+ }
+ } else {
+ schemaMap.put("type", "object");
+ }
+ }
+
+ private static String simpleComponentType(Logger logger, Map> componentsMap, Class type, Type genericType) {
+ try {
+ Encodeable encodeable = JsonFactory.root().loadEncoder(genericType);
+ String ct = componentKey(logger, componentsMap, null, encodeable, true);
+ if (ct == null || ct.length() == 0) return null;
+ if (componentsMap.containsKey(ct)) return ct;
+ Map cmap = new LinkedHashMap<>();
+ componentsMap.put(ct, cmap); //蹇呴』鍦ㄨ皟鐢╯impleSchemaType涔嬪墠put锛屼笉鐒跺祵濂楁儏鍐典笅姝诲惊鐜
+
+ cmap.put("type", "object");
+ List requireds = new ArrayList<>();
+ Map properties = new LinkedHashMap<>();
+ if (encodeable instanceof ObjectEncoder) {
+ for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
+ Map schemaMap = new LinkedHashMap<>();
+ simpleSchemaType(logger, componentsMap, TypeToken.typeToClassOrElse(member.getEncoder().getType(), Object.class), member.getEncoder().getType(), schemaMap, true);
+ String desc = "";
+ if (member.getField() != null) {
+ Column col = member.getField().getAnnotation(Column.class);
+ if (col == null) {
+ FilterColumn fcol = member.getField().getAnnotation(FilterColumn.class);
+ if (fcol != null) {
+ desc = fcol.comment();
+ if (fcol.required()) requireds.add(member.getAttribute().field());
+ }
+ } else {
+ desc = col.comment();
+ if (!col.nullable()) requireds.add(member.getAttribute().field());
+ }
+ if (desc.isEmpty() && member.getField().getAnnotation(Comment.class) != null) {
+ desc = member.getField().getAnnotation(Comment.class).value();
+ }
+ } else if (member.getMethod() != null) {
+ Column col = member.getMethod().getAnnotation(Column.class);
+ if (col == null) {
+ FilterColumn fcol = member.getMethod().getAnnotation(FilterColumn.class);
+ if (fcol != null) {
+ desc = fcol.comment();
+ if (fcol.required()) requireds.add(member.getAttribute().field());
+ }
+ } else {
+ desc = col.comment();
+ if (!col.nullable()) requireds.add(member.getAttribute().field());
+ }
+ if (desc.isEmpty() && member.getMethod().getAnnotation(Comment.class) != null) {
+ desc = member.getMethod().getAnnotation(Comment.class).value();
+ }
+ }
+ if (!desc.isEmpty()) schemaMap.put("description", desc);
+ properties.put(member.getAttribute().field(), schemaMap);
+ }
+ }
+ if (!requireds.isEmpty()) cmap.put("required", requireds);
+ cmap.put("properties", properties);
+ return ct;
+ } catch (Exception e) {
+ logger.log(Level.WARNING, genericType + " generate component info error", e);
+ return null;
+ }
+ }
+
+ private static String componentKey(Logger logger, Map> componentsMap, EnMember field, Encodeable encodeable, boolean first) {
+ if (encodeable instanceof ObjectEncoder) {
+ StringBuilder sb = new StringBuilder();
+ sb.append(((ObjectEncoder) encodeable).getTypeClass().getSimpleName());
+ for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
+ if (member.getEncoder() instanceof ArrayEncoder
+ || member.getEncoder() instanceof CollectionEncoder) {
+ String subsb = componentKey(logger, componentsMap, member, member.getEncoder(), false);
+ if (subsb == null) return null;
+ AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
+ if (real == null) continue;
+ Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
+ Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
+ if (cz == ct) continue;
+ if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
+ sb.append(subsb);
+ } else if (member.getEncoder() instanceof ObjectEncoder || member.getEncoder() instanceof SimpledCoder) {
+ AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
+ if (real == null) continue;
+ if (member.getEncoder() instanceof SimpledCoder) {
+ simpleSchemaType(logger, componentsMap, ((SimpledCoder) member.getEncoder()).getType(), ((SimpledCoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
+ } else {
+ simpleSchemaType(logger, componentsMap, ((ObjectEncoder) member.getEncoder()).getTypeClass(), ((ObjectEncoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
+ }
+ Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
+ Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
+ if (cz == ct) continue;
+ String subsb = componentKey(logger, componentsMap, member, member.getEncoder(), false);
+ if (subsb == null) return null;
+ if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
+ sb.append(subsb);
+ } else if (member.getEncoder() instanceof MapEncoder) {
+ continue;
+ } else {
+ return null;
+ }
+ }
+ return sb.toString();
+ } else if (encodeable instanceof ArrayEncoder || encodeable instanceof CollectionEncoder) {
+ final boolean array = (encodeable instanceof ArrayEncoder);
+ Encodeable subEncodeable = array ? ((ArrayEncoder) encodeable).getComponentEncoder() : ((CollectionEncoder) encodeable).getComponentEncoder();
+ if (subEncodeable instanceof SimpledCoder && field != null) return "";
+ final String sb = componentKey(logger, componentsMap, null, subEncodeable, false);
+ if (sb == null || sb.isEmpty()) return sb;
+ if (field != null && field.getField() != null && field.getField().getDeclaringClass() == Sheet.class) {
+ return sb;
+ }
+ return sb + (array ? "_Array" : "_Collection");
+ } else if (encodeable instanceof SimpledCoder) {
+ Class stype = ((SimpledCoder) encodeable).getType();
+ if (stype.isPrimitive() || stype == Boolean.class || Number.class.isAssignableFrom(stype) || CharSequence.class.isAssignableFrom(stype)) {
+ return stype.getSimpleName();
+ }
+ return "";
+ } else if (encodeable instanceof MapEncoder) {
+ return first ? null : "";
+ } else {
+ return null;
+ }
+ }
+
+ private static Object formatExample(String example, Class type, Type genericType) {
+ if (example == null || example.isEmpty()) return null;
+ if (type == Flipper.class) {
+ return new Flipper();
+ } else if (TYPE_RETRESULT_OBJECT.equals(genericType)) {
+ return RetResult.success();
+ } else if (TYPE_RETRESULT_STRING.equals(genericType)) {
+ return RetResult.success();
+ } else if (TYPE_RETRESULT_INTEGER.equals(genericType)) {
+ return RetResult.success(0);
+ } else if (TYPE_RETRESULT_LONG.equals(genericType)) {
+ return RetResult.success(0L);
+ }
+ return example;
+ }
+
+}
diff --git a/src/main/java/org/redkale/boot/ApplicationListener.java b/src/main/java/org/redkale/boot/ApplicationListener.java
index dd1ce9274..8148f5495 100644
--- a/src/main/java/org/redkale/boot/ApplicationListener.java
+++ b/src/main/java/org/redkale/boot/ApplicationListener.java
@@ -1,69 +1,69 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import org.redkale.util.AnyValue;
-
-/**
- * Application鍚姩鍜屽叧闂椂鐨勭洃鍚簨浠
- * 鍙兘閫氳繃application.xml閰嶇疆
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-public interface ApplicationListener {
-
- /**
- * 鍒濆鍖栨柟娉
- *
- * @param config 閰嶇疆鍙傛暟
- */
- default void init(AnyValue config) {
-
- }
-
- /**
- * Application 鍦ㄨ繍琛宻tart鍓嶈皟鐢
- *
- * @param application Application
- */
- default void preStart(Application application) {
- }
-
- /**
- * Application 鍦ㄨ繍琛宻tart鍚庤皟鐢
- *
- * @param application Application
- */
- default void postStart(Application application) {
- }
-
- /**
- * Application 鍦ㄨ繍琛孋ompile鍓嶈皟鐢
- *
- * @param application Application
- */
- default void preCompile(Application application) {
- }
-
- /**
- * Application 鍦ㄨ繍琛孋ompile鍚庤皟鐢
- *
- * @param application Application
- */
- default void postCompile(Application application) {
- }
-
- /**
- * Application 鍦ㄨ繍琛宻hutdown鍓嶈皟鐢
- *
- * @param application Application
- */
- default void preShutdown(Application application) {
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import org.redkale.util.AnyValue;
+
+/**
+ * Application鍚姩鍜屽叧闂椂鐨勭洃鍚簨浠
+ * 鍙兘閫氳繃application.xml閰嶇疆
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+public interface ApplicationListener {
+
+ /**
+ * 鍒濆鍖栨柟娉
+ *
+ * @param config 閰嶇疆鍙傛暟
+ */
+ default void init(AnyValue config) {
+
+ }
+
+ /**
+ * Application 鍦ㄨ繍琛宻tart鍓嶈皟鐢
+ *
+ * @param application Application
+ */
+ default void preStart(Application application) {
+ }
+
+ /**
+ * Application 鍦ㄨ繍琛宻tart鍚庤皟鐢
+ *
+ * @param application Application
+ */
+ default void postStart(Application application) {
+ }
+
+ /**
+ * Application 鍦ㄨ繍琛孋ompile鍓嶈皟鐢
+ *
+ * @param application Application
+ */
+ default void preCompile(Application application) {
+ }
+
+ /**
+ * Application 鍦ㄨ繍琛孋ompile鍚庤皟鐢
+ *
+ * @param application Application
+ */
+ default void postCompile(Application application) {
+ }
+
+ /**
+ * Application 鍦ㄨ繍琛宻hutdown鍓嶈皟鐢
+ *
+ * @param application Application
+ */
+ default void preShutdown(Application application) {
+ }
+}
diff --git a/src/main/java/org/redkale/boot/ClassFilter.java b/src/main/java/org/redkale/boot/ClassFilter.java
index c9b946926..cdd1df635 100644
--- a/src/main/java/org/redkale/boot/ClassFilter.java
+++ b/src/main/java/org/redkale/boot/ClassFilter.java
@@ -1,606 +1,606 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.io.*;
-import java.lang.annotation.*;
-import java.lang.reflect.Modifier;
-import java.net.*;
-import java.nio.charset.StandardCharsets;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.function.Predicate;
-import java.util.jar.*;
-import java.util.logging.*;
-import java.util.regex.*;
-import org.redkale.util.*;
-import org.redkale.util.AnyValue.DefaultAnyValue;
-
-/**
- * class杩囨护鍣紝 绗﹀悎鏉′欢鐨刢lass浼氫繚鐣欎笅鏉ュ瓨鍏ilterEntry銆
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- * @param 娉涘瀷
- */
-@SuppressWarnings("unchecked")
-public final class ClassFilter {
-
- private static final Logger logger = Logger.getLogger(ClassFilter.class.getName()); //鏃ュ織瀵硅薄
-
- private static final boolean finest = logger.isLoggable(Level.FINEST); //鏃ュ織绾у埆
-
- private final Set> entrys = new HashSet<>(); //绗﹀悎鏉′欢鐨勭粨鏋
-
- private final Set> expectEntrys = new HashSet<>(); //鍑嗗绗﹀悎鏉′欢鐨勭粨鏋
-
- private Predicate expectPredicate;
-
- private boolean refused; //鏄惁鎷掔粷鎵鏈夋暟鎹,璁剧疆true锛屽垯鍏朵粬瑙勫垯澶辨晥,閮芥槸鎷掔粷.
-
- private Class superClass; //绗﹀悎鐨勭埗绫诲瀷銆備笉涓虹┖鏃讹紝鎵弿缁撴灉鐨刢lass蹇呴』鏄痵uperClass鐨勫瓙绫
-
- private Class[] excludeSuperClasses; //涓嶇鍚堢殑鐖剁被鍨嬨
-
- private Class extends Annotation> annotationClass;//绗﹀悎鐨勬敞瑙c備笉涓虹┖鏃讹紝鎵弿缁撴灉鐨刢lass蹇呴』鍖呭惈璇ユ敞瑙
-
- private Pattern[] includePatterns; //绗﹀悎鐨刢lassname姝e垯琛ㄨ揪寮
-
- private Pattern[] excludePatterns;//鎷掔粷鐨刢lassname姝e垯琛ㄨ揪寮
-
- private Set privilegeIncludes; //鐗规壒绗﹀悎鏉′欢鐨刢lassname
-
- private Set privilegeExcludes;//鐗规壒鎷掔粷鏉′欢鐨刢lassname
-
- private List ors; //鎴栧叧绯荤殑鍏朵粬ClassFilter
-
- private List ands;//涓庡叧绯荤殑鍏朵粬ClassFilter
-
- private AnyValue conf; //鍩烘湰閰嶇疆淇℃伅, 褰撶鍚堟潯浠舵椂灏哻onf鐨勫睘鎬ц祴鍊煎埌FilterEntry涓幓銆
-
- private final ClassLoader classLoader;
-
- public ClassFilter(RedkaleClassLoader classLoader, Class extends Annotation> annotationClass, Class superClass, Class[] excludeSuperClasses) {
- this(classLoader, annotationClass, superClass, excludeSuperClasses, null);
- }
-
- public ClassFilter(RedkaleClassLoader classLoader, Class extends Annotation> annotationClass, Class superClass, Class[] excludeSuperClasses, AnyValue conf) {
- this.annotationClass = annotationClass;
- this.superClass = superClass;
- this.excludeSuperClasses = excludeSuperClasses;
- this.conf = conf;
- this.classLoader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
- }
-
- public static ClassFilter create(RedkaleClassLoader classLoader, Class[] excludeSuperClasses, String includeregs, String excluderegs, Set includeValues, Set excludeValues) {
- ClassFilter filter = new ClassFilter(classLoader, null, null, excludeSuperClasses);
- filter.setIncludePatterns(includeregs == null ? null : includeregs.split(";"));
- filter.setExcludePatterns(excluderegs == null ? null : excluderegs.split(";"));
- filter.setPrivilegeIncludes(includeValues);
- filter.setPrivilegeExcludes(excludeValues);
- return filter;
- }
-
- public ClassFilter or(ClassFilter filter) {
- if (ors == null) ors = new ArrayList<>();
- ors.add(filter);
- return this;
- }
-
- public ClassFilter and(ClassFilter filter) {
- if (ands == null) ands = new ArrayList<>();
- ands.add(filter);
- return this;
- }
-
- /**
- * 鑾峰彇绗﹀悎鏉′欢鐨刢lass闆嗗悎
- *
- * @return Set<FilterEntry<T>>
- */
- public final Set> getFilterEntrys() {
- HashSet> set = new HashSet<>();
- set.addAll(entrys);
- if (ors != null) ors.forEach(f -> set.addAll(f.getFilterEntrys()));
- if (ands != null) ands.forEach(f -> set.addAll(f.getFilterEntrys()));
- return set;
- }
-
- /**
- * 鑾峰彇棰勭暀鐨刢lass闆嗗悎
- *
- * @return Set<FilterEntry<T>>
- */
- public final Set> getFilterExpectEntrys() {
- HashSet> set = new HashSet<>();
- set.addAll(expectEntrys);
- if (ors != null) ors.forEach(f -> set.addAll(f.getFilterExpectEntrys()));
- if (ands != null) ands.forEach(f -> set.addAll(f.getFilterExpectEntrys()));
- return set;
- }
-
- /**
- * 鑾峰彇鎵鏈夌殑class闆嗗悎
- *
- * @return Set<FilterEntry<T>>
- */
- public final Set> getAllFilterEntrys() {
- HashSet> rs = new HashSet<>();
- rs.addAll(getFilterEntrys());
- rs.addAll(getFilterExpectEntrys());
- return rs;
- }
-
- /**
- * 鑷姩鎵弿鍦拌繃婊ゆ寚瀹氱殑class
- *
- * @param property AnyValue
- * @param clazzname String
- * @param url URL
- */
- @SuppressWarnings("unchecked")
- public final void filter(AnyValue property, String clazzname, URL url) {
- filter(property, clazzname, true, url);
- }
-
- /**
- * 杩囨护鎸囧畾鐨刢lass
- *
- * @param property application.xml涓搴攃lass鑺傜偣涓嬬殑property灞炴ч」
- * @param clazzname class鍚嶇О
- * @param autoscan 涓簍rue琛ㄧず鑷姩鎵弿鐨勶紝 false琛ㄧず鏄捐憲璋冪敤filter锛 AutoLoad鐨勬敞瑙e皢琚拷鐣
- */
- public final void filter(AnyValue property, String clazzname, boolean autoscan) {
- filter(property, clazzname, autoscan, null);
- }
-
- /**
- * 杩囨护鎸囧畾鐨刢lass
- *
- * @param property application.xml涓搴攃lass鑺傜偣涓嬬殑property灞炴ч」
- * @param clazzname class鍚嶇О
- * @param autoscan 涓簍rue琛ㄧず鑷姩鎵弿鐨勶紝 false琛ㄧず鏄捐憲璋冪敤filter锛 AutoLoad鐨勬敞瑙e皢琚拷鐣
- * @param url URL
- */
- public final void filter(AnyValue property, String clazzname, boolean autoscan, URL url) {
- boolean r = accept0(property, clazzname);
- ClassFilter cf = r ? this : null;
- if (r && ands != null) {
- for (ClassFilter filter : ands) {
- if (!filter.accept(property, clazzname)) return;
- }
- }
- if (!r && ors != null) {
- for (ClassFilter filter : ors) {
- if (filter.accept(filter.conf, clazzname)) {
- cf = filter;
- property = cf.conf;
- break;
- }
- }
- }
- if (cf == null || clazzname.startsWith("sun.") || clazzname.contains("module-info")) return;
- try {
- Class clazz = classLoader.loadClass(clazzname);
- if (!cf.accept(property, clazz, autoscan)) return;
- if (cf.conf != null) {
- if (property == null) {
- property = cf.conf;
- } else if (property instanceof DefaultAnyValue) {
- ((DefaultAnyValue) property).addAllStringSet(cf.conf);
- } else {
- DefaultAnyValue dav = new DefaultAnyValue();
- dav.addAllStringSet(property);
- dav.addAllStringSet(cf.conf);
- property = dav;
- }
- }
-
- AutoLoad auto = (AutoLoad) clazz.getAnnotation(AutoLoad.class);
- if ((expectPredicate != null && expectPredicate.test(clazzname)) || (autoscan && auto != null && !auto.value())) { //鑷姩鎵弿涓旇鏍囪涓篅AutoLoad(false)鐨
- expectEntrys.add(new FilterEntry(clazz, autoscan, true, property));
- } else {
- entrys.add(new FilterEntry(clazz, autoscan, false, property));
- }
- } catch (Throwable cfe) {
- if (finest && !clazzname.startsWith("sun.") && !clazzname.startsWith("javax.")
- && !clazzname.startsWith("com.sun.") && !clazzname.startsWith("jdk.") && !clazzname.startsWith("META-INF")
- && !clazzname.startsWith("com.mysql.") && !clazzname.startsWith("com.microsoft.") && !clazzname.startsWith("freemarker.")
- && !clazzname.startsWith("org.redkale") && (clazzname.contains("Service") || clazzname.contains("Servlet"))) {
- //&& (!(cfe instanceof NoClassDefFoundError) || (cfe instanceof UnsupportedClassVersionError) || ((NoClassDefFoundError) cfe).getMessage().startsWith("java.lang.NoClassDefFoundError: java"))) {
- logger.log(Level.FINEST, ClassFilter.class.getSimpleName() + " filter error for class: " + clazzname + (url == null ? "" : (" in " + url)), cfe);
- }
- }
- }
-
- /**
- * 鍒ゆ柇class鏄惁鏈夋晥
- *
- * @param classname String
- *
- * @return boolean
- */
- public boolean accept(String classname) {
- return accept(null, classname);
- }
-
- /**
- * 鍒ゆ柇class鏄惁鏈夋晥
- *
- * @param property AnyValue
- * @param classname String
- *
- * @return boolean
- */
- public boolean accept(AnyValue property, String classname) {
- boolean r = accept0(property, classname);
- if (r && ands != null) {
- for (ClassFilter filter : ands) {
- if (!filter.accept(property, classname)) return false;
- }
- }
- if (!r && ors != null) {
- for (ClassFilter filter : ors) {
- if (filter.accept(filter.conf, classname)) return true;
- }
- }
- return r;
- }
-
- private boolean accept0(AnyValue property, String classname) {
- if (this.refused) return false;
- if (this.privilegeIncludes != null && this.privilegeIncludes.contains(classname)) return true;
- if (this.privilegeExcludes != null && this.privilegeExcludes.contains(classname)) return false;
- if (classname.startsWith("java.") || classname.startsWith("javax.")) return false;
- if (excludePatterns != null) {
- for (Pattern reg : excludePatterns) {
- if (reg.matcher(classname).matches()) return false;
- }
- }
- if (includePatterns != null) {
- for (Pattern reg : includePatterns) {
- if (reg.matcher(classname).matches()) return true;
- }
- }
- return includePatterns == null;
- }
-
- /**
- * 鍒ゆ柇class鏄惁鏈夋晥
- *
- * @param property AnyValue
- * @param clazz Class
- * @param autoscan boolean
- *
- * @return boolean
- */
- @SuppressWarnings("unchecked")
- public boolean accept(AnyValue property, Class clazz, boolean autoscan) {
- if (this.refused || !Modifier.isPublic(clazz.getModifiers())) return false;
- if (annotationClass != null && clazz.getAnnotation(annotationClass) == null) return false;
- boolean rs = superClass == null || (clazz != superClass && superClass.isAssignableFrom(clazz));
- if (rs && this.excludeSuperClasses != null && this.excludeSuperClasses.length > 0) {
- for (Class c : this.excludeSuperClasses) {
- if (c != null && (clazz == c || c.isAssignableFrom(clazz))) return false;
- }
- }
- return rs;
- }
-
- public static Pattern[] toPattern(String[] regs) {
- if (regs == null || regs.length == 0) return null;
- int i = 0;
- Pattern[] rs = new Pattern[regs.length];
- for (String reg : regs) {
- if (reg == null || reg.trim().isEmpty()) continue;
- rs[i++] = Pattern.compile(reg.trim());
- }
- if (i == 0) return null;
- if (i == rs.length) return rs;
- Pattern[] ps = new Pattern[i];
- System.arraycopy(rs, 0, ps, 0, i);
- return ps;
- }
-
- public void setSuperClass(Class superClass) {
- this.superClass = superClass;
- }
-
- public Class getSuperClass() {
- return superClass;
- }
-
- public Class[] getExcludeSuperClasses() {
- return excludeSuperClasses;
- }
-
- public void setExcludeSuperClasses(Class[] excludeSuperClasses) {
- this.excludeSuperClasses = excludeSuperClasses;
- }
-
- public void setAnnotationClass(Class extends Annotation> annotationClass) {
- this.annotationClass = annotationClass;
- }
-
- public Pattern[] getIncludePatterns() {
- return includePatterns;
- }
-
- public void setIncludePatterns(String[] includePatterns) {
- this.includePatterns = toPattern(includePatterns);
- }
-
- public Pattern[] getExcludePatterns() {
- return excludePatterns;
- }
-
- public void setExcludePatterns(String[] excludePatterns) {
- this.excludePatterns = toPattern(excludePatterns);
- }
-
- public Class extends Annotation> getAnnotationClass() {
- return annotationClass;
- }
-
- public boolean isRefused() {
- return refused;
- }
-
- public void setRefused(boolean refused) {
- this.refused = refused;
- }
-
- public Predicate getExpectPredicate() {
- return expectPredicate;
- }
-
- public void setExpectPredicate(Predicate predicate) {
- this.expectPredicate = predicate;
- }
-
- public Set getPrivilegeIncludes() {
- return privilegeIncludes;
- }
-
- public void setPrivilegeIncludes(Set privilegeIncludes) {
- this.privilegeIncludes = privilegeIncludes == null || privilegeIncludes.isEmpty() ? null : privilegeIncludes;
- }
-
- public Set getPrivilegeExcludes() {
- return privilegeExcludes;
- }
-
- public void setPrivilegeExcludes(Set privilegeExcludes) {
- this.privilegeExcludes = privilegeExcludes == null || privilegeExcludes.isEmpty() ? null : privilegeExcludes;
-
- }
-
- /**
- * 瀛樻斁绗﹀悎鏉′欢鐨刢lass涓巆lass鎸囧畾鐨勫睘鎬ч」
- *
- * @param 娉涘瀷
- */
- public static final class FilterEntry {
-
- private final HashSet groups = new LinkedHashSet<>();
-
- private final String name;
-
- private final Class type;
-
- private final AnyValue property;
-
- private final boolean autoload;
-
- private final boolean expect;
-
- public FilterEntry(Class type, AnyValue property) {
- this(type, false, false, property);
- }
-
- public FilterEntry(Class type, final boolean autoload, boolean expect, AnyValue property) {
- this.type = type;
- String str = property == null ? null : property.getValue("groups");
- if (str != null) {
- str = str.trim();
- if (str.endsWith(";")) str = str.substring(0, str.length() - 1);
- }
- if (str != null) this.groups.addAll(Arrays.asList(str.split(";")));
- this.property = property;
- this.autoload = autoload;
- this.expect = expect;
- this.name = property == null ? "" : property.getValue("name", "");
- }
-
- @Override
- public String toString() {
- return this.getClass().getSimpleName() + "[thread=" + Thread.currentThread().getName()
- + ", type=" + this.type.getSimpleName() + ", name=" + name + ", groups=" + this.groups + "]";
- }
-
- @Override
- public int hashCode() {
- return this.type.hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- return (this.type == ((FilterEntry>) obj).type && this.groups.equals(((FilterEntry>) obj).groups) && this.name.equals(((FilterEntry>) obj).name));
- }
-
- public Class getType() {
- return type;
- }
-
- public String getName() {
- return name;
- }
-
- public AnyValue getProperty() {
- return property;
- }
-
- public boolean containsGroup(String group) {
- return groups != null && groups.contains(group);
- }
-
- public boolean isEmptyGroups() {
- return groups == null || groups.isEmpty();
- }
-
- public HashSet getGroups() {
- return groups;
- }
-
- public boolean isAutoload() {
- return autoload;
- }
-
- public boolean isExpect() {
- return expect;
- }
- }
-
- /**
- * class鍔犺浇绫
- */
- public static class Loader {
-
- protected static final Logger logger = Logger.getLogger(Loader.class.getName());
-
- protected static final ConcurrentMap> cache = new ConcurrentHashMap<>();
-
- public static void close() {
- cache.clear();
- }
-
- /**
- * 鍔犺浇褰撳墠绾跨▼鐨刢lasspath鎵弿鎵鏈塩lass杩涜杩囨护
- *
- * @param excludeFile 涓嶉渶瑕佹壂鎻忕殑鏂囦欢澶癸紝 鍙互涓簄ull
- * @param loader RedkaleClassloader锛 涓嶅彲涓簄ull
- * @param excludeRegs 鍖呭惈姝ゅ叧閿瓧鐨勬枃浠跺皢琚烦杩囷紝 鍙互涓簄ull
- * @param filters 杩囨护鍣
- *
- * @throws IOException 寮傚父
- */
- public static void load(final File excludeFile, RedkaleClassLoader loader, final String[] excludeRegs, final ClassFilter... filters) throws IOException {
- List urlfiles = new ArrayList<>(2);
- List urljares = new ArrayList<>(2);
- final URL exurl = excludeFile != null ? excludeFile.toURI().toURL() : null;
- final Pattern[] excludePatterns = toPattern(excludeRegs);
- for (URL url : loader.getAllURLs()) {
- if (exurl != null && exurl.sameFile(url)) continue;
- if (excludePatterns != null && url != RedkaleClassLoader.URL_NONE) {
- boolean skip = false;
- for (Pattern p : excludePatterns) {
- if (p.matcher(url.toString()).matches()) {
- skip = true;
- break;
- }
- }
- if (skip) continue;
- }
- if (url.getPath().endsWith(".jar")) {
- urljares.add(url);
- } else {
- urlfiles.add(url);
- }
- }
- List files = new ArrayList<>();
- boolean debug = logger.isLoggable(Level.FINEST);
- StringBuilder debugstr = new StringBuilder();
- for (final URL url : urljares) {
- Set classes = cache.get(url);
- if (classes == null) {
- classes = new LinkedHashSet<>();
- try (JarFile jar = new JarFile(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8))) {
- Enumeration it = jar.entries();
- while (it.hasMoreElements()) {
- String entryname = it.nextElement().getName().replace('/', '.');
- if (entryname.endsWith(".class") && entryname.indexOf('$') < 0) {
- String classname = entryname.substring(0, entryname.length() - 6);
- if (classname.startsWith("javax.") || classname.startsWith("com.sun.")) continue;
- //甯歌鐨刯ar璺宠繃
- if (classname.startsWith("com.redkaledyn.")) break; //redkale鍔ㄦ佺敓鎴愮殑绫
- if (classname.startsWith("com.mysql.")) break;
- if (classname.startsWith("org.mariadb.")) break;
- if (classname.startsWith("oracle.jdbc.")) break;
- if (classname.startsWith("org.postgresql.")) break;
- if (classname.startsWith("com.microsoft.sqlserver.")) break;
- classes.add(classname);
- if (debug) debugstr.append(classname).append("\r\n");
- for (final ClassFilter filter : filters) {
- if (filter != null) filter.filter(null, classname, url);
- }
- }
- }
- }
- cache.put(url, classes);
- } else {
- for (String classname : classes) {
- for (final ClassFilter filter : filters) {
- if (filter != null) filter.filter(null, classname, url);
- }
- }
- }
- }
- for (final URL url : urlfiles) {
- Set classes = cache.get(url);
- if (classes == null) {
- classes = new LinkedHashSet<>();
- final Set cs = classes;
- if (url == RedkaleClassLoader.URL_NONE) loader.forEachCacheClass(v -> cs.add(v));
- if (cs.isEmpty()) {
- files.clear();
- File root = new File(url.getFile());
- String rootpath = root.getPath();
- loadClassFiles(excludeFile, root, files);
- for (File f : files) {
- String classname = f.getPath().substring(rootpath.length() + 1, f.getPath().length() - 6).replace(File.separatorChar, '.');
- if (classname.startsWith("javax.") || classname.startsWith("com.sun.")) continue;
- classes.add(classname);
- if (debug) debugstr.append(classname).append("\r\n");
- for (final ClassFilter filter : filters) {
- if (filter != null) filter.filter(null, classname, url);
- }
- }
- } else {
- for (String classname : classes) {
- for (final ClassFilter filter : filters) {
- if (filter != null) filter.filter(null, classname, url);
- }
- }
- }
- cache.put(url, classes);
- } else {
- for (String classname : classes) {
- for (final ClassFilter filter : filters) {
- if (filter != null) filter.filter(null, classname, url);
- }
- }
- }
- }
- //if (debug) logger.log(Level.INFO, "scan classes: \r\n{0}", debugstr);
- }
-
- private static void loadClassFiles(File exclude, File root, List files) {
- if (root.isFile() && root.getName().endsWith(".class")) {
- files.add(root);
- } else if (root.isDirectory()) {
- if (exclude != null && exclude.equals(root)) return;
- File[] lfs = root.listFiles();
- if (lfs == null) throw new RuntimeException("File(" + root + ") cannot listFiles()");
- for (File f : lfs) {
- loadClassFiles(exclude, f, files);
- }
- }
- }
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.io.*;
+import java.lang.annotation.*;
+import java.lang.reflect.Modifier;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.function.Predicate;
+import java.util.jar.*;
+import java.util.logging.*;
+import java.util.regex.*;
+import org.redkale.util.*;
+import org.redkale.util.AnyValue.DefaultAnyValue;
+
+/**
+ * class杩囨护鍣紝 绗﹀悎鏉′欢鐨刢lass浼氫繚鐣欎笅鏉ュ瓨鍏ilterEntry銆
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ * @param 娉涘瀷
+ */
+@SuppressWarnings("unchecked")
+public final class ClassFilter {
+
+ private static final Logger logger = Logger.getLogger(ClassFilter.class.getName()); //鏃ュ織瀵硅薄
+
+ private static final boolean finest = logger.isLoggable(Level.FINEST); //鏃ュ織绾у埆
+
+ private final Set> entrys = new HashSet<>(); //绗﹀悎鏉′欢鐨勭粨鏋
+
+ private final Set> expectEntrys = new HashSet<>(); //鍑嗗绗﹀悎鏉′欢鐨勭粨鏋
+
+ private Predicate expectPredicate;
+
+ private boolean refused; //鏄惁鎷掔粷鎵鏈夋暟鎹,璁剧疆true锛屽垯鍏朵粬瑙勫垯澶辨晥,閮芥槸鎷掔粷.
+
+ private Class superClass; //绗﹀悎鐨勭埗绫诲瀷銆備笉涓虹┖鏃讹紝鎵弿缁撴灉鐨刢lass蹇呴』鏄痵uperClass鐨勫瓙绫
+
+ private Class[] excludeSuperClasses; //涓嶇鍚堢殑鐖剁被鍨嬨
+
+ private Class extends Annotation> annotationClass;//绗﹀悎鐨勬敞瑙c備笉涓虹┖鏃讹紝鎵弿缁撴灉鐨刢lass蹇呴』鍖呭惈璇ユ敞瑙
+
+ private Pattern[] includePatterns; //绗﹀悎鐨刢lassname姝e垯琛ㄨ揪寮
+
+ private Pattern[] excludePatterns;//鎷掔粷鐨刢lassname姝e垯琛ㄨ揪寮
+
+ private Set privilegeIncludes; //鐗规壒绗﹀悎鏉′欢鐨刢lassname
+
+ private Set privilegeExcludes;//鐗规壒鎷掔粷鏉′欢鐨刢lassname
+
+ private List ors; //鎴栧叧绯荤殑鍏朵粬ClassFilter
+
+ private List ands;//涓庡叧绯荤殑鍏朵粬ClassFilter
+
+ private AnyValue conf; //鍩烘湰閰嶇疆淇℃伅, 褰撶鍚堟潯浠舵椂灏哻onf鐨勫睘鎬ц祴鍊煎埌FilterEntry涓幓銆
+
+ private final ClassLoader classLoader;
+
+ public ClassFilter(RedkaleClassLoader classLoader, Class extends Annotation> annotationClass, Class superClass, Class[] excludeSuperClasses) {
+ this(classLoader, annotationClass, superClass, excludeSuperClasses, null);
+ }
+
+ public ClassFilter(RedkaleClassLoader classLoader, Class extends Annotation> annotationClass, Class superClass, Class[] excludeSuperClasses, AnyValue conf) {
+ this.annotationClass = annotationClass;
+ this.superClass = superClass;
+ this.excludeSuperClasses = excludeSuperClasses;
+ this.conf = conf;
+ this.classLoader = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
+ }
+
+ public static ClassFilter create(RedkaleClassLoader classLoader, Class[] excludeSuperClasses, String includeregs, String excluderegs, Set includeValues, Set excludeValues) {
+ ClassFilter filter = new ClassFilter(classLoader, null, null, excludeSuperClasses);
+ filter.setIncludePatterns(includeregs == null ? null : includeregs.split(";"));
+ filter.setExcludePatterns(excluderegs == null ? null : excluderegs.split(";"));
+ filter.setPrivilegeIncludes(includeValues);
+ filter.setPrivilegeExcludes(excludeValues);
+ return filter;
+ }
+
+ public ClassFilter or(ClassFilter filter) {
+ if (ors == null) ors = new ArrayList<>();
+ ors.add(filter);
+ return this;
+ }
+
+ public ClassFilter and(ClassFilter filter) {
+ if (ands == null) ands = new ArrayList<>();
+ ands.add(filter);
+ return this;
+ }
+
+ /**
+ * 鑾峰彇绗﹀悎鏉′欢鐨刢lass闆嗗悎
+ *
+ * @return Set<FilterEntry<T>>
+ */
+ public final Set> getFilterEntrys() {
+ HashSet> set = new HashSet<>();
+ set.addAll(entrys);
+ if (ors != null) ors.forEach(f -> set.addAll(f.getFilterEntrys()));
+ if (ands != null) ands.forEach(f -> set.addAll(f.getFilterEntrys()));
+ return set;
+ }
+
+ /**
+ * 鑾峰彇棰勭暀鐨刢lass闆嗗悎
+ *
+ * @return Set<FilterEntry<T>>
+ */
+ public final Set> getFilterExpectEntrys() {
+ HashSet> set = new HashSet<>();
+ set.addAll(expectEntrys);
+ if (ors != null) ors.forEach(f -> set.addAll(f.getFilterExpectEntrys()));
+ if (ands != null) ands.forEach(f -> set.addAll(f.getFilterExpectEntrys()));
+ return set;
+ }
+
+ /**
+ * 鑾峰彇鎵鏈夌殑class闆嗗悎
+ *
+ * @return Set<FilterEntry<T>>
+ */
+ public final Set> getAllFilterEntrys() {
+ HashSet> rs = new HashSet<>();
+ rs.addAll(getFilterEntrys());
+ rs.addAll(getFilterExpectEntrys());
+ return rs;
+ }
+
+ /**
+ * 鑷姩鎵弿鍦拌繃婊ゆ寚瀹氱殑class
+ *
+ * @param property AnyValue
+ * @param clazzname String
+ * @param url URL
+ */
+ @SuppressWarnings("unchecked")
+ public final void filter(AnyValue property, String clazzname, URL url) {
+ filter(property, clazzname, true, url);
+ }
+
+ /**
+ * 杩囨护鎸囧畾鐨刢lass
+ *
+ * @param property application.xml涓搴攃lass鑺傜偣涓嬬殑property灞炴ч」
+ * @param clazzname class鍚嶇О
+ * @param autoscan 涓簍rue琛ㄧず鑷姩鎵弿鐨勶紝 false琛ㄧず鏄捐憲璋冪敤filter锛 AutoLoad鐨勬敞瑙e皢琚拷鐣
+ */
+ public final void filter(AnyValue property, String clazzname, boolean autoscan) {
+ filter(property, clazzname, autoscan, null);
+ }
+
+ /**
+ * 杩囨护鎸囧畾鐨刢lass
+ *
+ * @param property application.xml涓搴攃lass鑺傜偣涓嬬殑property灞炴ч」
+ * @param clazzname class鍚嶇О
+ * @param autoscan 涓簍rue琛ㄧず鑷姩鎵弿鐨勶紝 false琛ㄧず鏄捐憲璋冪敤filter锛 AutoLoad鐨勬敞瑙e皢琚拷鐣
+ * @param url URL
+ */
+ public final void filter(AnyValue property, String clazzname, boolean autoscan, URL url) {
+ boolean r = accept0(property, clazzname);
+ ClassFilter cf = r ? this : null;
+ if (r && ands != null) {
+ for (ClassFilter filter : ands) {
+ if (!filter.accept(property, clazzname)) return;
+ }
+ }
+ if (!r && ors != null) {
+ for (ClassFilter filter : ors) {
+ if (filter.accept(filter.conf, clazzname)) {
+ cf = filter;
+ property = cf.conf;
+ break;
+ }
+ }
+ }
+ if (cf == null || clazzname.startsWith("sun.") || clazzname.contains("module-info")) return;
+ try {
+ Class clazz = classLoader.loadClass(clazzname);
+ if (!cf.accept(property, clazz, autoscan)) return;
+ if (cf.conf != null) {
+ if (property == null) {
+ property = cf.conf;
+ } else if (property instanceof DefaultAnyValue) {
+ ((DefaultAnyValue) property).addAllStringSet(cf.conf);
+ } else {
+ DefaultAnyValue dav = new DefaultAnyValue();
+ dav.addAllStringSet(property);
+ dav.addAllStringSet(cf.conf);
+ property = dav;
+ }
+ }
+
+ AutoLoad auto = (AutoLoad) clazz.getAnnotation(AutoLoad.class);
+ if ((expectPredicate != null && expectPredicate.test(clazzname)) || (autoscan && auto != null && !auto.value())) { //鑷姩鎵弿涓旇鏍囪涓篅AutoLoad(false)鐨
+ expectEntrys.add(new FilterEntry(clazz, autoscan, true, property));
+ } else {
+ entrys.add(new FilterEntry(clazz, autoscan, false, property));
+ }
+ } catch (Throwable cfe) {
+ if (finest && !clazzname.startsWith("sun.") && !clazzname.startsWith("javax.")
+ && !clazzname.startsWith("com.sun.") && !clazzname.startsWith("jdk.") && !clazzname.startsWith("META-INF")
+ && !clazzname.startsWith("com.mysql.") && !clazzname.startsWith("com.microsoft.") && !clazzname.startsWith("freemarker.")
+ && !clazzname.startsWith("org.redkale") && (clazzname.contains("Service") || clazzname.contains("Servlet"))) {
+ //&& (!(cfe instanceof NoClassDefFoundError) || (cfe instanceof UnsupportedClassVersionError) || ((NoClassDefFoundError) cfe).getMessage().startsWith("java.lang.NoClassDefFoundError: java"))) {
+ logger.log(Level.FINEST, ClassFilter.class.getSimpleName() + " filter error for class: " + clazzname + (url == null ? "" : (" in " + url)), cfe);
+ }
+ }
+ }
+
+ /**
+ * 鍒ゆ柇class鏄惁鏈夋晥
+ *
+ * @param classname String
+ *
+ * @return boolean
+ */
+ public boolean accept(String classname) {
+ return accept(null, classname);
+ }
+
+ /**
+ * 鍒ゆ柇class鏄惁鏈夋晥
+ *
+ * @param property AnyValue
+ * @param classname String
+ *
+ * @return boolean
+ */
+ public boolean accept(AnyValue property, String classname) {
+ boolean r = accept0(property, classname);
+ if (r && ands != null) {
+ for (ClassFilter filter : ands) {
+ if (!filter.accept(property, classname)) return false;
+ }
+ }
+ if (!r && ors != null) {
+ for (ClassFilter filter : ors) {
+ if (filter.accept(filter.conf, classname)) return true;
+ }
+ }
+ return r;
+ }
+
+ private boolean accept0(AnyValue property, String classname) {
+ if (this.refused) return false;
+ if (this.privilegeIncludes != null && this.privilegeIncludes.contains(classname)) return true;
+ if (this.privilegeExcludes != null && this.privilegeExcludes.contains(classname)) return false;
+ if (classname.startsWith("java.") || classname.startsWith("javax.")) return false;
+ if (excludePatterns != null) {
+ for (Pattern reg : excludePatterns) {
+ if (reg.matcher(classname).matches()) return false;
+ }
+ }
+ if (includePatterns != null) {
+ for (Pattern reg : includePatterns) {
+ if (reg.matcher(classname).matches()) return true;
+ }
+ }
+ return includePatterns == null;
+ }
+
+ /**
+ * 鍒ゆ柇class鏄惁鏈夋晥
+ *
+ * @param property AnyValue
+ * @param clazz Class
+ * @param autoscan boolean
+ *
+ * @return boolean
+ */
+ @SuppressWarnings("unchecked")
+ public boolean accept(AnyValue property, Class clazz, boolean autoscan) {
+ if (this.refused || !Modifier.isPublic(clazz.getModifiers())) return false;
+ if (annotationClass != null && clazz.getAnnotation(annotationClass) == null) return false;
+ boolean rs = superClass == null || (clazz != superClass && superClass.isAssignableFrom(clazz));
+ if (rs && this.excludeSuperClasses != null && this.excludeSuperClasses.length > 0) {
+ for (Class c : this.excludeSuperClasses) {
+ if (c != null && (clazz == c || c.isAssignableFrom(clazz))) return false;
+ }
+ }
+ return rs;
+ }
+
+ public static Pattern[] toPattern(String[] regs) {
+ if (regs == null || regs.length == 0) return null;
+ int i = 0;
+ Pattern[] rs = new Pattern[regs.length];
+ for (String reg : regs) {
+ if (reg == null || reg.trim().isEmpty()) continue;
+ rs[i++] = Pattern.compile(reg.trim());
+ }
+ if (i == 0) return null;
+ if (i == rs.length) return rs;
+ Pattern[] ps = new Pattern[i];
+ System.arraycopy(rs, 0, ps, 0, i);
+ return ps;
+ }
+
+ public void setSuperClass(Class superClass) {
+ this.superClass = superClass;
+ }
+
+ public Class getSuperClass() {
+ return superClass;
+ }
+
+ public Class[] getExcludeSuperClasses() {
+ return excludeSuperClasses;
+ }
+
+ public void setExcludeSuperClasses(Class[] excludeSuperClasses) {
+ this.excludeSuperClasses = excludeSuperClasses;
+ }
+
+ public void setAnnotationClass(Class extends Annotation> annotationClass) {
+ this.annotationClass = annotationClass;
+ }
+
+ public Pattern[] getIncludePatterns() {
+ return includePatterns;
+ }
+
+ public void setIncludePatterns(String[] includePatterns) {
+ this.includePatterns = toPattern(includePatterns);
+ }
+
+ public Pattern[] getExcludePatterns() {
+ return excludePatterns;
+ }
+
+ public void setExcludePatterns(String[] excludePatterns) {
+ this.excludePatterns = toPattern(excludePatterns);
+ }
+
+ public Class extends Annotation> getAnnotationClass() {
+ return annotationClass;
+ }
+
+ public boolean isRefused() {
+ return refused;
+ }
+
+ public void setRefused(boolean refused) {
+ this.refused = refused;
+ }
+
+ public Predicate getExpectPredicate() {
+ return expectPredicate;
+ }
+
+ public void setExpectPredicate(Predicate predicate) {
+ this.expectPredicate = predicate;
+ }
+
+ public Set getPrivilegeIncludes() {
+ return privilegeIncludes;
+ }
+
+ public void setPrivilegeIncludes(Set privilegeIncludes) {
+ this.privilegeIncludes = privilegeIncludes == null || privilegeIncludes.isEmpty() ? null : privilegeIncludes;
+ }
+
+ public Set getPrivilegeExcludes() {
+ return privilegeExcludes;
+ }
+
+ public void setPrivilegeExcludes(Set privilegeExcludes) {
+ this.privilegeExcludes = privilegeExcludes == null || privilegeExcludes.isEmpty() ? null : privilegeExcludes;
+
+ }
+
+ /**
+ * 瀛樻斁绗﹀悎鏉′欢鐨刢lass涓巆lass鎸囧畾鐨勫睘鎬ч」
+ *
+ * @param 娉涘瀷
+ */
+ public static final class FilterEntry {
+
+ private final HashSet groups = new LinkedHashSet<>();
+
+ private final String name;
+
+ private final Class type;
+
+ private final AnyValue property;
+
+ private final boolean autoload;
+
+ private final boolean expect;
+
+ public FilterEntry(Class type, AnyValue property) {
+ this(type, false, false, property);
+ }
+
+ public FilterEntry(Class type, final boolean autoload, boolean expect, AnyValue property) {
+ this.type = type;
+ String str = property == null ? null : property.getValue("groups");
+ if (str != null) {
+ str = str.trim();
+ if (str.endsWith(";")) str = str.substring(0, str.length() - 1);
+ }
+ if (str != null) this.groups.addAll(Arrays.asList(str.split(";")));
+ this.property = property;
+ this.autoload = autoload;
+ this.expect = expect;
+ this.name = property == null ? "" : property.getValue("name", "");
+ }
+
+ @Override
+ public String toString() {
+ return this.getClass().getSimpleName() + "[thread=" + Thread.currentThread().getName()
+ + ", type=" + this.type.getSimpleName() + ", name=" + name + ", groups=" + this.groups + "]";
+ }
+
+ @Override
+ public int hashCode() {
+ return this.type.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) return false;
+ if (getClass() != obj.getClass()) return false;
+ return (this.type == ((FilterEntry>) obj).type && this.groups.equals(((FilterEntry>) obj).groups) && this.name.equals(((FilterEntry>) obj).name));
+ }
+
+ public Class getType() {
+ return type;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public AnyValue getProperty() {
+ return property;
+ }
+
+ public boolean containsGroup(String group) {
+ return groups != null && groups.contains(group);
+ }
+
+ public boolean isEmptyGroups() {
+ return groups == null || groups.isEmpty();
+ }
+
+ public HashSet getGroups() {
+ return groups;
+ }
+
+ public boolean isAutoload() {
+ return autoload;
+ }
+
+ public boolean isExpect() {
+ return expect;
+ }
+ }
+
+ /**
+ * class鍔犺浇绫
+ */
+ public static class Loader {
+
+ protected static final Logger logger = Logger.getLogger(Loader.class.getName());
+
+ protected static final ConcurrentMap> cache = new ConcurrentHashMap<>();
+
+ public static void close() {
+ cache.clear();
+ }
+
+ /**
+ * 鍔犺浇褰撳墠绾跨▼鐨刢lasspath鎵弿鎵鏈塩lass杩涜杩囨护
+ *
+ * @param excludeFile 涓嶉渶瑕佹壂鎻忕殑鏂囦欢澶癸紝 鍙互涓簄ull
+ * @param loader RedkaleClassloader锛 涓嶅彲涓簄ull
+ * @param excludeRegs 鍖呭惈姝ゅ叧閿瓧鐨勬枃浠跺皢琚烦杩囷紝 鍙互涓簄ull
+ * @param filters 杩囨护鍣
+ *
+ * @throws IOException 寮傚父
+ */
+ public static void load(final File excludeFile, RedkaleClassLoader loader, final String[] excludeRegs, final ClassFilter... filters) throws IOException {
+ List urlfiles = new ArrayList<>(2);
+ List urljares = new ArrayList<>(2);
+ final URL exurl = excludeFile != null ? excludeFile.toURI().toURL() : null;
+ final Pattern[] excludePatterns = toPattern(excludeRegs);
+ for (URL url : loader.getAllURLs()) {
+ if (exurl != null && exurl.sameFile(url)) continue;
+ if (excludePatterns != null && url != RedkaleClassLoader.URL_NONE) {
+ boolean skip = false;
+ for (Pattern p : excludePatterns) {
+ if (p.matcher(url.toString()).matches()) {
+ skip = true;
+ break;
+ }
+ }
+ if (skip) continue;
+ }
+ if (url.getPath().endsWith(".jar")) {
+ urljares.add(url);
+ } else {
+ urlfiles.add(url);
+ }
+ }
+ List files = new ArrayList<>();
+ boolean debug = logger.isLoggable(Level.FINEST);
+ StringBuilder debugstr = new StringBuilder();
+ for (final URL url : urljares) {
+ Set classes = cache.get(url);
+ if (classes == null) {
+ classes = new LinkedHashSet<>();
+ try (JarFile jar = new JarFile(URLDecoder.decode(url.getFile(), StandardCharsets.UTF_8))) {
+ Enumeration it = jar.entries();
+ while (it.hasMoreElements()) {
+ String entryname = it.nextElement().getName().replace('/', '.');
+ if (entryname.endsWith(".class") && entryname.indexOf('$') < 0) {
+ String classname = entryname.substring(0, entryname.length() - 6);
+ if (classname.startsWith("javax.") || classname.startsWith("com.sun.")) continue;
+ //甯歌鐨刯ar璺宠繃
+ if (classname.startsWith("com.redkaledyn.")) break; //redkale鍔ㄦ佺敓鎴愮殑绫
+ if (classname.startsWith("com.mysql.")) break;
+ if (classname.startsWith("org.mariadb.")) break;
+ if (classname.startsWith("oracle.jdbc.")) break;
+ if (classname.startsWith("org.postgresql.")) break;
+ if (classname.startsWith("com.microsoft.sqlserver.")) break;
+ classes.add(classname);
+ if (debug) debugstr.append(classname).append("\r\n");
+ for (final ClassFilter filter : filters) {
+ if (filter != null) filter.filter(null, classname, url);
+ }
+ }
+ }
+ }
+ cache.put(url, classes);
+ } else {
+ for (String classname : classes) {
+ for (final ClassFilter filter : filters) {
+ if (filter != null) filter.filter(null, classname, url);
+ }
+ }
+ }
+ }
+ for (final URL url : urlfiles) {
+ Set classes = cache.get(url);
+ if (classes == null) {
+ classes = new LinkedHashSet<>();
+ final Set cs = classes;
+ if (url == RedkaleClassLoader.URL_NONE) loader.forEachCacheClass(v -> cs.add(v));
+ if (cs.isEmpty()) {
+ files.clear();
+ File root = new File(url.getFile());
+ String rootpath = root.getPath();
+ loadClassFiles(excludeFile, root, files);
+ for (File f : files) {
+ String classname = f.getPath().substring(rootpath.length() + 1, f.getPath().length() - 6).replace(File.separatorChar, '.');
+ if (classname.startsWith("javax.") || classname.startsWith("com.sun.")) continue;
+ classes.add(classname);
+ if (debug) debugstr.append(classname).append("\r\n");
+ for (final ClassFilter filter : filters) {
+ if (filter != null) filter.filter(null, classname, url);
+ }
+ }
+ } else {
+ for (String classname : classes) {
+ for (final ClassFilter filter : filters) {
+ if (filter != null) filter.filter(null, classname, url);
+ }
+ }
+ }
+ cache.put(url, classes);
+ } else {
+ for (String classname : classes) {
+ for (final ClassFilter filter : filters) {
+ if (filter != null) filter.filter(null, classname, url);
+ }
+ }
+ }
+ }
+ //if (debug) logger.log(Level.INFO, "scan classes: \r\n{0}", debugstr);
+ }
+
+ private static void loadClassFiles(File exclude, File root, List files) {
+ if (root.isFile() && root.getName().endsWith(".class")) {
+ files.add(root);
+ } else if (root.isDirectory()) {
+ if (exclude != null && exclude.equals(root)) return;
+ File[] lfs = root.listFiles();
+ if (lfs == null) throw new RuntimeException("File(" + root + ") cannot listFiles()");
+ for (File f : lfs) {
+ loadClassFiles(exclude, f, files);
+ }
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/redkale/boot/LoggingFileHandler.java b/src/main/java/org/redkale/boot/LoggingFileHandler.java
index e5f616faf..32fc1c8f0 100644
--- a/src/main/java/org/redkale/boot/LoggingFileHandler.java
+++ b/src/main/java/org/redkale/boot/LoggingFileHandler.java
@@ -1,372 +1,372 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import org.redkale.util.RedkaleClassLoader;
-
-import java.io.*;
-import java.nio.file.*;
-import static java.nio.file.StandardCopyOption.*;
-import java.time.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.concurrent.atomic.*;
-import java.util.logging.*;
-import java.util.logging.Formatter;
-import java.util.regex.Pattern;
-
-/**
- * 鑷畾涔夌殑鏃ュ織杈撳嚭绫
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-@SuppressWarnings("unchecked")
-public class LoggingFileHandler extends Handler {
-
- //public static final String FORMATTER_FORMAT = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL %4$s %2$s%n%5$s%6$s%n";
- public static final String FORMATTER_FORMAT = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL %4$s %2$s\r\n%5$s%6$s\r\n";
-
- /**
- * SNCP鐨勬棩蹇楄緭鍑篐andler
- */
- public static class LoggingSncpFileHandler extends LoggingFileHandler {
-
- @Override
- public String getPrefix() {
- return "sncp-";
- }
- }
-
- /**
- * 榛樿鐨勬棩蹇楁椂闂存牸寮忓寲绫
- * 涓嶴impleFormatter鐨勫尯鍒湪浜巐evel涓嶄娇鐢ㄦ湰鍦板寲
- *
- */
- public static class LoggingFormater extends Formatter {
-
- @Override
- public String format(LogRecord log) {
- String source;
- if (log.getSourceClassName() != null) {
- source = log.getSourceClassName();
- if (log.getSourceMethodName() != null) {
- source += " " + log.getSourceMethodName();
- }
- } else {
- source = log.getLoggerName();
- }
- String message = formatMessage(log);
- String throwable = "";
- if (log.getThrown() != null) {
- StringWriter sw = new StringWriter();
- PrintWriter pw = new PrintWriter(sw) {
- @Override
- public void println() {
- super.print("\r\n");
- }
- };
- pw.println();
- log.getThrown().printStackTrace(pw);
- pw.close();
- throwable = sw.toString();
- }
- return String.format(FORMATTER_FORMAT,
- System.currentTimeMillis(),
- source,
- log.getLoggerName(),
- log.getLevel().getName(),
- message,
- throwable);
- }
- }
-
- public static void initDebugLogConfig() {
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- final PrintStream ps = new PrintStream(out);
- ps.println("handlers = java.util.logging.ConsoleHandler");
- ps.println(".level = FINEST");
- ps.println("jdk.level = INFO");
- ps.println("sun.level = INFO");
- ps.println("com.sun.level = INFO");
- ps.println("javax.level = INFO");
- ps.println("java.util.logging.ConsoleHandler.level = FINEST");
- ps.println("java.util.logging.ConsoleHandler.formatter = " + LoggingFileHandler.LoggingFormater.class.getName());
- LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray()));
- } catch (Exception e) {
- }
- }
-
- protected final LinkedBlockingQueue logqueue = new LinkedBlockingQueue();
-
- private String pattern;
-
- private String unusual; //涓嶄负null琛ㄧず灏 WARNING銆丼EVERE 绾у埆鐨勬棩蹇楀啓鍏ュ崟鐙殑鏂囦欢涓
-
- private int limit; //鏂囦欢澶у皬闄愬埗
-
- private final AtomicInteger logindex = new AtomicInteger();
-
- private final AtomicInteger logunusualindex = new AtomicInteger();
-
- private int count = 1; //鏂囦欢闄愬埗
-
- private long tomorrow;
-
- private boolean append;
-
- private Pattern denyreg;
-
- private final AtomicLong loglength = new AtomicLong();
-
- private final AtomicLong logunusuallength = new AtomicLong();
-
- private File logfile;
-
- private File logunusualfile;
-
- private OutputStream logstream;
-
- private OutputStream logunusualstream;
-
- public LoggingFileHandler() {
- updateTomorrow();
- configure();
- open();
- }
-
- private void updateTomorrow() {
- Calendar cal = Calendar.getInstance();
- cal.set(Calendar.HOUR_OF_DAY, 0);
- cal.set(Calendar.MINUTE, 0);
- cal.set(Calendar.SECOND, 0);
- cal.set(Calendar.MILLISECOND, 0);
- cal.add(Calendar.DAY_OF_YEAR, 1);
- long t = cal.getTimeInMillis();
- if (this.tomorrow != t) logindex.set(0);
- this.tomorrow = t;
- }
-
- private void open() {
- final String name = "Redkale-Logging-" + getClass().getSimpleName() + "-Thread";
- new Thread() {
- {
- setName(name);
- setDaemon(true);
- }
-
- @Override
- public void run() {
- while (true) {
- try {
- LogRecord log = logqueue.take();
- final boolean bigger = (limit > 0 && limit <= loglength.get());
- final boolean changeday = tomorrow <= log.getMillis();
- if (bigger || changeday) {
- updateTomorrow();
- if (logstream != null) {
- logstream.close();
- 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);
- }
- Files.move(logfile.toPath(), new File(logfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
- } else {
- if (logfile.exists() && logfile.length() < 1) logfile.delete();
- }
- logstream = null;
- }
- }
- if (unusual != null && changeday && logunusualstream != null) {
- logunusualstream.close();
- 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);
- }
- Files.move(logunusualfile.toPath(), new File(logunusualfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
- } else {
- if (logunusualfile.exists() && logunusualfile.length() < 1) logunusualfile.delete();
- }
- logunusualstream = null;
- }
- if (logstream == null) {
- logindex.incrementAndGet();
- java.time.LocalDate date = LocalDate.now();
- logfile = new File(pattern.replace("%m", String.valueOf((date.getYear() * 100 + date.getMonthValue()))).replace("%d", String.valueOf((date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth()))));
- logfile.getParentFile().mkdirs();
- loglength.set(logfile.length());
- logstream = new FileOutputStream(logfile, append);
- }
- if (unusual != null && logunusualstream == null) {
- logunusualindex.incrementAndGet();
- java.time.LocalDate date = LocalDate.now();
- logunusualfile = new File(unusual.replace("%m", String.valueOf((date.getYear() * 100 + date.getMonthValue()))).replace("%d", String.valueOf((date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth()))));
- logunusualfile.getParentFile().mkdirs();
- logunusuallength.set(logunusualfile.length());
- logunusualstream = new FileOutputStream(logunusualfile, append);
- }
- //----------------------鍐欐棩蹇-------------------------
- String message = getFormatter().format(log);
- String encoding = getEncoding();
- byte[] bytes = encoding == null ? message.getBytes() : message.getBytes(encoding);
- logstream.write(bytes);
- loglength.addAndGet(bytes.length);
- if (unusual != null && (log.getLevel() == Level.WARNING || log.getLevel() == Level.SEVERE)) {
- logunusualstream.write(bytes);
- logunusuallength.addAndGet(bytes.length);
- }
- } catch (Exception e) {
- ErrorManager err = getErrorManager();
- if (err != null) err.error(null, e, ErrorManager.WRITE_FAILURE);
- }
- }
-
- }
- }.start();
- }
-
- public String getPrefix() {
- return "";
- }
-
- private void configure() {
- LogManager manager = LogManager.getLogManager();
- String cname = LoggingFileHandler.class.getName();
- this.pattern = manager.getProperty(cname + ".pattern");
- if (this.pattern == null) {
- this.pattern = "logs-%m/" + getPrefix() + "log-%d.log";
- } else {
- int pos = this.pattern.lastIndexOf('/');
- if (pos > 0) {
- this.pattern = this.pattern.substring(0, pos + 1) + getPrefix() + this.pattern.substring(pos + 1);
- } else {
- this.pattern = getPrefix() + this.pattern;
- }
- }
- String unusualstr = manager.getProperty(cname + ".unusual");
- if (unusualstr != null) {
- int pos = unusualstr.lastIndexOf('/');
- if (pos > 0) {
- this.unusual = unusualstr.substring(0, pos + 1) + getPrefix() + unusualstr.substring(pos + 1);
- } else {
- this.unusual = getPrefix() + unusualstr;
- }
- }
- String limitstr = manager.getProperty(cname + ".limit");
- try {
- if (limitstr != null) {
- limitstr = limitstr.toUpperCase();
- boolean g = limitstr.indexOf('G') > 0;
- boolean m = limitstr.indexOf('M') > 0;
- boolean k = limitstr.indexOf('K') > 0;
- int ls = Math.abs(Integer.decode(limitstr.replace("G", "").replace("M", "").replace("K", "").replace("B", "")));
- if (g) {
- ls *= 1024 * 1024 * 1024;
- } else if (m) {
- ls *= 1024 * 1024;
- } else if (k) {
- ls *= 1024;
- }
- this.limit = ls;
- }
- } catch (Exception e) {
- }
- String countstr = manager.getProperty(cname + ".count");
- try {
- 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);
- } catch (Exception e) {
- }
- String levelstr = manager.getProperty(cname + ".level");
- try {
- if (levelstr != null) {
- Level l = Level.parse(levelstr);
- setLevel(l != null ? l : Level.ALL);
- }
- } catch (Exception e) {
- }
- String filterstr = manager.getProperty(cname + ".filter");
- try {
- if (filterstr != null) {
- Class> clz = ClassLoader.getSystemClassLoader().loadClass(filterstr);
- RedkaleClassLoader.putReflectionDeclaredConstructors(clz, clz.getName());
- setFilter((Filter) clz.getDeclaredConstructor().newInstance());
- }
- } catch (Exception e) {
- }
- String formatterstr = manager.getProperty(cname + ".formatter");
- try {
- if (formatterstr != null) {
- Class> clz = ClassLoader.getSystemClassLoader().loadClass(formatterstr);
- RedkaleClassLoader.putReflectionDeclaredConstructors(clz, clz.getName());
- setFormatter((Formatter) clz.getDeclaredConstructor().newInstance());
- }
- } catch (Exception e) {
- }
- if (getFormatter() == null) setFormatter(new SimpleFormatter());
-
- String encodingstr = manager.getProperty(cname + ".encoding");
- try {
- if (encodingstr != null) setEncoding(encodingstr);
- } catch (Exception e) {
- }
-
- String denyregstr = manager.getProperty(cname + ".denyreg");
- try {
- if (denyregstr != null && !denyregstr.trim().isEmpty()) {
- denyreg = Pattern.compile(denyregstr);
- }
- } catch (Exception e) {
- }
- }
-
- @Override
- public void publish(LogRecord log) {
- final String sourceClassName = log.getSourceClassName();
- if (sourceClassName == null || true) {
- StackTraceElement[] ses = new Throwable().getStackTrace();
- for (int i = 2; i < ses.length; i++) {
- if (ses[i].getClassName().startsWith("java.util.logging")) continue;
- log.setSourceClassName('[' + Thread.currentThread().getName() + "] " + ses[i].getClassName());
- log.setSourceMethodName(ses[i].getMethodName());
- break;
- }
- } else {
- log.setSourceClassName('[' + Thread.currentThread().getName() + "] " + sourceClassName);
- }
- if (denyreg != null && denyreg.matcher(log.getMessage()).find()) return;
- logqueue.offer(log);
- }
-
- @Override
- public void flush() {
- try {
- if (logstream != null) logstream.flush();
- } catch (Exception e) {
- ErrorManager err = getErrorManager();
- if (err != null) err.error(null, e, ErrorManager.FLUSH_FAILURE);
- }
- }
-
- @Override
- public void close() throws SecurityException {
- try {
- if (logstream != null) logstream.close();
- } catch (Exception e) {
- ErrorManager err = getErrorManager();
- if (err != null) err.error(null, e, ErrorManager.CLOSE_FAILURE);
- }
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import org.redkale.util.RedkaleClassLoader;
+
+import java.io.*;
+import java.nio.file.*;
+import static java.nio.file.StandardCopyOption.*;
+import java.time.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.*;
+import java.util.logging.*;
+import java.util.logging.Formatter;
+import java.util.regex.Pattern;
+
+/**
+ * 鑷畾涔夌殑鏃ュ織杈撳嚭绫
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+@SuppressWarnings("unchecked")
+public class LoggingFileHandler extends Handler {
+
+ //public static final String FORMATTER_FORMAT = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL %4$s %2$s%n%5$s%6$s%n";
+ public static final String FORMATTER_FORMAT = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%tL %4$s %2$s\r\n%5$s%6$s\r\n";
+
+ /**
+ * SNCP鐨勬棩蹇楄緭鍑篐andler
+ */
+ public static class LoggingSncpFileHandler extends LoggingFileHandler {
+
+ @Override
+ public String getPrefix() {
+ return "sncp-";
+ }
+ }
+
+ /**
+ * 榛樿鐨勬棩蹇楁椂闂存牸寮忓寲绫
+ * 涓嶴impleFormatter鐨勫尯鍒湪浜巐evel涓嶄娇鐢ㄦ湰鍦板寲
+ *
+ */
+ public static class LoggingFormater extends Formatter {
+
+ @Override
+ public String format(LogRecord log) {
+ String source;
+ if (log.getSourceClassName() != null) {
+ source = log.getSourceClassName();
+ if (log.getSourceMethodName() != null) {
+ source += " " + log.getSourceMethodName();
+ }
+ } else {
+ source = log.getLoggerName();
+ }
+ String message = formatMessage(log);
+ String throwable = "";
+ if (log.getThrown() != null) {
+ StringWriter sw = new StringWriter();
+ PrintWriter pw = new PrintWriter(sw) {
+ @Override
+ public void println() {
+ super.print("\r\n");
+ }
+ };
+ pw.println();
+ log.getThrown().printStackTrace(pw);
+ pw.close();
+ throwable = sw.toString();
+ }
+ return String.format(FORMATTER_FORMAT,
+ System.currentTimeMillis(),
+ source,
+ log.getLoggerName(),
+ log.getLevel().getName(),
+ message,
+ throwable);
+ }
+ }
+
+ public static void initDebugLogConfig() {
+ try {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ final PrintStream ps = new PrintStream(out);
+ ps.println("handlers = java.util.logging.ConsoleHandler");
+ ps.println(".level = FINEST");
+ ps.println("jdk.level = INFO");
+ ps.println("sun.level = INFO");
+ ps.println("com.sun.level = INFO");
+ ps.println("javax.level = INFO");
+ ps.println("java.util.logging.ConsoleHandler.level = FINEST");
+ ps.println("java.util.logging.ConsoleHandler.formatter = " + LoggingFileHandler.LoggingFormater.class.getName());
+ LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray()));
+ } catch (Exception e) {
+ }
+ }
+
+ protected final LinkedBlockingQueue logqueue = new LinkedBlockingQueue();
+
+ private String pattern;
+
+ private String unusual; //涓嶄负null琛ㄧず灏 WARNING銆丼EVERE 绾у埆鐨勬棩蹇楀啓鍏ュ崟鐙殑鏂囦欢涓
+
+ private int limit; //鏂囦欢澶у皬闄愬埗
+
+ private final AtomicInteger logindex = new AtomicInteger();
+
+ private final AtomicInteger logunusualindex = new AtomicInteger();
+
+ private int count = 1; //鏂囦欢闄愬埗
+
+ private long tomorrow;
+
+ private boolean append;
+
+ private Pattern denyreg;
+
+ private final AtomicLong loglength = new AtomicLong();
+
+ private final AtomicLong logunusuallength = new AtomicLong();
+
+ private File logfile;
+
+ private File logunusualfile;
+
+ private OutputStream logstream;
+
+ private OutputStream logunusualstream;
+
+ public LoggingFileHandler() {
+ updateTomorrow();
+ configure();
+ open();
+ }
+
+ private void updateTomorrow() {
+ Calendar cal = Calendar.getInstance();
+ cal.set(Calendar.HOUR_OF_DAY, 0);
+ cal.set(Calendar.MINUTE, 0);
+ cal.set(Calendar.SECOND, 0);
+ cal.set(Calendar.MILLISECOND, 0);
+ cal.add(Calendar.DAY_OF_YEAR, 1);
+ long t = cal.getTimeInMillis();
+ if (this.tomorrow != t) logindex.set(0);
+ this.tomorrow = t;
+ }
+
+ private void open() {
+ final String name = "Redkale-Logging-" + getClass().getSimpleName() + "-Thread";
+ new Thread() {
+ {
+ setName(name);
+ setDaemon(true);
+ }
+
+ @Override
+ public void run() {
+ while (true) {
+ try {
+ LogRecord log = logqueue.take();
+ final boolean bigger = (limit > 0 && limit <= loglength.get());
+ final boolean changeday = tomorrow <= log.getMillis();
+ if (bigger || changeday) {
+ updateTomorrow();
+ if (logstream != null) {
+ logstream.close();
+ 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);
+ }
+ Files.move(logfile.toPath(), new File(logfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
+ } else {
+ if (logfile.exists() && logfile.length() < 1) logfile.delete();
+ }
+ logstream = null;
+ }
+ }
+ if (unusual != null && changeday && logunusualstream != null) {
+ logunusualstream.close();
+ 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);
+ }
+ Files.move(logunusualfile.toPath(), new File(logunusualfile.getPath() + ".1").toPath(), REPLACE_EXISTING, ATOMIC_MOVE);
+ } else {
+ if (logunusualfile.exists() && logunusualfile.length() < 1) logunusualfile.delete();
+ }
+ logunusualstream = null;
+ }
+ if (logstream == null) {
+ logindex.incrementAndGet();
+ java.time.LocalDate date = LocalDate.now();
+ logfile = new File(pattern.replace("%m", String.valueOf((date.getYear() * 100 + date.getMonthValue()))).replace("%d", String.valueOf((date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth()))));
+ logfile.getParentFile().mkdirs();
+ loglength.set(logfile.length());
+ logstream = new FileOutputStream(logfile, append);
+ }
+ if (unusual != null && logunusualstream == null) {
+ logunusualindex.incrementAndGet();
+ java.time.LocalDate date = LocalDate.now();
+ logunusualfile = new File(unusual.replace("%m", String.valueOf((date.getYear() * 100 + date.getMonthValue()))).replace("%d", String.valueOf((date.getYear() * 10000 + date.getMonthValue() * 100 + date.getDayOfMonth()))));
+ logunusualfile.getParentFile().mkdirs();
+ logunusuallength.set(logunusualfile.length());
+ logunusualstream = new FileOutputStream(logunusualfile, append);
+ }
+ //----------------------鍐欐棩蹇-------------------------
+ String message = getFormatter().format(log);
+ String encoding = getEncoding();
+ byte[] bytes = encoding == null ? message.getBytes() : message.getBytes(encoding);
+ logstream.write(bytes);
+ loglength.addAndGet(bytes.length);
+ if (unusual != null && (log.getLevel() == Level.WARNING || log.getLevel() == Level.SEVERE)) {
+ logunusualstream.write(bytes);
+ logunusuallength.addAndGet(bytes.length);
+ }
+ } catch (Exception e) {
+ ErrorManager err = getErrorManager();
+ if (err != null) err.error(null, e, ErrorManager.WRITE_FAILURE);
+ }
+ }
+
+ }
+ }.start();
+ }
+
+ public String getPrefix() {
+ return "";
+ }
+
+ private void configure() {
+ LogManager manager = LogManager.getLogManager();
+ String cname = LoggingFileHandler.class.getName();
+ this.pattern = manager.getProperty(cname + ".pattern");
+ if (this.pattern == null) {
+ this.pattern = "logs-%m/" + getPrefix() + "log-%d.log";
+ } else {
+ int pos = this.pattern.lastIndexOf('/');
+ if (pos > 0) {
+ this.pattern = this.pattern.substring(0, pos + 1) + getPrefix() + this.pattern.substring(pos + 1);
+ } else {
+ this.pattern = getPrefix() + this.pattern;
+ }
+ }
+ String unusualstr = manager.getProperty(cname + ".unusual");
+ if (unusualstr != null) {
+ int pos = unusualstr.lastIndexOf('/');
+ if (pos > 0) {
+ this.unusual = unusualstr.substring(0, pos + 1) + getPrefix() + unusualstr.substring(pos + 1);
+ } else {
+ this.unusual = getPrefix() + unusualstr;
+ }
+ }
+ String limitstr = manager.getProperty(cname + ".limit");
+ try {
+ if (limitstr != null) {
+ limitstr = limitstr.toUpperCase();
+ boolean g = limitstr.indexOf('G') > 0;
+ boolean m = limitstr.indexOf('M') > 0;
+ boolean k = limitstr.indexOf('K') > 0;
+ int ls = Math.abs(Integer.decode(limitstr.replace("G", "").replace("M", "").replace("K", "").replace("B", "")));
+ if (g) {
+ ls *= 1024 * 1024 * 1024;
+ } else if (m) {
+ ls *= 1024 * 1024;
+ } else if (k) {
+ ls *= 1024;
+ }
+ this.limit = ls;
+ }
+ } catch (Exception e) {
+ }
+ String countstr = manager.getProperty(cname + ".count");
+ try {
+ 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);
+ } catch (Exception e) {
+ }
+ String levelstr = manager.getProperty(cname + ".level");
+ try {
+ if (levelstr != null) {
+ Level l = Level.parse(levelstr);
+ setLevel(l != null ? l : Level.ALL);
+ }
+ } catch (Exception e) {
+ }
+ String filterstr = manager.getProperty(cname + ".filter");
+ try {
+ if (filterstr != null) {
+ Class> clz = ClassLoader.getSystemClassLoader().loadClass(filterstr);
+ RedkaleClassLoader.putReflectionDeclaredConstructors(clz, clz.getName());
+ setFilter((Filter) clz.getDeclaredConstructor().newInstance());
+ }
+ } catch (Exception e) {
+ }
+ String formatterstr = manager.getProperty(cname + ".formatter");
+ try {
+ if (formatterstr != null) {
+ Class> clz = ClassLoader.getSystemClassLoader().loadClass(formatterstr);
+ RedkaleClassLoader.putReflectionDeclaredConstructors(clz, clz.getName());
+ setFormatter((Formatter) clz.getDeclaredConstructor().newInstance());
+ }
+ } catch (Exception e) {
+ }
+ if (getFormatter() == null) setFormatter(new SimpleFormatter());
+
+ String encodingstr = manager.getProperty(cname + ".encoding");
+ try {
+ if (encodingstr != null) setEncoding(encodingstr);
+ } catch (Exception e) {
+ }
+
+ String denyregstr = manager.getProperty(cname + ".denyreg");
+ try {
+ if (denyregstr != null && !denyregstr.trim().isEmpty()) {
+ denyreg = Pattern.compile(denyregstr);
+ }
+ } catch (Exception e) {
+ }
+ }
+
+ @Override
+ public void publish(LogRecord log) {
+ final String sourceClassName = log.getSourceClassName();
+ if (sourceClassName == null || true) {
+ StackTraceElement[] ses = new Throwable().getStackTrace();
+ for (int i = 2; i < ses.length; i++) {
+ if (ses[i].getClassName().startsWith("java.util.logging")) continue;
+ log.setSourceClassName('[' + Thread.currentThread().getName() + "] " + ses[i].getClassName());
+ log.setSourceMethodName(ses[i].getMethodName());
+ break;
+ }
+ } else {
+ log.setSourceClassName('[' + Thread.currentThread().getName() + "] " + sourceClassName);
+ }
+ if (denyreg != null && denyreg.matcher(log.getMessage()).find()) return;
+ logqueue.offer(log);
+ }
+
+ @Override
+ public void flush() {
+ try {
+ if (logstream != null) logstream.flush();
+ } catch (Exception e) {
+ ErrorManager err = getErrorManager();
+ if (err != null) err.error(null, e, ErrorManager.FLUSH_FAILURE);
+ }
+ }
+
+ @Override
+ public void close() throws SecurityException {
+ try {
+ if (logstream != null) logstream.close();
+ } catch (Exception e) {
+ ErrorManager err = getErrorManager();
+ if (err != null) err.error(null, e, ErrorManager.CLOSE_FAILURE);
+ }
+ }
+
+}
diff --git a/src/main/java/org/redkale/boot/NodeInterceptor.java b/src/main/java/org/redkale/boot/NodeInterceptor.java
index 138e41743..a6edf764b 100644
--- a/src/main/java/org/redkale/boot/NodeInterceptor.java
+++ b/src/main/java/org/redkale/boot/NodeInterceptor.java
@@ -1,38 +1,38 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-/**
- * NodeServer鐨勬嫤鎴被
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-public class NodeInterceptor {
-
- /** *
- * Server.start涔嬪墠璋冪敤
- * NodeServer.start鐨勯儴缃叉槸鍏堟墽琛孨odeInterceptor.preStart锛屽啀鎵ц Server.start 鏂规硶
- *
- * @param server NodeServer
- */
- public void preStart(NodeServer server) {
-
- }
-
- /**
- * Server.shutdown涔嬪墠璋冪敤
- * NodeServer.shutdown鐨勯儴缃叉槸鍏堟墽琛孨odeInterceptor.preShutdown锛屽啀鎵ц Server.sshutdown 鏂规硶
- *
- * @param server NodeServer
- */
- public void preShutdown(NodeServer server) {
-
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+/**
+ * NodeServer鐨勬嫤鎴被
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+public class NodeInterceptor {
+
+ /** *
+ * Server.start涔嬪墠璋冪敤
+ * NodeServer.start鐨勯儴缃叉槸鍏堟墽琛孨odeInterceptor.preStart锛屽啀鎵ц Server.start 鏂规硶
+ *
+ * @param server NodeServer
+ */
+ public void preStart(NodeServer server) {
+
+ }
+
+ /**
+ * Server.shutdown涔嬪墠璋冪敤
+ * NodeServer.shutdown鐨勯儴缃叉槸鍏堟墽琛孨odeInterceptor.preShutdown锛屽啀鎵ц Server.sshutdown 鏂规硶
+ *
+ * @param server NodeServer
+ */
+ public void preShutdown(NodeServer server) {
+
+ }
+
+}
diff --git a/src/main/java/org/redkale/boot/NodeProtocol.java b/src/main/java/org/redkale/boot/NodeProtocol.java
index ab72e3cef..f37f8da57 100644
--- a/src/main/java/org/redkale/boot/NodeProtocol.java
+++ b/src/main/java/org/redkale/boot/NodeProtocol.java
@@ -1,24 +1,24 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.lang.annotation.*;
-
-/**
- * 鏍规嵁application.xml涓殑server鑺傜偣涓殑protocol鍊兼潵閫傞厤Server鐨勫姞杞介昏緫, 鍙兘娉ㄨВ鍦∟odeServer瀛愮被涓
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-@Target({ElementType.TYPE})
-@Retention(RetentionPolicy.RUNTIME)
-@Documented
-public @interface NodeProtocol {
-
- String value();
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.lang.annotation.*;
+
+/**
+ * 鏍规嵁application.xml涓殑server鑺傜偣涓殑protocol鍊兼潵閫傞厤Server鐨勫姞杞介昏緫, 鍙兘娉ㄨВ鍦∟odeServer瀛愮被涓
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+@Target({ElementType.TYPE})
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface NodeProtocol {
+
+ String value();
+}
diff --git a/src/main/java/org/redkale/boot/NodeSncpServer.java b/src/main/java/org/redkale/boot/NodeSncpServer.java
index ef2e1e173..293d0d3de 100644
--- a/src/main/java/org/redkale/boot/NodeSncpServer.java
+++ b/src/main/java/org/redkale/boot/NodeSncpServer.java
@@ -1,125 +1,125 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.lang.reflect.Modifier;
-import java.net.*;
-import java.util.*;
-import java.util.logging.Level;
-import org.redkale.boot.ClassFilter.FilterEntry;
-import org.redkale.mq.MessageAgent;
-import org.redkale.net.*;
-import org.redkale.net.sncp.*;
-import org.redkale.service.*;
-import org.redkale.util.*;
-import org.redkale.util.AnyValue.DefaultAnyValue;
-
-/**
- * SNCP Server鑺傜偣鐨勯厤缃甋erver
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-@NodeProtocol("SNCP")
-public class NodeSncpServer extends NodeServer {
-
- protected final SncpServer sncpServer;
-
- private NodeSncpServer(Application application, AnyValue serconf) {
- 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; //鏈湴妯″紡鐨凷ervice涓嶇敓鎴怱ncpServlet
- SncpDynServlet servlet = sncpServer.addSncpServlet(x);
- dynServletMap.put(x, servlet);
- if (agent != null) agent.putService(this, x, servlet);
- };
- }
-
- public static NodeServer createNodeServer(Application application, AnyValue serconf) {
- return new NodeSncpServer(application, serconf);
- }
-
- private static Server createServer(Application application, AnyValue serconf) {
- return new SncpServer(application, application.getStartTime(), serconf, application.getResourceFactory().createChild());
- }
-
- @Override
- public InetSocketAddress getSocketAddress() {
- return sncpServer == null ? null : sncpServer.getSocketAddress();
- }
-
- public void consumerAccept(MessageAgent messageAgent, Service 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; //璋冭瘯鏃秙erver鎵嶅彲鑳戒负null
- final StringBuilder sb = logger.isLoggable(Level.FINE) ? new StringBuilder() : null;
- final String localThreadName = "[" + Thread.currentThread().getName() + "] ";
- List servlets = sncpServer.getSncpServlets();
- Collections.sort(servlets);
- for (SncpServlet en : servlets) {
- if (sb != null) sb.append(localThreadName).append(" Load ").append(en).append(LINE_SEPARATOR);
- }
- if (sb != null && sb.length() > 0) logger.log(Level.FINE, sb.toString());
- }
-
- @Override
- public boolean isSNCP() {
- return true;
- }
-
- public SncpServer getSncpServer() {
- return sncpServer;
- }
-
- @Override
- protected void loadFilter(ClassFilter extends Filter> filterFilter, ClassFilter otherFilter) throws Exception {
- if (sncpServer != null) loadSncpFilter(this.serverConf.getAnyValue("fliters"), filterFilter);
- }
-
- @SuppressWarnings("unchecked")
- protected void loadSncpFilter(final AnyValue servletsConf, final ClassFilter extends Filter> classFilter) throws Exception {
- final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
- final String localThreadName = "[" + Thread.currentThread().getName() + "] ";
- List> list = new ArrayList(classFilter.getFilterEntrys());
- for (FilterEntry extends Filter> en : list) {
- Class clazz = (Class) en.getType();
- 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(localThreadName).append(" Load ").append(clazz.getName()).append(LINE_SEPARATOR);
- }
- if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
- }
-
- @Override
- protected void loadServlet(ClassFilter extends Servlet> servletFilter, ClassFilter otherFilter) throws Exception {
- RedkaleClassLoader.putReflectionPublicClasses(SncpServlet.class.getName());
- RedkaleClassLoader.putReflectionPublicClasses(SncpDynServlet.class.getName());
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected ClassFilter createFilterClassFilter() {
- return createClassFilter(null, null, SncpFilter.class, new Class[]{org.redkale.watch.WatchFilter.class}, null, "filters", "filter");
- }
-
- @Override
- protected ClassFilter createServletClassFilter() {
- return null;
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.lang.reflect.Modifier;
+import java.net.*;
+import java.util.*;
+import java.util.logging.Level;
+import org.redkale.boot.ClassFilter.FilterEntry;
+import org.redkale.mq.MessageAgent;
+import org.redkale.net.*;
+import org.redkale.net.sncp.*;
+import org.redkale.service.*;
+import org.redkale.util.*;
+import org.redkale.util.AnyValue.DefaultAnyValue;
+
+/**
+ * SNCP Server鑺傜偣鐨勯厤缃甋erver
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+@NodeProtocol("SNCP")
+public class NodeSncpServer extends NodeServer {
+
+ protected final SncpServer sncpServer;
+
+ private NodeSncpServer(Application application, AnyValue serconf) {
+ 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; //鏈湴妯″紡鐨凷ervice涓嶇敓鎴怱ncpServlet
+ SncpDynServlet servlet = sncpServer.addSncpServlet(x);
+ dynServletMap.put(x, servlet);
+ if (agent != null) agent.putService(this, x, servlet);
+ };
+ }
+
+ public static NodeServer createNodeServer(Application application, AnyValue serconf) {
+ return new NodeSncpServer(application, serconf);
+ }
+
+ private static Server createServer(Application application, AnyValue serconf) {
+ return new SncpServer(application, application.getStartTime(), serconf, application.getResourceFactory().createChild());
+ }
+
+ @Override
+ public InetSocketAddress getSocketAddress() {
+ return sncpServer == null ? null : sncpServer.getSocketAddress();
+ }
+
+ public void consumerAccept(MessageAgent messageAgent, Service 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; //璋冭瘯鏃秙erver鎵嶅彲鑳戒负null
+ final StringBuilder sb = logger.isLoggable(Level.FINE) ? new StringBuilder() : null;
+ final String localThreadName = "[" + Thread.currentThread().getName() + "] ";
+ List servlets = sncpServer.getSncpServlets();
+ Collections.sort(servlets);
+ for (SncpServlet en : servlets) {
+ if (sb != null) sb.append(localThreadName).append(" Load ").append(en).append(LINE_SEPARATOR);
+ }
+ if (sb != null && sb.length() > 0) logger.log(Level.FINE, sb.toString());
+ }
+
+ @Override
+ public boolean isSNCP() {
+ return true;
+ }
+
+ public SncpServer getSncpServer() {
+ return sncpServer;
+ }
+
+ @Override
+ protected void loadFilter(ClassFilter extends Filter> filterFilter, ClassFilter otherFilter) throws Exception {
+ if (sncpServer != null) loadSncpFilter(this.serverConf.getAnyValue("fliters"), filterFilter);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected void loadSncpFilter(final AnyValue servletsConf, final ClassFilter extends Filter> classFilter) throws Exception {
+ final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
+ final String localThreadName = "[" + Thread.currentThread().getName() + "] ";
+ List> list = new ArrayList(classFilter.getFilterEntrys());
+ for (FilterEntry extends Filter> en : list) {
+ Class clazz = (Class) en.getType();
+ 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(localThreadName).append(" Load ").append(clazz.getName()).append(LINE_SEPARATOR);
+ }
+ if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
+ }
+
+ @Override
+ protected void loadServlet(ClassFilter extends Servlet> servletFilter, ClassFilter otherFilter) throws Exception {
+ RedkaleClassLoader.putReflectionPublicClasses(SncpServlet.class.getName());
+ RedkaleClassLoader.putReflectionPublicClasses(SncpDynServlet.class.getName());
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected ClassFilter createFilterClassFilter() {
+ return createClassFilter(null, null, SncpFilter.class, new Class[]{org.redkale.watch.WatchFilter.class}, null, "filters", "filter");
+ }
+
+ @Override
+ protected ClassFilter createServletClassFilter() {
+ return null;
+ }
+
+}
diff --git a/src/main/java/org/redkale/boot/NodeWatchServer.java b/src/main/java/org/redkale/boot/NodeWatchServer.java
index 67760a416..b7ea1f695 100644
--- a/src/main/java/org/redkale/boot/NodeWatchServer.java
+++ b/src/main/java/org/redkale/boot/NodeWatchServer.java
@@ -1,53 +1,53 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.lang.annotation.Annotation;
-import org.redkale.net.*;
-import org.redkale.net.http.*;
-import org.redkale.service.Service;
-import org.redkale.util.AnyValue;
-import org.redkale.watch.*;
-
-/**
- *
- * @author zhangjx
- */
-@NodeProtocol("WATCH")
-public class NodeWatchServer extends NodeHttpServer {
-
- public NodeWatchServer(Application application, AnyValue serconf) {
- super(application, serconf);
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected ClassFilter createServiceClassFilter() {
- return createClassFilter(this.sncpGroup, null, WatchService.class, null, Annotation.class, "services", "service");
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected ClassFilter createFilterClassFilter() {
- return createClassFilter(null, null, WatchFilter.class, null, null, "filters", "filter");
- }
-
- @Override
- @SuppressWarnings("unchecked")
- protected ClassFilter createServletClassFilter() {
- return createClassFilter(null, WebServlet.class, WatchServlet.class, null, null, "servlets", "servlet");
- }
-
- @Override
- protected ClassFilter createOtherClassFilter() {
- return null;
- }
-
- @Override
- public boolean isWATCH() {
- return true;
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.lang.annotation.Annotation;
+import org.redkale.net.*;
+import org.redkale.net.http.*;
+import org.redkale.service.Service;
+import org.redkale.util.AnyValue;
+import org.redkale.watch.*;
+
+/**
+ *
+ * @author zhangjx
+ */
+@NodeProtocol("WATCH")
+public class NodeWatchServer extends NodeHttpServer {
+
+ public NodeWatchServer(Application application, AnyValue serconf) {
+ super(application, serconf);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected ClassFilter createServiceClassFilter() {
+ return createClassFilter(this.sncpGroup, null, WatchService.class, null, Annotation.class, "services", "service");
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected ClassFilter createFilterClassFilter() {
+ return createClassFilter(null, null, WatchFilter.class, null, null, "filters", "filter");
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ protected ClassFilter createServletClassFilter() {
+ return createClassFilter(null, WebServlet.class, WatchServlet.class, null, null, "servlets", "servlet");
+ }
+
+ @Override
+ protected ClassFilter createOtherClassFilter() {
+ return null;
+ }
+
+ @Override
+ public boolean isWATCH() {
+ return true;
+ }
+}
diff --git a/src/main/java/org/redkale/boot/PrepareCompiler.java b/src/main/java/org/redkale/boot/PrepareCompiler.java
index ed91febcc..7a1c0efca 100644
--- a/src/main/java/org/redkale/boot/PrepareCompiler.java
+++ b/src/main/java/org/redkale/boot/PrepareCompiler.java
@@ -1,86 +1,86 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot;
-
-import java.lang.reflect.Modifier;
-import javax.persistence.Entity;
-import org.redkale.boot.ClassFilter.FilterEntry;
-import org.redkale.convert.Decodeable;
-import org.redkale.convert.bson.BsonFactory;
-import org.redkale.convert.json.*;
-import org.redkale.source.*;
-import org.redkale.util.*;
-
-/**
- * 鎵ц涓娆pplication.run鎻愬墠鑾峰彇鎵鏈夊姩鎬佺被
- *
- * @author zhangjx
- * @since 2.5.0
- */
-public class PrepareCompiler {
-
-// public static void main(String[] args) throws Exception {
-// new PrepareCompiler().run();
-// }
- public Application run() throws Exception {
- final Application application = new Application(false, true, Application.loadAppConfig());
- application.init();
- for (ApplicationListener listener : application.listeners) {
- listener.preStart(application);
- }
- for (ApplicationListener listener : application.listeners) {
- listener.preCompile(application);
- }
- application.start();
- final boolean hasSncp = application.getNodeServers().stream().filter(v -> v instanceof NodeSncpServer).findFirst().isPresent();
- final String[] exlibs = (application.excludelibs != null ? (application.excludelibs + ";") : "").split(";");
-
- final ClassFilter> entityFilter = new ClassFilter(application.getClassLoader(), Entity.class, Object.class, (Class[]) null);
- final ClassFilter> beanFilter = new ClassFilter(application.getClassLoader(), Bean.class, Object.class, (Class[]) null);
- final ClassFilter> filterFilter = new ClassFilter(application.getClassLoader(), null, FilterBean.class, (Class[]) null);
-
- ClassFilter.Loader.load(application.getHome(), application.getClassLoader(), exlibs, entityFilter, beanFilter, filterFilter);
-
- for (FilterEntry en : entityFilter.getFilterEntrys()) {
- Class clz = en.getType();
- 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);
- Decodeable decoder = JsonFactory.root().loadDecoder(clz);
- if (hasSncp) BsonFactory.root().loadDecoder(clz);
- decoder.convertFrom(new JsonReader("{}"));
- } catch (Exception e) { //JsonFactory.loadDecoder鍙兘浼氬け璐ワ紝鍥犱负class鍙兘鍖呭惈鎶借薄绫诲瓧娈,濡侰olumnValue.value瀛楁
- }
- }
- for (FilterEntry en : beanFilter.getFilterEntrys()) {
- Class clz = en.getType();
- if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
- try {
- JsonFactory.root().loadEncoder(clz);
- if (hasSncp) BsonFactory.root().loadEncoder(clz);
- Decodeable decoder = JsonFactory.root().loadDecoder(clz);
- if (hasSncp) BsonFactory.root().loadDecoder(clz);
- decoder.convertFrom(new JsonReader("{}"));
- } catch (Exception e) { //JsonFactory.loadDecoder鍙兘浼氬け璐ワ紝鍥犱负class鍙兘鍖呭惈鎶借薄绫诲瓧娈,濡侰olumnValue.value瀛楁
- }
- }
- for (FilterEntry en : filterFilter.getFilterEntrys()) {
- Class clz = en.getType();
- if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
- try {
- FilterNodeBean.load(clz);
- } catch (Exception e) {
- }
- }
- for (ApplicationListener listener : application.listeners) {
- listener.postCompile(application);
- }
- application.shutdown();
- return application;
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot;
+
+import java.lang.reflect.Modifier;
+import javax.persistence.Entity;
+import org.redkale.boot.ClassFilter.FilterEntry;
+import org.redkale.convert.Decodeable;
+import org.redkale.convert.bson.BsonFactory;
+import org.redkale.convert.json.*;
+import org.redkale.source.*;
+import org.redkale.util.*;
+
+/**
+ * 鎵ц涓娆pplication.run鎻愬墠鑾峰彇鎵鏈夊姩鎬佺被
+ *
+ * @author zhangjx
+ * @since 2.5.0
+ */
+public class PrepareCompiler {
+
+// public static void main(String[] args) throws Exception {
+// new PrepareCompiler().run();
+// }
+ public Application run() throws Exception {
+ final Application application = new Application(false, true, Application.loadAppConfig());
+ application.init();
+ for (ApplicationListener listener : application.listeners) {
+ listener.preStart(application);
+ }
+ for (ApplicationListener listener : application.listeners) {
+ listener.preCompile(application);
+ }
+ application.start();
+ final boolean hasSncp = application.getNodeServers().stream().filter(v -> v instanceof NodeSncpServer).findFirst().isPresent();
+ final String[] exlibs = (application.excludelibs != null ? (application.excludelibs + ";") : "").split(";");
+
+ final ClassFilter> entityFilter = new ClassFilter(application.getClassLoader(), Entity.class, Object.class, (Class[]) null);
+ final ClassFilter> beanFilter = new ClassFilter(application.getClassLoader(), Bean.class, Object.class, (Class[]) null);
+ final ClassFilter> filterFilter = new ClassFilter(application.getClassLoader(), null, FilterBean.class, (Class[]) null);
+
+ ClassFilter.Loader.load(application.getHome(), application.getClassLoader(), exlibs, entityFilter, beanFilter, filterFilter);
+
+ for (FilterEntry en : entityFilter.getFilterEntrys()) {
+ Class clz = en.getType();
+ 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);
+ Decodeable decoder = JsonFactory.root().loadDecoder(clz);
+ if (hasSncp) BsonFactory.root().loadDecoder(clz);
+ decoder.convertFrom(new JsonReader("{}"));
+ } catch (Exception e) { //JsonFactory.loadDecoder鍙兘浼氬け璐ワ紝鍥犱负class鍙兘鍖呭惈鎶借薄绫诲瓧娈,濡侰olumnValue.value瀛楁
+ }
+ }
+ for (FilterEntry en : beanFilter.getFilterEntrys()) {
+ Class clz = en.getType();
+ if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
+ try {
+ JsonFactory.root().loadEncoder(clz);
+ if (hasSncp) BsonFactory.root().loadEncoder(clz);
+ Decodeable decoder = JsonFactory.root().loadDecoder(clz);
+ if (hasSncp) BsonFactory.root().loadDecoder(clz);
+ decoder.convertFrom(new JsonReader("{}"));
+ } catch (Exception e) { //JsonFactory.loadDecoder鍙兘浼氬け璐ワ紝鍥犱负class鍙兘鍖呭惈鎶借薄绫诲瓧娈,濡侰olumnValue.value瀛楁
+ }
+ }
+ for (FilterEntry en : filterFilter.getFilterEntrys()) {
+ Class clz = en.getType();
+ if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) continue;
+ try {
+ FilterNodeBean.load(clz);
+ } catch (Exception e) {
+ }
+ }
+ for (ApplicationListener listener : application.listeners) {
+ listener.postCompile(application);
+ }
+ application.shutdown();
+ return application;
+ }
+}
diff --git a/src/main/java/org/redkale/boot/apidoc-template.html b/src/main/java/org/redkale/boot/apidoc-template.html
index fa0c5cdc5..755dfc2e7 100644
--- a/src/main/java/org/redkale/boot/apidoc-template.html
+++ b/src/main/java/org/redkale/boot/apidoc-template.html
@@ -1,110 +1,110 @@
-
-
-
- 鎺ュ彛鏂囨。(apidoc鐢熸垚)
-
-
-
-
-
-
-
-
-
+
+
+
+ 鎺ュ彛鏂囨。(apidoc鐢熸垚)
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/org/redkale/boot/package-info.java b/src/main/java/org/redkale/boot/package-info.java
index 4e9f60058..2b9eae06d 100644
--- a/src/main/java/org/redkale/boot/package-info.java
+++ b/src/main/java/org/redkale/boot/package-info.java
@@ -1,4 +1,4 @@
-/**
- * 鎻愪緵Redkale鏈嶅姟鍣ㄧ殑鍚姩銆佸垵濮嬪寲鍜屽姞杞藉姛鑳
- */
-package org.redkale.boot;
+/**
+ * 鎻愪緵Redkale鏈嶅姟鍣ㄧ殑鍚姩銆佸垵濮嬪寲鍜屽姞杞藉姛鑳
+ */
+package org.redkale.boot;
diff --git a/src/main/java/org/redkale/boot/watch/AbstractWatchService.java b/src/main/java/org/redkale/boot/watch/AbstractWatchService.java
index 673d7d781..29d385c2e 100644
--- a/src/main/java/org/redkale/boot/watch/AbstractWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/AbstractWatchService.java
@@ -1,23 +1,23 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import org.redkale.service.AbstractService;
-import org.redkale.util.Comment;
-import org.redkale.watch.WatchService;
-
-/**
- *
- * @author zhangjx
- */
-public abstract class AbstractWatchService extends AbstractService implements WatchService {
-
- @Comment("缂哄皯鍙傛暟")
- public static final int RET_WATCH_PARAMS_ILLEGAL = 1600_0001;
-
- @Comment("鎵ц寮傚父")
- public static final int RET_WATCH_RUN_EXCEPTION = 1600_0002;
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import org.redkale.service.AbstractService;
+import org.redkale.util.Comment;
+import org.redkale.watch.WatchService;
+
+/**
+ *
+ * @author zhangjx
+ */
+public abstract class AbstractWatchService extends AbstractService implements WatchService {
+
+ @Comment("缂哄皯鍙傛暟")
+ public static final int RET_WATCH_PARAMS_ILLEGAL = 1600_0001;
+
+ @Comment("鎵ц寮傚父")
+ public static final int RET_WATCH_RUN_EXCEPTION = 1600_0002;
+}
diff --git a/src/main/java/org/redkale/boot/watch/FilterWatchService.java b/src/main/java/org/redkale/boot/watch/FilterWatchService.java
index e5c24137f..039edbef2 100644
--- a/src/main/java/org/redkale/boot/watch/FilterWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/FilterWatchService.java
@@ -1,80 +1,80 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import java.io.IOException;
-import java.util.List;
-import javax.annotation.Resource;
-import org.redkale.boot.*;
-import org.redkale.net.http.*;
-import org.redkale.service.RetResult;
-import org.redkale.util.Comment;
-
-/**
- *
- * @author zhangjx
- */
-@RestService(name = "filter", catalog = "watch", repair = false)
-public class FilterWatchService extends AbstractWatchService {
-
- @Comment("Filter绫诲悕涓嶅瓨鍦")
- public static final int RET_FILTER_TYPE_NOT_EXISTS = 1601_0002;
-
- @Comment("Filter绫诲悕涓嶅悎娉")
- public static final int RET_FILTER_TYPE_ILLEGAL = 1601_0003;
-
- @Comment("Filter绫诲悕宸插瓨鍦")
- public static final int RET_FILTER_EXISTS = 1601_0004;
-
- @Comment("Filter鐨凧AR鍖呬笉瀛樺湪")
- public static final int RET_FILTER_JAR_ILLEGAL = 1601_0005;
-
- @Resource
- protected Application application;
-
- @RestMapping(name = "addFilter", auth = false, comment = "鍔ㄦ佸鍔燜ilter")
- public RetResult addFilter(@RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.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");
- List nodes = application.getNodeServers();
- for (NodeServer node : nodes) {
- if (node.getServer().containsFilter(filterType)) return new RetResult(RET_FILTER_EXISTS, "Filter(" + filterType + ") exists");
- }
- return RetResult.success();
- }
-
- @RestMapping(name = "test1", auth = false, comment = "棰勭暀")
- public RetResult test1() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test2", auth = false, comment = "棰勭暀")
- public RetResult test2() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test3", auth = false, comment = "棰勭暀")
- public RetResult test3() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test4", auth = false, comment = "棰勭暀")
- public RetResult test4() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test5", auth = false, comment = "棰勭暀")
- public RetResult test5() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test6", auth = false, comment = "棰勭暀")
- public RetResult test6() {
- return RetResult.success();
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import java.io.IOException;
+import java.util.List;
+import javax.annotation.Resource;
+import org.redkale.boot.*;
+import org.redkale.net.http.*;
+import org.redkale.service.RetResult;
+import org.redkale.util.Comment;
+
+/**
+ *
+ * @author zhangjx
+ */
+@RestService(name = "filter", catalog = "watch", repair = false)
+public class FilterWatchService extends AbstractWatchService {
+
+ @Comment("Filter绫诲悕涓嶅瓨鍦")
+ public static final int RET_FILTER_TYPE_NOT_EXISTS = 1601_0002;
+
+ @Comment("Filter绫诲悕涓嶅悎娉")
+ public static final int RET_FILTER_TYPE_ILLEGAL = 1601_0003;
+
+ @Comment("Filter绫诲悕宸插瓨鍦")
+ public static final int RET_FILTER_EXISTS = 1601_0004;
+
+ @Comment("Filter鐨凧AR鍖呬笉瀛樺湪")
+ public static final int RET_FILTER_JAR_ILLEGAL = 1601_0005;
+
+ @Resource
+ protected Application application;
+
+ @RestMapping(name = "addFilter", auth = false, comment = "鍔ㄦ佸鍔燜ilter")
+ public RetResult addFilter(@RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.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");
+ List nodes = application.getNodeServers();
+ for (NodeServer node : nodes) {
+ if (node.getServer().containsFilter(filterType)) return new RetResult(RET_FILTER_EXISTS, "Filter(" + filterType + ") exists");
+ }
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test1", auth = false, comment = "棰勭暀")
+ public RetResult test1() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test2", auth = false, comment = "棰勭暀")
+ public RetResult test2() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test3", auth = false, comment = "棰勭暀")
+ public RetResult test3() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test4", auth = false, comment = "棰勭暀")
+ public RetResult test4() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test5", auth = false, comment = "棰勭暀")
+ public RetResult test5() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test6", auth = false, comment = "棰勭暀")
+ public RetResult test6() {
+ 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 1e2c2cf1e..80e7476c9 100644
--- a/src/main/java/org/redkale/boot/watch/ServerWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/ServerWatchService.java
@@ -1,104 +1,104 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.stream.Stream;
-import javax.annotation.Resource;
-import org.redkale.boot.*;
-import org.redkale.net.Server;
-import org.redkale.net.http.*;
-import org.redkale.service.RetResult;
-import org.redkale.util.Comment;
-
-/**
- *
- * @author zhangjx
- */
-@RestService(name = "server", catalog = "watch", repair = false)
-public class ServerWatchService extends AbstractWatchService {
-
- @Comment("涓嶅瓨鍦ㄧ殑Server鑺傜偣")
- public static final int RET_SERVER_NOT_EXISTS = 1602_0001;
-
- @Comment("鏇存敼Server鐩戝惉鍦板潃绔彛澶辫触")
- public static final int RET_SERVER_CHANGEPORT_ERROR = 1602_0002;
-
- @Resource
- protected Application application;
-
- @RestMapping(name = "info", comment = "鍗曚釜Server淇℃伅鏌ヨ")
- 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");
- return new RetResult(formatToMap(node));
- }
-
- @RestMapping(name = "infos", comment = "Server淇℃伅鏌ヨ")
- public RetResult infos() {
- Map rs = new LinkedHashMap<>();
- for (NodeServer ns : application.getNodeServers()) {
- Server server = ns.getServer();
- rs.put("" + server.getSocketAddress().getPort(), formatToMap(ns));
- }
- return new RetResult(rs);
- }
-
- @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`");
- 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");
- final Server server = node.getServer();
- InetSocketAddress newAddr = new InetSocketAddress(newhost == null || newhost.isEmpty() ? server.getSocketAddress().getHostString() : newhost, newport);
- try {
- server.changeAddress(application, newAddr);
- } catch (IOException e) {
- e.printStackTrace();
- return new RetResult(RET_SERVER_CHANGEPORT_ERROR, "changeaddress error");
- }
- return RetResult.success();
- }
-
- private Map formatToMap(NodeServer node) {
- Server server = node.getServer();
- Map rs = new LinkedHashMap<>();
- String protocol = server.getNetprotocol();
- if (node instanceof NodeSncpServer) {
- protocol += "/SNCP";
- } else if (node instanceof NodeWatchServer) {
- protocol += "/WATCH";
- } else if (node instanceof NodeHttpServer) {
- protocol += "/HTTP";
- } else {
- NodeProtocol np = node.getClass().getAnnotation(NodeProtocol.class);
- protocol += "/" + np.value();
- }
- rs.put("name", server.getName());
- rs.put("protocol", protocol);
- rs.put("address", server.getSocketAddress());
- rs.put("backlog", server.getBacklog());
- rs.put("bufferCapacity", server.getBufferCapacity());
- rs.put("bufferPoolSize", server.getBufferPoolSize());
- rs.put("charset", server.getCharset() == null ? "UTF-8" : server.getCharset().name());
- rs.put("maxbody", server.getMaxbody());
- rs.put("maxconns", server.getMaxconns());
- rs.put("serverStartTime", server.getServerStartTime());
- rs.put("responsePoolSize", server.getResponsePoolSize());
- rs.put("readTimeoutSeconds", server.getReadTimeoutSeconds());
- rs.put("writeTimeoutSeconds", server.getWriteTimeoutSeconds());
- rs.put("createConnectionCount", server.getCreateConnectionCount());
- rs.put("livingConnectionCount", server.getLivingConnectionCount());
- rs.put("closedConnectionCount", server.getClosedConnectionCount());
- return rs;
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.*;
+import java.util.stream.Stream;
+import javax.annotation.Resource;
+import org.redkale.boot.*;
+import org.redkale.net.Server;
+import org.redkale.net.http.*;
+import org.redkale.service.RetResult;
+import org.redkale.util.Comment;
+
+/**
+ *
+ * @author zhangjx
+ */
+@RestService(name = "server", catalog = "watch", repair = false)
+public class ServerWatchService extends AbstractWatchService {
+
+ @Comment("涓嶅瓨鍦ㄧ殑Server鑺傜偣")
+ public static final int RET_SERVER_NOT_EXISTS = 1602_0001;
+
+ @Comment("鏇存敼Server鐩戝惉鍦板潃绔彛澶辫触")
+ public static final int RET_SERVER_CHANGEPORT_ERROR = 1602_0002;
+
+ @Resource
+ protected Application application;
+
+ @RestMapping(name = "info", comment = "鍗曚釜Server淇℃伅鏌ヨ")
+ 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");
+ return new RetResult(formatToMap(node));
+ }
+
+ @RestMapping(name = "infos", comment = "Server淇℃伅鏌ヨ")
+ public RetResult infos() {
+ Map rs = new LinkedHashMap<>();
+ for (NodeServer ns : application.getNodeServers()) {
+ Server server = ns.getServer();
+ rs.put("" + server.getSocketAddress().getPort(), formatToMap(ns));
+ }
+ return new RetResult(rs);
+ }
+
+ @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`");
+ 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");
+ final Server server = node.getServer();
+ InetSocketAddress newAddr = new InetSocketAddress(newhost == null || newhost.isEmpty() ? server.getSocketAddress().getHostString() : newhost, newport);
+ try {
+ server.changeAddress(application, newAddr);
+ } catch (IOException e) {
+ e.printStackTrace();
+ return new RetResult(RET_SERVER_CHANGEPORT_ERROR, "changeaddress error");
+ }
+ return RetResult.success();
+ }
+
+ private Map formatToMap(NodeServer node) {
+ Server server = node.getServer();
+ Map rs = new LinkedHashMap<>();
+ String protocol = server.getNetprotocol();
+ if (node instanceof NodeSncpServer) {
+ protocol += "/SNCP";
+ } else if (node instanceof NodeWatchServer) {
+ protocol += "/WATCH";
+ } else if (node instanceof NodeHttpServer) {
+ protocol += "/HTTP";
+ } else {
+ NodeProtocol np = node.getClass().getAnnotation(NodeProtocol.class);
+ protocol += "/" + np.value();
+ }
+ rs.put("name", server.getName());
+ rs.put("protocol", protocol);
+ rs.put("address", server.getSocketAddress());
+ rs.put("backlog", server.getBacklog());
+ rs.put("bufferCapacity", server.getBufferCapacity());
+ rs.put("bufferPoolSize", server.getBufferPoolSize());
+ rs.put("charset", server.getCharset() == null ? "UTF-8" : server.getCharset().name());
+ rs.put("maxbody", server.getMaxbody());
+ rs.put("maxconns", server.getMaxconns());
+ rs.put("serverStartTime", server.getServerStartTime());
+ rs.put("responsePoolSize", server.getResponsePoolSize());
+ rs.put("readTimeoutSeconds", server.getReadTimeoutSeconds());
+ rs.put("writeTimeoutSeconds", server.getWriteTimeoutSeconds());
+ rs.put("createConnectionCount", server.getCreateConnectionCount());
+ rs.put("livingConnectionCount", server.getLivingConnectionCount());
+ rs.put("closedConnectionCount", server.getClosedConnectionCount());
+ return rs;
+ }
+}
diff --git a/src/main/java/org/redkale/boot/watch/ServiceWatchService.java b/src/main/java/org/redkale/boot/watch/ServiceWatchService.java
index 27fe661a8..4872d0f79 100644
--- a/src/main/java/org/redkale/boot/watch/ServiceWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/ServiceWatchService.java
@@ -1,199 +1,199 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import java.lang.reflect.*;
-import java.util.*;
-import javax.annotation.Resource;
-import org.redkale.boot.*;
-import org.redkale.convert.json.JsonConvert;
-import org.redkale.net.http.*;
-import org.redkale.service.RetResult;
-import org.redkale.util.*;
-
-/**
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-@RestService(name = "service", catalog = "watch", repair = false)
-public class ServiceWatchService extends AbstractWatchService {
-
- @Comment("娌℃湁鎵惧埌鐩爣Service")
- public static final int RET_SERVICE_DEST_NOT_EXISTS = 1603_0001;
-
- @Resource
- protected Application application;
-
- @RestConvert(type = void.class)
- @RestMapping(name = "setField", auth = false, comment = "璁剧疆Service涓寚瀹氬瓧娈电殑鍐呭")
- public RetResult setField(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
- @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 = "";
- 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`");
- Object dest = findService(name, type);
- Class clazz = dest.getClass();
- Throwable t = null;
- try {
- Field fieldObj = null;
- do {
- try {
- fieldObj = clazz.getDeclaredField(field);
- break;
- } catch (Exception 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) + ")");
- fieldObj.setAccessible(true);
- fieldObj.set(dest, JsonConvert.root().convertFrom(fieldObj.getGenericType(), value));
- return RetResult.success();
- } catch (Throwable t2) {
- return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
- }
- }
-
- @RestConvert(type = void.class)
- @RestMapping(name = "getField", auth = false, comment = "鏌ヨService涓寚瀹氬瓧娈电殑鍐呭")
- 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 = "";
- 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`");
- Object dest = findService(name, type);
- Class clazz = dest.getClass();
- Throwable t = null;
- try {
- Field fieldObj = null;
- do {
- try {
- fieldObj = clazz.getDeclaredField(field);
- break;
- } catch (Exception 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) + ")");
- fieldObj.setAccessible(true);
- return new RetResult(fieldObj.get(dest));
- } catch (Throwable t2) {
- return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
- }
- }
-
- @RestConvert(type = void.class)
- @RestMapping(name = "runMethod", auth = false, comment = "璋冪敤Service涓寚瀹氭柟娉")
- public RetResult runMethod(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
- @RestParam(name = "type", comment = "Service鐨勭被鍚") String type,
- @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 = "";
- 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`");
- 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");
- try {
- Method methodObj = null;
- do {
- try {
- for (Method m : clazz.getDeclaredMethods()) {
- if (m.getName().equals(method) && m.getParameterCount() == paramcount) {
- boolean flag = true;
- if (paramtypes != null) {
- Class[] pts = m.getParameterTypes();
- for (int i = 0; i < pts.length; i++) {
- if (!pts[i].getName().endsWith(paramtypes.get(i))) {
- flag = false;
- break;
- }
- }
- }
- if (flag) {
- methodObj = m;
- break;
- }
- }
- }
- if (methodObj != null) break;
- } catch (Exception 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)) + ")");
- methodObj.setAccessible(true);
- 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++) {
- paramObjs[i] = JsonConvert.root().convertFrom(pts[i], params.get(i));
- }
- return new RetResult(methodObj.invoke(dest, paramObjs));
- } catch (Throwable t2) {
- return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
- }
- }
-
- protected Object findService(String name, String type) {
- Object dest = null;
- 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;
- dest = list.get(0);
- }
- if (dest == null) return new RetResult(RET_SERVICE_DEST_NOT_EXISTS, "not found servie (name=" + name + ", type=" + type + ")");
- return dest;
- }
-
- @RestMapping(name = "loadService", auth = false, comment = "鍔ㄦ佸鍔燬ervice")
- public RetResult loadService(@RestParam(name = "type", comment = "Service鐨勭被鍚") String type,
- @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.jar$") byte[] jar) {
- //寰呭紑鍙
- return RetResult.success();
- }
-
- @RestMapping(name = "reloadService", auth = false, comment = "閲嶆柊鍔犺浇Service")
- public RetResult reloadService(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
- @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
- //寰呭紑鍙
- return RetResult.success();
- }
-
- @RestMapping(name = "stopService", auth = false, comment = "鍔ㄦ佸仠姝ervice")
- public RetResult stopService(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
- @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
- //寰呭紑鍙
- return RetResult.success();
- }
-
- @RestMapping(name = "findService", auth = false, comment = "鏌ユ壘Service")
- public RetResult find(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
- @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
- //寰呭紑鍙
- return RetResult.success();
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import java.lang.reflect.*;
+import java.util.*;
+import javax.annotation.Resource;
+import org.redkale.boot.*;
+import org.redkale.convert.json.JsonConvert;
+import org.redkale.net.http.*;
+import org.redkale.service.RetResult;
+import org.redkale.util.*;
+
+/**
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+@RestService(name = "service", catalog = "watch", repair = false)
+public class ServiceWatchService extends AbstractWatchService {
+
+ @Comment("娌℃湁鎵惧埌鐩爣Service")
+ public static final int RET_SERVICE_DEST_NOT_EXISTS = 1603_0001;
+
+ @Resource
+ protected Application application;
+
+ @RestConvert(type = void.class)
+ @RestMapping(name = "setField", auth = false, comment = "璁剧疆Service涓寚瀹氬瓧娈电殑鍐呭")
+ public RetResult setField(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
+ @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 = "";
+ 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`");
+ Object dest = findService(name, type);
+ Class clazz = dest.getClass();
+ Throwable t = null;
+ try {
+ Field fieldObj = null;
+ do {
+ try {
+ fieldObj = clazz.getDeclaredField(field);
+ break;
+ } catch (Exception 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) + ")");
+ fieldObj.setAccessible(true);
+ fieldObj.set(dest, JsonConvert.root().convertFrom(fieldObj.getGenericType(), value));
+ return RetResult.success();
+ } catch (Throwable t2) {
+ return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
+ }
+ }
+
+ @RestConvert(type = void.class)
+ @RestMapping(name = "getField", auth = false, comment = "鏌ヨService涓寚瀹氬瓧娈电殑鍐呭")
+ 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 = "";
+ 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`");
+ Object dest = findService(name, type);
+ Class clazz = dest.getClass();
+ Throwable t = null;
+ try {
+ Field fieldObj = null;
+ do {
+ try {
+ fieldObj = clazz.getDeclaredField(field);
+ break;
+ } catch (Exception 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) + ")");
+ fieldObj.setAccessible(true);
+ return new RetResult(fieldObj.get(dest));
+ } catch (Throwable t2) {
+ return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
+ }
+ }
+
+ @RestConvert(type = void.class)
+ @RestMapping(name = "runMethod", auth = false, comment = "璋冪敤Service涓寚瀹氭柟娉")
+ public RetResult runMethod(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
+ @RestParam(name = "type", comment = "Service鐨勭被鍚") String type,
+ @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 = "";
+ 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`");
+ 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");
+ try {
+ Method methodObj = null;
+ do {
+ try {
+ for (Method m : clazz.getDeclaredMethods()) {
+ if (m.getName().equals(method) && m.getParameterCount() == paramcount) {
+ boolean flag = true;
+ if (paramtypes != null) {
+ Class[] pts = m.getParameterTypes();
+ for (int i = 0; i < pts.length; i++) {
+ if (!pts[i].getName().endsWith(paramtypes.get(i))) {
+ flag = false;
+ break;
+ }
+ }
+ }
+ if (flag) {
+ methodObj = m;
+ break;
+ }
+ }
+ }
+ if (methodObj != null) break;
+ } catch (Exception 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)) + ")");
+ methodObj.setAccessible(true);
+ 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++) {
+ paramObjs[i] = JsonConvert.root().convertFrom(pts[i], params.get(i));
+ }
+ return new RetResult(methodObj.invoke(dest, paramObjs));
+ } catch (Throwable t2) {
+ return new RetResult(RET_WATCH_RUN_EXCEPTION, "run exception (" + t2.toString() + ")");
+ }
+ }
+
+ protected Object findService(String name, String type) {
+ Object dest = null;
+ 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;
+ dest = list.get(0);
+ }
+ if (dest == null) return new RetResult(RET_SERVICE_DEST_NOT_EXISTS, "not found servie (name=" + name + ", type=" + type + ")");
+ return dest;
+ }
+
+ @RestMapping(name = "loadService", auth = false, comment = "鍔ㄦ佸鍔燬ervice")
+ public RetResult loadService(@RestParam(name = "type", comment = "Service鐨勭被鍚") String type,
+ @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.jar$") byte[] jar) {
+ //寰呭紑鍙
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "reloadService", auth = false, comment = "閲嶆柊鍔犺浇Service")
+ public RetResult reloadService(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
+ @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
+ //寰呭紑鍙
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "stopService", auth = false, comment = "鍔ㄦ佸仠姝ervice")
+ public RetResult stopService(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
+ @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
+ //寰呭紑鍙
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "findService", auth = false, comment = "鏌ユ壘Service")
+ public RetResult find(@RestParam(name = "name", comment = "Service鐨勮祫婧愬悕") String name,
+ @RestParam(name = "type", comment = "Service鐨勭被鍚") String type) {
+ //寰呭紑鍙
+ return RetResult.success();
+ }
+}
diff --git a/src/main/java/org/redkale/boot/watch/ServletWatchService.java b/src/main/java/org/redkale/boot/watch/ServletWatchService.java
index 53bf28a3b..1b7fa095c 100644
--- a/src/main/java/org/redkale/boot/watch/ServletWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/ServletWatchService.java
@@ -1,39 +1,39 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import javax.annotation.Resource;
-import org.redkale.boot.Application;
-import org.redkale.net.TransportFactory;
-import org.redkale.net.http.*;
-
-/**
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- */
-@RestService(name = "servlet", catalog = "watch", repair = false)
-public class ServletWatchService extends AbstractWatchService {
-
- @Resource
- protected Application application;
-
- @Resource
- protected TransportFactory transportFactory;
-//
-// @RestMapping(name = "loadServlet", auth = false, comment = "鍔ㄦ佸鍔燬ervlet")
-// public RetResult loadServlet(String type, @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.jar$") byte[] jar) {
-// //寰呭紑鍙
-// return RetResult.success();
-// }
-//
-// @RestMapping(name = "stopServlet", auth = false, comment = "鍔ㄦ佸仠姝ervlet")
-// public RetResult stopServlet(String type) {
-// //寰呭紑鍙
-// return RetResult.success();
-// }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import javax.annotation.Resource;
+import org.redkale.boot.Application;
+import org.redkale.net.TransportFactory;
+import org.redkale.net.http.*;
+
+/**
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ */
+@RestService(name = "servlet", catalog = "watch", repair = false)
+public class ServletWatchService extends AbstractWatchService {
+
+ @Resource
+ protected Application application;
+
+ @Resource
+ protected TransportFactory transportFactory;
+//
+// @RestMapping(name = "loadServlet", auth = false, comment = "鍔ㄦ佸鍔燬ervlet")
+// public RetResult loadServlet(String type, @RestUploadFile(maxLength = 10 * 1024 * 1024, fileNameReg = "\\.jar$") byte[] jar) {
+// //寰呭紑鍙
+// return RetResult.success();
+// }
+//
+// @RestMapping(name = "stopServlet", auth = false, comment = "鍔ㄦ佸仠姝ervlet")
+// public RetResult stopServlet(String type) {
+// //寰呭紑鍙
+// return RetResult.success();
+// }
+}
diff --git a/src/main/java/org/redkale/boot/watch/TransportWatchService.java b/src/main/java/org/redkale/boot/watch/TransportWatchService.java
index 9fad7757c..c849c94ac 100644
--- a/src/main/java/org/redkale/boot/watch/TransportWatchService.java
+++ b/src/main/java/org/redkale/boot/watch/TransportWatchService.java
@@ -1,140 +1,140 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.boot.watch;
-
-import java.io.IOException;
-import java.net.*;
-import java.nio.channels.AsynchronousSocketChannel;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import javax.annotation.Resource;
-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.DefaultAnyValue;
-
-/**
- *
- * @author zhangjx
- */
-@RestService(name = "transport", catalog = "watch", repair = false)
-public class TransportWatchService extends AbstractWatchService {
-
- @Comment("涓嶅瓨鍦ㄧ殑Group鑺傜偣")
- public static final int RET_TRANSPORT_GROUP_NOT_EXISTS = 1606_0001;
-
- @Comment("闈炴硶鐨凬ode鑺傜偣IP鍦板潃")
- public static final int RET_TRANSPORT_ADDR_ILLEGAL = 1606_0002;
-
- @Comment("Node鑺傜偣IP鍦板潃宸插瓨鍦")
- public static final int RET_TRANSPORT_ADDR_EXISTS = 1606_0003;
-
- @Resource
- protected Application application;
-
- @Resource
- protected TransportFactory transportFactory;
-
- @RestMapping(name = "listnodes", auth = false, comment = "鑾峰彇鎵鏈塏ode鑺傜偣")
- public List listNodes() {
- return transportFactory.getGroupInfos();
- }
-
- @RestMapping(name = "addnode", auth = false, comment = "鍔ㄦ佸鍔犳寚瀹欸roup鐨凬ode鑺傜偣")
- public RetResult addNode(@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 {
- InetSocketAddress address;
- try {
- address = new InetSocketAddress(addr, port);
- AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
- channel.connect(address).get(2, TimeUnit.SECONDS); //杩炴帴瓒呮椂2绉
- channel.close();
- } 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");
- 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;
- SncpClient client = Sncp.getSncpClient(service);
- if (Sncp.isRemote(service)) {
- if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
- client.getRemoteGroupTransport().addRemoteAddresses(address);
- }
- }
- }
- DefaultAnyValue node = DefaultAnyValue.create("addr", addr).addValue("port", port);
- for (AnyValue groupconf : application.getAppConfig().getAnyValue("resources").getAnyValues("group")) {
- if (group.equals(groupconf.getValue("name"))) {
- ((DefaultAnyValue) groupconf).addValue("node", node);
- break;
- }
- }
- //application.restoreConfig();
- }
- return RetResult.success();
- }
-
- @RestMapping(name = "removenode", auth = false, comment = "鍔ㄦ佸垹闄ゆ寚瀹欸roup鐨凬ode鑺傜偣")
- 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 + ")");
- 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 + ")");
- 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;
- SncpClient client = Sncp.getSncpClient(service);
- if (Sncp.isRemote(service)) {
- if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
- client.getRemoteGroupTransport().removeRemoteAddresses(address);
- }
- }
- }
- for (AnyValue groupconf : application.getAppConfig().getAnyValue("resources").getAnyValues("group")) {
- if (group.equals(groupconf.getValue("name"))) {
- ((DefaultAnyValue) groupconf).removeValue("node", DefaultAnyValue.create("addr", addr).addValue("port", port));
- break;
- }
- }
- //application.restoreConfig();
- }
- return RetResult.success();
- }
-
- @RestMapping(name = "test1", auth = false, comment = "棰勭暀")
- public RetResult test1() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test2", auth = false, comment = "棰勭暀")
- public RetResult test2() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test3", auth = false, comment = "棰勭暀")
- public RetResult test3() {
- return RetResult.success();
- }
-
- @RestMapping(name = "test4", auth = false, comment = "棰勭暀")
- public RetResult test4() {
- return RetResult.success();
- }
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.boot.watch;
+
+import java.io.IOException;
+import java.net.*;
+import java.nio.channels.AsynchronousSocketChannel;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Resource;
+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.DefaultAnyValue;
+
+/**
+ *
+ * @author zhangjx
+ */
+@RestService(name = "transport", catalog = "watch", repair = false)
+public class TransportWatchService extends AbstractWatchService {
+
+ @Comment("涓嶅瓨鍦ㄧ殑Group鑺傜偣")
+ public static final int RET_TRANSPORT_GROUP_NOT_EXISTS = 1606_0001;
+
+ @Comment("闈炴硶鐨凬ode鑺傜偣IP鍦板潃")
+ public static final int RET_TRANSPORT_ADDR_ILLEGAL = 1606_0002;
+
+ @Comment("Node鑺傜偣IP鍦板潃宸插瓨鍦")
+ public static final int RET_TRANSPORT_ADDR_EXISTS = 1606_0003;
+
+ @Resource
+ protected Application application;
+
+ @Resource
+ protected TransportFactory transportFactory;
+
+ @RestMapping(name = "listnodes", auth = false, comment = "鑾峰彇鎵鏈塏ode鑺傜偣")
+ public List listNodes() {
+ return transportFactory.getGroupInfos();
+ }
+
+ @RestMapping(name = "addnode", auth = false, comment = "鍔ㄦ佸鍔犳寚瀹欸roup鐨凬ode鑺傜偣")
+ public RetResult addNode(@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 {
+ InetSocketAddress address;
+ try {
+ address = new InetSocketAddress(addr, port);
+ AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
+ channel.connect(address).get(2, TimeUnit.SECONDS); //杩炴帴瓒呮椂2绉
+ channel.close();
+ } 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");
+ 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;
+ SncpClient client = Sncp.getSncpClient(service);
+ if (Sncp.isRemote(service)) {
+ if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
+ client.getRemoteGroupTransport().addRemoteAddresses(address);
+ }
+ }
+ }
+ DefaultAnyValue node = DefaultAnyValue.create("addr", addr).addValue("port", port);
+ for (AnyValue groupconf : application.getAppConfig().getAnyValue("resources").getAnyValues("group")) {
+ if (group.equals(groupconf.getValue("name"))) {
+ ((DefaultAnyValue) groupconf).addValue("node", node);
+ break;
+ }
+ }
+ //application.restoreConfig();
+ }
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "removenode", auth = false, comment = "鍔ㄦ佸垹闄ゆ寚瀹欸roup鐨凬ode鑺傜偣")
+ 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 + ")");
+ 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 + ")");
+ 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;
+ SncpClient client = Sncp.getSncpClient(service);
+ if (Sncp.isRemote(service)) {
+ if (client.getRemoteGroups() != null && client.getRemoteGroups().contains(group)) {
+ client.getRemoteGroupTransport().removeRemoteAddresses(address);
+ }
+ }
+ }
+ for (AnyValue groupconf : application.getAppConfig().getAnyValue("resources").getAnyValues("group")) {
+ if (group.equals(groupconf.getValue("name"))) {
+ ((DefaultAnyValue) groupconf).removeValue("node", DefaultAnyValue.create("addr", addr).addValue("port", port));
+ break;
+ }
+ }
+ //application.restoreConfig();
+ }
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test1", auth = false, comment = "棰勭暀")
+ public RetResult test1() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test2", auth = false, comment = "棰勭暀")
+ public RetResult test2() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test3", auth = false, comment = "棰勭暀")
+ public RetResult test3() {
+ return RetResult.success();
+ }
+
+ @RestMapping(name = "test4", auth = false, comment = "棰勭暀")
+ public RetResult test4() {
+ return RetResult.success();
+ }
+}
diff --git a/src/main/java/org/redkale/cluster/CacheClusterAgent.java b/src/main/java/org/redkale/cluster/CacheClusterAgent.java
index aafdc0ae3..9dcc2bfb9 100644
--- a/src/main/java/org/redkale/cluster/CacheClusterAgent.java
+++ b/src/main/java/org/redkale/cluster/CacheClusterAgent.java
@@ -1,327 +1,327 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.cluster;
-
-import java.net.*;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.logging.Level;
-import javax.annotation.Resource;
-import org.redkale.boot.*;
-import org.redkale.convert.json.JsonConvert;
-import org.redkale.service.Service;
-import org.redkale.source.CacheSource;
-import org.redkale.util.*;
-
-/**
- * 浣跨敤CacheSource瀹炵幇鐨勭涓夋柟鏈嶅姟鍙戠幇绠$悊鎺ュ彛cluster
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- *
- * @since 2.3.0
- */
-public class CacheClusterAgent extends ClusterAgent implements Resourcable {
-
- @Resource(name = "$")
- private CacheSource source;
-
- private String sourceName;
-
- protected int ttls = 10; //瀹氭椂妫鏌ョ殑绉掓暟
-
- protected ScheduledThreadPoolExecutor scheduler;
-
- //鍙兘琚獺ttpMessageClient鐢ㄥ埌鐨勬湇鍔 key: servicename
- protected final ConcurrentHashMap> httpAddressMap = new ConcurrentHashMap<>();
-
- //鍙兘琚玬qtp鐢ㄥ埌鐨勬湇鍔 key: servicename
- protected final ConcurrentHashMap> mqtpAddressMap = new ConcurrentHashMap<>();
-
- @Override
- public void init(AnyValue config) {
- super.init(config);
- this.sourceName = getSourceName();
-
- AnyValue[] properties = config.getAnyValues("property");
- for (AnyValue property : properties) {
- if ("ttls".equalsIgnoreCase(property.getValue("name"))) {
- this.ttls = Integer.parseInt(property.getValue("value", "").trim());
- if (this.ttls < 5) this.ttls = 10;
- }
- }
- }
-
- @Override
- public void destroy(AnyValue config) {
- if (scheduler != null) scheduler.shutdownNow();
- }
-
- public String getSourceName() {
- AnyValue[] properties = config.getAnyValues("property");
- for (AnyValue property : properties) {
- if ("source".equalsIgnoreCase(property.getValue("name"))
- && property.getValue("value") != null) {
- this.sourceName = property.getValue("value");
- return this.sourceName;
- }
- }
- return null;
- }
-
- @Override
- public String resourceName() {
- return sourceName;
- }
-
- @Override //ServiceLoader鏃跺垽鏂厤缃槸鍚︾鍚堝綋鍓嶅疄鐜扮被
- public boolean acceptsConf(AnyValue config) {
- if (config == null) return false;
- AnyValue[] properties = config.getAnyValues("property");
- if (properties == null || properties.length == 0) return false;
- for (AnyValue property : properties) {
- if ("source".equalsIgnoreCase(property.getValue("name"))
- && property.getValue("value") != null) return true;
- }
- return false;
- }
-
- @Override
- public void start() {
- if (this.scheduler == null) {
- this.scheduler = new ScheduledThreadPoolExecutor(4, (Runnable r) -> {
- final Thread t = new Thread(r, "Redkale-" + CacheClusterAgent.class.getSimpleName() + "-Task-Thread");
- t.setDaemon(true);
- return t;
- });
-
- this.scheduler.scheduleAtFixedRate(() -> {
- try {
- checkApplicationHealth();
- checkHttpAddressHealth();
- loadMqtpAddressHealth();
- localEntrys.values().stream().filter(e -> !e.canceled).forEach(entry -> {
- checkLocalHealth(entry);
- });
- remoteEntrys.values().stream().filter(entry -> "SNCP".equalsIgnoreCase(entry.protocol)).forEach(entry -> {
- updateSncpTransport(entry);
- });
- } catch (Exception e) {
- logger.log(Level.SEVERE, "scheduleAtFixedRate check error", e);
- }
- }, Math.max(2000, ttls * 1000), Math.max(2000, ttls * 1000), TimeUnit.MILLISECONDS);
- }
- }
-
- protected void loadMqtpAddressHealth() {
- List keys = source.queryKeysStartsWith("cluster.mqtp:");
- keys.forEach(servicename -> {
- try {
- this.mqtpAddressMap.put(servicename, queryAddress(servicename).get(3, TimeUnit.SECONDS));
- } catch (Exception e) {
- logger.log(Level.SEVERE, "loadMqtpAddressHealth check " + servicename + " error", e);
- }
- });
- }
-
- protected void checkHttpAddressHealth() {
- try {
- this.httpAddressMap.keySet().stream().forEach(servicename -> {
- try {
- this.httpAddressMap.put(servicename, queryAddress(servicename).get(3, TimeUnit.SECONDS));
- } catch (Exception e) {
- logger.log(Level.SEVERE, "checkHttpAddressHealth check " + servicename + " error", e);
- }
- });
- } catch (Exception ex) {
- logger.log(Level.SEVERE, "checkHttpAddressHealth check error", ex);
- }
- }
-
- protected void checkLocalHealth(final ClusterEntry entry) {
- AddressEntry newaddr = new AddressEntry();
- newaddr.addr = entry.address;
- newaddr.nodeid = this.nodeid;
- newaddr.time = System.currentTimeMillis();
- source.hset(entry.checkname, entry.checkid, AddressEntry.class, newaddr);
- }
-
- @Override //鑾峰彇MQTP鐨凥TTP杩滅▼鏈嶅姟鐨勫彲鐢╥p鍒楄〃, key = servicename鐨勫悗鍗婃
- public CompletableFuture>> queryMqtpAddress(String protocol, String module, String resname) {
- final Map> rsmap = new ConcurrentHashMap<>();
- final String servicenamprefix = generateHttpServiceName(protocol, module, null) + ":";
- mqtpAddressMap.keySet().stream().filter(k -> k.startsWith(servicenamprefix))
- .forEach(sn -> rsmap.put(sn.substring(servicenamprefix.length()), mqtpAddressMap.get(sn)));
- return CompletableFuture.completedFuture(rsmap);
- }
-
- @Override //鑾峰彇HTTP杩滅▼鏈嶅姟鐨勫彲鐢╥p鍒楄〃
- 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);
- return queryAddress(servicename).thenApply(t -> {
- httpAddressMap.put(servicename, t);
- return t;
- });
- }
-
- @Override
- protected CompletableFuture> queryAddress(final ClusterEntry entry) {
- return queryAddress(entry.servicename);
- }
-
- private CompletableFuture> queryAddress(final String servicename) {
- final CompletableFuture> future = source.hmapAsync(servicename, AddressEntry.class, 0, 10000);
- 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);
- });
- return set;
- });
- }
-
- protected boolean isApplicationHealth() {
- String servicename = generateApplicationServiceName();
- String serviceid = generateApplicationServiceId();
- AddressEntry entry = (AddressEntry) source.hget(servicename, serviceid, AddressEntry.class);
- return entry != null && (System.currentTimeMillis() - entry.time) / 1000 < ttls;
- }
-
- protected void checkApplicationHealth() {
- String checkname = generateApplicationServiceName();
- String checkid = generateApplicationCheckId();
- AddressEntry entry = new AddressEntry();
- entry.addr = this.appAddress;
- entry.nodeid = this.nodeid;
- entry.time = System.currentTimeMillis();
- source.hset(checkname, checkid, AddressEntry.class, entry);
- }
-
- @Override
- public void register(Application application) {
- if (isApplicationHealth()) throw new RuntimeException("application.nodeid=" + nodeid + " exists in cluster");
- deregister(application);
-
- String serviceid = generateApplicationServiceId();
- String servicename = generateApplicationServiceName();
- AddressEntry entry = new AddressEntry();
- entry.addr = this.appAddress;
- entry.nodeid = this.nodeid;
- entry.time = System.currentTimeMillis();
- source.hset(servicename, serviceid, AddressEntry.class, entry);
- }
-
- @Override
- public void deregister(Application application) {
- String servicename = generateApplicationServiceName();
- source.remove(servicename);
- }
-
- @Override
- protected ClusterEntry register(NodeServer ns, String protocol, Service service) {
- deregister(ns, protocol, service, false);
- //
- ClusterEntry clusterEntry = new ClusterEntry(ns, protocol, service);
- AddressEntry entry = new AddressEntry();
- entry.addr = clusterEntry.address;
- entry.nodeid = this.nodeid;
- entry.time = System.currentTimeMillis();
- source.hset(clusterEntry.servicename, clusterEntry.serviceid, AddressEntry.class, entry);
- return clusterEntry;
- }
-
- @Override
- protected void deregister(NodeServer ns, String protocol, Service service) {
- deregister(ns, protocol, service, true);
- }
-
- protected void deregister(NodeServer ns, String protocol, Service service, boolean realcanceled) {
- String servicename = generateServiceName(ns, protocol, service);
- String serviceid = generateServiceId(ns, protocol, service);
- ClusterEntry currEntry = null;
- for (final ClusterEntry entry : localEntrys.values()) {
- if (entry.servicename.equals(servicename) && entry.serviceid.equals(serviceid)) {
- currEntry = entry;
- break;
- }
- }
- if (currEntry == null) {
- for (final ClusterEntry entry : remoteEntrys.values()) {
- if (entry.servicename.equals(servicename) && entry.serviceid.equals(serviceid)) {
- currEntry = entry;
- break;
- }
- }
- }
- source.hremove(servicename, serviceid);
- if (realcanceled && currEntry != null) currEntry.canceled = true;
- if (!"mqtp".equals(protocol) && currEntry != null && currEntry.submqtp) {
- deregister(ns, "mqtp", service, realcanceled);
- }
- }
-
- @Override
- protected String generateApplicationServiceName() {
- return "cluster." + super.generateApplicationServiceName();
- }
-
- @Override
- protected String generateServiceName(NodeServer ns, String protocol, Service service) {
- return "cluster." + super.generateServiceName(ns, protocol, service);
- }
-
- @Override
- public String generateHttpServiceName(String protocol, String module, String resname) {
- return "cluster." + super.generateHttpServiceName(protocol, module, resname);
- }
-
- @Override
- protected String generateApplicationCheckName() {
- return generateApplicationServiceName();
- }
-
- @Override
- protected String generateApplicationCheckId() {
- return generateApplicationServiceId();
- }
-
- @Override
- protected String generateCheckName(NodeServer ns, String protocol, Service service) {
- return generateServiceName(ns, protocol, service);
- }
-
- @Override
- protected String generateCheckId(NodeServer ns, String protocol, Service service) {
- return generateServiceId(ns, protocol, service);
- }
-
- public static class AddressEntry {
-
- public InetSocketAddress addr;
-
- public int nodeid;
-
- public long time;
-
- public AddressEntry() {
- }
-
- public AddressEntry refresh() {
- this.time = System.currentTimeMillis();
- return this;
- }
-
- @Override
- public String toString() {
- return JsonConvert.root().convertTo(this);
- }
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package org.redkale.cluster;
+
+import java.net.*;
+import java.util.*;
+import java.util.concurrent.*;
+import java.util.logging.Level;
+import javax.annotation.Resource;
+import org.redkale.boot.*;
+import org.redkale.convert.json.JsonConvert;
+import org.redkale.service.Service;
+import org.redkale.source.CacheSource;
+import org.redkale.util.*;
+
+/**
+ * 浣跨敤CacheSource瀹炵幇鐨勭涓夋柟鏈嶅姟鍙戠幇绠$悊鎺ュ彛cluster
+ *
+ *
+ * 璇︽儏瑙: https://redkale.org
+ *
+ * @author zhangjx
+ *
+ * @since 2.3.0
+ */
+public class CacheClusterAgent extends ClusterAgent implements Resourcable {
+
+ @Resource(name = "$")
+ private CacheSource source;
+
+ private String sourceName;
+
+ protected int ttls = 10; //瀹氭椂妫鏌ョ殑绉掓暟
+
+ protected ScheduledThreadPoolExecutor scheduler;
+
+ //鍙兘琚獺ttpMessageClient鐢ㄥ埌鐨勬湇鍔 key: servicename
+ protected final ConcurrentHashMap> httpAddressMap = new ConcurrentHashMap<>();
+
+ //鍙兘琚玬qtp鐢ㄥ埌鐨勬湇鍔 key: servicename
+ protected final ConcurrentHashMap> mqtpAddressMap = new ConcurrentHashMap<>();
+
+ @Override
+ public void init(AnyValue config) {
+ super.init(config);
+ this.sourceName = getSourceName();
+
+ AnyValue[] properties = config.getAnyValues("property");
+ for (AnyValue property : properties) {
+ if ("ttls".equalsIgnoreCase(property.getValue("name"))) {
+ this.ttls = Integer.parseInt(property.getValue("value", "").trim());
+ if (this.ttls < 5) this.ttls = 10;
+ }
+ }
+ }
+
+ @Override
+ public void destroy(AnyValue config) {
+ if (scheduler != null) scheduler.shutdownNow();
+ }
+
+ public String getSourceName() {
+ AnyValue[] properties = config.getAnyValues("property");
+ for (AnyValue property : properties) {
+ if ("source".equalsIgnoreCase(property.getValue("name"))
+ && property.getValue("value") != null) {
+ this.sourceName = property.getValue("value");
+ return this.sourceName;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String resourceName() {
+ return sourceName;
+ }
+
+ @Override //ServiceLoader鏃跺垽鏂厤缃槸鍚︾鍚堝綋鍓嶅疄鐜扮被
+ public boolean acceptsConf(AnyValue config) {
+ if (config == null) return false;
+ AnyValue[] properties = config.getAnyValues("property");
+ if (properties == null || properties.length == 0) return false;
+ for (AnyValue property : properties) {
+ if ("source".equalsIgnoreCase(property.getValue("name"))
+ && property.getValue("value") != null) return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void start() {
+ if (this.scheduler == null) {
+ this.scheduler = new ScheduledThreadPoolExecutor(4, (Runnable r) -> {
+ final Thread t = new Thread(r, "Redkale-" + CacheClusterAgent.class.getSimpleName() + "-Task-Thread");
+ t.setDaemon(true);
+ return t;
+ });
+
+ this.scheduler.scheduleAtFixedRate(() -> {
+ try {
+ checkApplicationHealth();
+ checkHttpAddressHealth();
+ loadMqtpAddressHealth();
+ localEntrys.values().stream().filter(e -> !e.canceled).forEach(entry -> {
+ checkLocalHealth(entry);
+ });
+ remoteEntrys.values().stream().filter(entry -> "SNCP".equalsIgnoreCase(entry.protocol)).forEach(entry -> {
+ updateSncpTransport(entry);
+ });
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "scheduleAtFixedRate check error", e);
+ }
+ }, Math.max(2000, ttls * 1000), Math.max(2000, ttls * 1000), TimeUnit.MILLISECONDS);
+ }
+ }
+
+ protected void loadMqtpAddressHealth() {
+ List keys = source.queryKeysStartsWith("cluster.mqtp:");
+ keys.forEach(servicename -> {
+ try {
+ this.mqtpAddressMap.put(servicename, queryAddress(servicename).get(3, TimeUnit.SECONDS));
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "loadMqtpAddressHealth check " + servicename + " error", e);
+ }
+ });
+ }
+
+ protected void checkHttpAddressHealth() {
+ try {
+ this.httpAddressMap.keySet().stream().forEach(servicename -> {
+ try {
+ this.httpAddressMap.put(servicename, queryAddress(servicename).get(3, TimeUnit.SECONDS));
+ } catch (Exception e) {
+ logger.log(Level.SEVERE, "checkHttpAddressHealth check " + servicename + " error", e);
+ }
+ });
+ } catch (Exception ex) {
+ logger.log(Level.SEVERE, "checkHttpAddressHealth check error", ex);
+ }
+ }
+
+ protected void checkLocalHealth(final ClusterEntry entry) {
+ AddressEntry newaddr = new AddressEntry();
+ newaddr.addr = entry.address;
+ newaddr.nodeid = this.nodeid;
+ newaddr.time = System.currentTimeMillis();
+ source.hset(entry.checkname, entry.checkid, AddressEntry.class, newaddr);
+ }
+
+ @Override //鑾峰彇MQTP鐨凥TTP杩滅▼鏈嶅姟鐨勫彲鐢╥p鍒楄〃, key = servicename鐨勫悗鍗婃
+ public CompletableFuture>> queryMqtpAddress(String protocol, String module, String resname) {
+ final Map> rsmap = new ConcurrentHashMap<>();
+ final String servicenamprefix = generateHttpServiceName(protocol, module, null) + ":";
+ mqtpAddressMap.keySet().stream().filter(k -> k.startsWith(servicenamprefix))
+ .forEach(sn -> rsmap.put(sn.substring(servicenamprefix.length()), mqtpAddressMap.get(sn)));
+ return CompletableFuture.completedFuture(rsmap);
+ }
+
+ @Override //鑾峰彇HTTP杩滅▼鏈嶅姟鐨勫彲鐢╥p鍒楄〃
+ 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);
+ return queryAddress(servicename).thenApply(t -> {
+ httpAddressMap.put(servicename, t);
+ return t;
+ });
+ }
+
+ @Override
+ protected CompletableFuture> queryAddress(final ClusterEntry entry) {
+ return queryAddress(entry.servicename);
+ }
+
+ private CompletableFuture> queryAddress(final String servicename) {
+ final CompletableFuture> future = source.hmapAsync(servicename, AddressEntry.class, 0, 10000);
+ 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);
+ });
+ return set;
+ });
+ }
+
+ protected boolean isApplicationHealth() {
+ String servicename = generateApplicationServiceName();
+ String serviceid = generateApplicationServiceId();
+ AddressEntry entry = (AddressEntry) source.hget(servicename, serviceid, AddressEntry.class);
+ return entry != null && (System.currentTimeMillis() - entry.time) / 1000 < ttls;
+ }
+
+ protected void checkApplicationHealth() {
+ String checkname = generateApplicationServiceName();
+ String checkid = generateApplicationCheckId();
+ AddressEntry entry = new AddressEntry();
+ entry.addr = this.appAddress;
+ entry.nodeid = this.nodeid;
+ entry.time = System.currentTimeMillis();
+ source.hset(checkname, checkid, AddressEntry.class, entry);
+ }
+
+ @Override
+ public void register(Application application) {
+ if (isApplicationHealth()) throw new RuntimeException("application.nodeid=" + nodeid + " exists in cluster");
+ deregister(application);
+
+ String serviceid = generateApplicationServiceId();
+ String servicename = generateApplicationServiceName();
+ AddressEntry entry = new AddressEntry();
+ entry.addr = this.appAddress;
+ entry.nodeid = this.nodeid;
+ entry.time = System.currentTimeMillis();
+ source.hset(servicename, serviceid, AddressEntry.class, entry);
+ }
+
+ @Override
+ public void deregister(Application application) {
+ String servicename = generateApplicationServiceName();
+ source.remove(servicename);
+ }
+
+ @Override
+ protected ClusterEntry register(NodeServer ns, String protocol, Service service) {
+ deregister(ns, protocol, service, false);
+ //
+ ClusterEntry clusterEntry = new ClusterEntry(ns, protocol, service);
+ AddressEntry entry = new AddressEntry();
+ entry.addr = clusterEntry.address;
+ entry.nodeid = this.nodeid;
+ entry.time = System.currentTimeMillis();
+ source.hset(clusterEntry.servicename, clusterEntry.serviceid, AddressEntry.class, entry);
+ return clusterEntry;
+ }
+
+ @Override
+ protected void deregister(NodeServer ns, String protocol, Service service) {
+ deregister(ns, protocol, service, true);
+ }
+
+ protected void deregister(NodeServer ns, String protocol, Service service, boolean realcanceled) {
+ String servicename = generateServiceName(ns, protocol, service);
+ String serviceid = generateServiceId(ns, protocol, service);
+ ClusterEntry currEntry = null;
+ for (final ClusterEntry entry : localEntrys.values()) {
+ if (entry.servicename.equals(servicename) && entry.serviceid.equals(serviceid)) {
+ currEntry = entry;
+ break;
+ }
+ }
+ if (currEntry == null) {
+ for (final ClusterEntry entry : remoteEntrys.values()) {
+ if (entry.servicename.equals(servicename) && entry.serviceid.equals(serviceid)) {
+ currEntry = entry;
+ break;
+ }
+ }
+ }
+ source.hremove(servicename, serviceid);
+ if (realcanceled && currEntry != null) currEntry.canceled = true;
+ if (!"mqtp".equals(protocol) && currEntry != null && currEntry.submqtp) {
+ deregister(ns, "mqtp", service, realcanceled);
+ }
+ }
+
+ @Override
+ protected String generateApplicationServiceName() {
+ return "cluster." + super.generateApplicationServiceName();
+ }
+
+ @Override
+ protected String generateServiceName(NodeServer ns, String protocol, Service service) {
+ return "cluster." + super.generateServiceName(ns, protocol, service);
+ }
+
+ @Override
+ public String generateHttpServiceName(String protocol, String module, String resname) {
+ return "cluster." + super.generateHttpServiceName(protocol, module, resname);
+ }
+
+ @Override
+ protected String generateApplicationCheckName() {
+ return generateApplicationServiceName();
+ }
+
+ @Override
+ protected String generateApplicationCheckId() {
+ return generateApplicationServiceId();
+ }
+
+ @Override
+ protected String generateCheckName(NodeServer ns, String protocol, Service service) {
+ return generateServiceName(ns, protocol, service);
+ }
+
+ @Override
+ protected String generateCheckId(NodeServer ns, String protocol, Service service) {
+ return generateServiceId(ns, protocol, service);
+ }
+
+ public static class AddressEntry {
+
+ public InetSocketAddress addr;
+
+ public int nodeid;
+
+ public long time;
+
+ public AddressEntry() {
+ }
+
+ public AddressEntry refresh() {
+ this.time = System.currentTimeMillis();
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return JsonConvert.root().convertTo(this);
+ }
+ }
+
+}
diff --git a/src/main/java/org/redkale/cluster/ClusterAgent.java b/src/main/java/org/redkale/cluster/ClusterAgent.java
index 16991c165..d1af825d3 100644
--- a/src/main/java/org/redkale/cluster/ClusterAgent.java
+++ b/src/main/java/org/redkale/cluster/ClusterAgent.java
@@ -1,342 +1,342 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.redkale.cluster;
-
-import java.lang.ref.WeakReference;
-import java.net.InetSocketAddress;
-import java.util.*;
-import java.util.concurrent.*;
-import java.util.logging.Logger;
-import javax.annotation.Resource;
-import org.redkale.boot.*;
-import static org.redkale.boot.Application.*;
-import org.redkale.convert.json.JsonConvert;
-import org.redkale.mq.MessageMultiConsumer;
-import org.redkale.net.*;
-import org.redkale.net.http.*;
-import org.redkale.net.sncp.*;
-import org.redkale.service.*;
-import org.redkale.util.*;
-
-/**
- * 绗笁鏂规湇鍔″彂鐜扮鐞嗘帴鍙luster
- *
- *
- * 璇︽儏瑙: https://redkale.org
- *
- * @author zhangjx
- *
- * @since 2.1.0
- */
-public abstract class ClusterAgent {
-
- protected final Logger logger = Logger.getLogger(this.getClass().getSimpleName());
-
- @Resource(name = RESNAME_APP_NODEID)
- protected int nodeid;
-
- @Resource(name = RESNAME_APP_NAME)
- protected String appName = "";
-
- @Resource(name = RESNAME_APP_ADDR)
- protected InetSocketAddress appAddress;
-
- protected String name;
-
- protected boolean waits;
-
- protected String[] protocols; //蹇呴』鍏ㄥぇ鍐
-
- protected int[] ports;
-
- protected AnyValue config;
-
- protected TransportFactory transportFactory;
-
- protected final ConcurrentHashMap localEntrys = new ConcurrentHashMap<>();
-
- protected final ConcurrentHashMap remoteEntrys = new ConcurrentHashMap<>();
-
- public void init(AnyValue config) {
- this.config = config;
- this.name = config.getValue("name", "");
- this.waits = config.getBoolValue("waits", false);
- {
- String ps = config.getValue("protocols", "").toUpperCase();
- if (ps == null || ps.isEmpty()) ps = "SNCP;HTTP";
- this.protocols = ps.split(";");
- }
- String ts = config.getValue("ports", "");
- if (ts != null && !ts.isEmpty()) {
- String[] its = ts.split(";");
- List list = new ArrayList<>();
- for (String str : its) {
- if (str.trim().isEmpty()) continue;
- list.add(Integer.parseInt(str.trim()));
- }
- if (!list.isEmpty()) this.ports = list.stream().mapToInt(x -> x).toArray();
- }
- }
-
- public void destroy(AnyValue config) {
- }
-
- //ServiceLoader鏃跺垽鏂厤缃槸鍚︾鍚堝綋鍓嶅疄鐜扮被
- public abstract boolean acceptsConf(AnyValue config);
-
- public boolean containsProtocol(String protocol) {
- 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;
- return Utility.contains(ports, port);
- }
-
- public abstract void register(Application application);
-
- public abstract void deregister(Application application);
-
- //娉ㄥ唽鏈嶅姟, 鍦∟odeService璋冪敤Service.init鏂规硶涔嬪墠璋冪敤
- public void register(NodeServer ns, String protocol, Set localServices, Set remoteServices) {
- if (localServices.isEmpty()) return;
- //娉ㄥ唽鏈湴妯″紡
- for (Service service : localServices) {
- if (!canRegister(protocol, service)) continue;
- ClusterEntry htentry = register(ns, protocol, service);
- localEntrys.put(htentry.serviceid, htentry);
- if (protocol.toLowerCase().startsWith("http")) {
- MessageMultiConsumer mmc = service.getClass().getAnnotation(MessageMultiConsumer.class);
- if (mmc != null) {
- ClusterEntry mqentry = register(ns, "mqtp", service);
- localEntrys.put(mqentry.serviceid, mqentry);
- htentry.submqtp = true;
- }
- }
- }
- //杩滅▼妯″紡鍔犺浇IP鍒楄〃, 鍙敮鎸丼NCP鍗忚
- if (ns.isSNCP()) {
- for (Service service : remoteServices) {
- ClusterEntry entry = new ClusterEntry(ns, protocol, service);
- updateSncpTransport(entry);
- remoteEntrys.put(entry.serviceid, entry);
- }
- }
- }
-
- //娉ㄩ攢鏈嶅姟, 鍦∟odeService璋冪敤Service.destroy 鏂规硶涔嬪墠璋冪敤
- public void deregister(NodeServer ns, String protocol, Set